From b505f566adb6912e53886e8e6cc25ae9f8c82f87 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Feb 2023 10:26:18 +0000 Subject: [PATCH 01/81] (1) Remove PyTree. --- jaxutils/pytree.py | 76 -------------------------- tests/test_pytree.py | 124 ------------------------------------------- 2 files changed, 200 deletions(-) delete mode 100644 jaxutils/pytree.py delete mode 100644 tests/test_pytree.py diff --git a/jaxutils/pytree.py b/jaxutils/pytree.py deleted file mode 100644 index d6677b2..0000000 --- a/jaxutils/pytree.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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 abc -import jax - -from typing import Any - - -class PyTree(metaclass=abc.ABCMeta): - """An abstract base class for a JAX compatible pytree. Adapted from `distrax._src.utils.jittable.Jittable`.""" - - def __new__(cls, *args, **kwargs): - # Discard the parameters to this function because the constructor is not - # called during serialization: its `__dict__` gets repopulated directly. - del args, kwargs - try: - registered_cls = jax.tree_util.register_pytree_node_class(cls) - except ValueError: - registered_cls = cls # Already registered. - return object.__new__(registered_cls) - - def tree_flatten(self): - leaves, treedef = jax.tree_util.tree_flatten(self.__dict__) - switch = list(map(is_jax_type, leaves)) - children = [leaf if s else None for leaf, s in zip(leaves, switch)] - metadata = [None if s else leaf for leaf, s in zip(leaves, switch)] - return children, (metadata, switch, treedef) - - @classmethod - def tree_unflatten(cls, aux_data, children): - metadata, switch, treedef = aux_data - leaves = [j if s else p for j, p, s in zip(children, metadata, switch)] - obj = object.__new__(cls) - obj.__dict__ = jax.tree_util.tree_unflatten(treedef, leaves) - return obj - - -def is_jax_type(x: Any) -> bool: - """Check whether `x` is an instance of a JAX-compatible type.""" - # If it's a tracer, then it's already been converted by JAX. - if isinstance(x, jax.core.Tracer): - return True - - # `jax.vmap` replaces vmappable leaves with `object()` during serialization. - if type(x) is object: # pylint: disable=unidiomatic-typecheck - return True - - # Primitive types (e.g. shape tuples) are treated as metadata for Distrax. - if isinstance(x, (bool, int, float)) or x is None: - return False - - # Otherwise, try to make it into a tracer. If it succeeds, then it's JAX data. - try: - jax.xla.abstractify(x) - return True - except TypeError: - return False - - -__all__ = [ - "PyTree", - "is_jax_type", -] diff --git a/tests/test_pytree.py b/tests/test_pytree.py deleted file mode 100644 index 8efc699..0000000 --- a/tests/test_pytree.py +++ /dev/null @@ -1,124 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -"""Adapted from Distrax._src.utils.test_jittable.""" - -import pytest - -import jax -import jax.numpy as jnp -import numpy as np - -from typing import Any -from jaxtyping import Float, Array -from jaxutils import pytree - - -class DummyJittable(pytree.PyTree): - def __init__(self, values: Float[Array, "N"]): - self.name = "dummy" # Non-JAX property, cannot be traced. - self.data = {"params": values} # Tree property, must be traced recursively. - - -def test_jittable() -> None: - @jax.jit - def get_params(obj): - return obj.data["params"] - - obj = DummyJittable(jnp.ones((5,))) - np.testing.assert_array_equal(get_params(obj), obj.data["params"]) - - -def test_vmappable() -> None: - def do_sum(obj): - return obj.data["params"].sum() - - obj = DummyJittable(jnp.array([[1, 2, 3], [4, 5, 6]])) - - np.testing.assert_array_equal(do_sum(obj), obj.data["params"].sum()) - - np.testing.assert_array_equal( - jax.vmap(do_sum, in_axes=0)(obj), obj.data["params"].sum(axis=1) - ) - - np.testing.assert_array_equal( - jax.vmap(do_sum, in_axes=1)(obj), obj.data["params"].sum(axis=0) - ) - - -def test_traceable() -> None: - @jax.jit - def inner_fn(obj): - obj.data["params"] *= 3 # Modification after passing to jitted fn. - return obj.data["params"].sum() - - def loss_fn(params): - obj = DummyJittable(params) - obj.data["params"] *= 2 # Modification before passing to jitted fn. - return inner_fn(obj) - - params = np.ones((5,)) - # Both modifications will be traced if data tree is correctly traversed. - grad_expected = params * 2 * 3 - grad = jax.grad(loss_fn)(params) - np.testing.assert_array_equal(grad, grad_expected) - - params = jnp.ones((5,)) - # Both modifications will be traced if data tree is correctly traversed. - grad_expected = params * 2 * 3 - grad = jax.grad(loss_fn)(params) - np.testing.assert_array_equal(grad, grad_expected) - - -def test_different_jittables_to_compiled_function() -> None: - @jax.jit - def add_one_to_params(obj): - obj.data["params"] = obj.data["params"] + 1 - return obj - - add_one_to_params(DummyJittable(np.zeros((5,)))) - add_one_to_params(DummyJittable(np.ones((5,)))) - - add_one_to_params(DummyJittable(jnp.zeros((5,)))) - add_one_to_params(DummyJittable(jnp.ones((5,)))) - - -def test_modifying_object_data_does_not_leak_tracers() -> None: - @jax.jit - def add_one_to_params(obj): - obj.data["params"] = obj.data["params"] + 1 - return obj - - dummy = DummyJittable(jnp.ones((5,))) - dummy_out = add_one_to_params(dummy) - dummy_out.data["params"] -= 1 - - -def test_metadata_modification_statements_are_removed_by_compilation() -> None: - @jax.jit - def add_char_to_name(obj): - obj.name += "_x" - return obj - - dummy = DummyJittable(jnp.ones((5,))) - dummy_out = add_char_to_name(dummy) - dummy_out = add_char_to_name(dummy) # `name` change has been compiled out. - dummy_out.name += "y" - assert dummy_out.name == "dummy_xy" - - -@pytest.mark.parametrize("x", [1, 1.0, True, None]) -def test_is_jax_type(x: Any) -> None: - assert pytree.is_jax_type(x) == False From bdcfacbc7ae43fe9506abd9e1a81efc6e83a3970 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Feb 2023 10:30:14 +0000 Subject: [PATCH 02/81] remove `dict` --- jaxutils/data.py | 7 ++- jaxutils/dict.py | 105 --------------------------------------------- tests/test_dict.py | 67 ----------------------------- 3 files changed, 5 insertions(+), 174 deletions(-) delete mode 100644 jaxutils/dict.py delete mode 100644 tests/test_dict.py diff --git a/jaxutils/data.py b/jaxutils/data.py index 0a9747e..cdf6487 100644 --- a/jaxutils/data.py +++ b/jaxutils/data.py @@ -18,9 +18,12 @@ from jaxtyping import Array, Float from typing import Optional -from .pytree import PyTree +import equinox as eqx + +class Dataset(eqx.Module): + X: Optional[Float[Array, "N D"]] = None + y: Optional[Float[Array, "N Q"]] = None -class Dataset(PyTree): """Dataset class.""" #TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. diff --git a/jaxutils/dict.py b/jaxutils/dict.py deleted file mode 100644 index 9b71e80..0000000 --- a/jaxutils/dict.py +++ /dev/null @@ -1,105 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from typing import Callable, Dict, Tuple - -import jax - - -def concat_dictionaries(a: Dict, b: Dict) -> Dict: - """ - Append one dictionary below another. If duplicate keys exist, then the - key-value pair of the second supplied dictionary will be used. - - Args: - a (Dict): The first dictionary. - b (Dict): The second dictionary. - - Returns: - Dict: The merged dictionary. - """ - return {**a, **b} - - -def merge_dictionaries(base_dict: Dict, in_dict: Dict) -> Dict: - """ - This will return a complete dictionary based on the keys of the first - matrix. If the same key should exist in the second matrix, then the - key-value pair from the first dictionary will be overwritten. The purpose of - this is that the base_dict will be a complete dictionary of values such that - an incomplete second dictionary can be used to update specific key-value - pairs. - - Args: - base_dict (Dict): Complete dictionary of key-value pairs. - in_dict (Dict): Subset of key-values pairs such that values from this - dictionary will take precedent. - - Returns: - Dict: A dictionary with the same keys as the base_dict, but with - values from the in_dict. - """ - for k, _ in base_dict.items(): - if k in in_dict.keys(): - base_dict[k] = in_dict[k] - return base_dict - - -def sort_dictionary(base_dict: Dict) -> Dict: - """ - Sort a dictionary based on the dictionary's key values. - - Args: - base_dict (Dict): The dictionary to be sorted. - - Returns: - Dict: The dictionary sorted alphabetically on the dictionary's keys. - """ - return dict(sorted(base_dict.items())) - - -def dict_array_coercion(params: Dict) -> Tuple[Callable, Callable]: - """ - Construct the logic required to map a dictionary of parameters to an array - of parameters. The values of the dictionary can themselves be dictionaries; - the function should work recursively. - - Args: - params (Dict): The dictionary of parameters that we would like to map - into an array. - - Returns: - Tuple[Callable, Callable]: A pair of functions, the first of which maps - a dictionary to an array, and the second of which maps an array to a - dictionary. The remapped dictionary is equal in structure to the original - dictionary. - """ - flattened_pytree = jax.tree_util.tree_flatten(params) - - def dict_to_array(parameter_dict) -> jax.Array: - return jax.tree_util.tree_flatten(parameter_dict)[0] - - def array_to_dict(parameter_array) -> Dict: - return jax.tree_util.tree_unflatten(flattened_pytree[1], parameter_array) - - return dict_to_array, array_to_dict - - -__all__ = [ - "concat_dictionaries", - "merge_dictionaries", - "sort_dictionary", - "dict_array_coercion", -] diff --git a/tests/test_dict.py b/tests/test_dict.py deleted file mode 100644 index cfefc97..0000000 --- a/tests/test_dict.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright 2022 The GPJax Contributors. 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 -# -# 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 jax.numpy as jnp -import pytest -from jax.config import config - -from jaxutils.dict import ( - concat_dictionaries, - dict_array_coercion, - merge_dictionaries, - sort_dictionary, -) - -# Enable Float64 for more stable matrix inversions. -config.update("jax_enable_x64", True) - - -def test_concat_dict(): - d1 = {"a": 1, "b": 2} - d2 = {"c": 3, "d": 4} - d = concat_dictionaries(d1, d2) - assert list(d.keys()) == ["a", "b", "c", "d"] - assert list(d.values()) == [1, 2, 3, 4] - - -def test_merge_dicts(): - d1 = {"a": 1, "b": 2} - d2 = {"b": 3} - d = merge_dictionaries(d1, d2) - assert list(d.keys()) == ["a", "b"] - assert list(d.values()) == [1, 3] - - -def test_sort_dict(): - unsorted = {"b": 1, "a": 2} - sorted_dict = sort_dictionary(unsorted) - assert list(sorted_dict.keys()) == ["a", "b"] - assert list(sorted_dict.values()) == [2, 1] - - -@pytest.mark.parametrize("d", [1, 2, 10]) -def test_array_coercion(d): - params = { - "kernel": { - "lengthscale": jnp.array([1.0] * d), - "variance": jnp.array([1.0]), - }, - "likelihood": {"obs_noise": jnp.array([1.0])}, - "mean_function": {}, - } - dict_to_array, array_to_dict = dict_array_coercion(params) - assert array_to_dict(dict_to_array(params)) == params - assert isinstance(dict_to_array(params), list) - assert isinstance(array_to_dict(dict_to_array(params)), dict) From 21b26194f2fbb8a2e8a1145d1bbed353ab4a525f Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Feb 2023 11:05:53 +0000 Subject: [PATCH 03/81] Add stuff. --- jaxutils/config.py | 60 +-- jaxutils/parameters.py | 420 ------------------- jaxutils/params.py | 193 +++++++++ tests/{test_parameters.py => test_params.py} | 0 4 files changed, 223 insertions(+), 450 deletions(-) delete mode 100644 jaxutils/parameters.py create mode 100644 jaxutils/params.py rename tests/{test_parameters.py => test_params.py} (100%) diff --git a/jaxutils/config.py b/jaxutils/config.py index cabbbfd..03d8a95 100644 --- a/jaxutils/config.py +++ b/jaxutils/config.py @@ -93,35 +93,35 @@ def get_default_config() -> ConfigDict: # Covariance matrix stabilising jitter config.jitter = 1e-6 - FillScaleTriL = dx.Chain( - [ - tfb.FillScaleTriL(diag_shift=jnp.array(config.jitter)), - ] - ) - - # Default bijections - config.transformations = transformations = ConfigDict() - transformations.positive_transform = Softplus - transformations.identity_transform = Identity - transformations.triangular_transform = FillScaleTriL - - # Default parameter transforms - transformations.alpha = "positive_transform" - transformations.lengthscale = "positive_transform" - transformations.variance = "positive_transform" - transformations.smoothness = "positive_transform" - transformations.shift = "positive_transform" - transformations.obs_noise = "positive_transform" - transformations.latent = "identity_transform" - transformations.basis_fns = "identity_transform" - transformations.offset = "identity_transform" - transformations.inducing_inputs = "identity_transform" - transformations.variational_mean = "identity_transform" - transformations.variational_root_covariance = "triangular_transform" - transformations.natural_vector = "identity_transform" - transformations.natural_matrix = "identity_transform" - transformations.expectation_vector = "identity_transform" - transformations.expectation_matrix = "identity_transform" + # FillScaleTriL = dx.Chain( + # [ + # tfb.FillScaleTriL(diag_shift=jnp.array(config.jitter)), + # ] + # ) + + # # Default bijections + # config.transformations = transformations = ConfigDict() + # transformations.positive_transform = Softplus + # transformations.identity_transform = Identity + # transformations.triangular_transform = FillScaleTriL + + # # Default parameter transforms + # transformations.alpha = "positive_transform" + # transformations.lengthscale = "positive_transform" + # transformations.variance = "positive_transform" + # transformations.smoothness = "positive_transform" + # transformations.shift = "positive_transform" + # transformations.obs_noise = "positive_transform" + # transformations.latent = "identity_transform" + # transformations.basis_fns = "identity_transform" + # transformations.offset = "identity_transform" + # transformations.inducing_inputs = "identity_transform" + # transformations.variational_mean = "identity_transform" + # transformations.variational_root_covariance = "triangular_transform" + # transformations.natural_vector = "identity_transform" + # transformations.natural_matrix = "identity_transform" + # transformations.expectation_vector = "identity_transform" + # transformations.expectation_matrix = "identity_transform" return config @@ -147,4 +147,4 @@ def add_parameter(param_name: str, bijection: dx.Bijector) -> None: lookup_name = f"{param_name}_transform" get_global_config() __config.transformations[lookup_name] = bijection - __config.transformations[param_name] = lookup_name + __config.transformations[param_name] = lookup_name \ No newline at end of file diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py deleted file mode 100644 index b573c0a..0000000 --- a/jaxutils/parameters.py +++ /dev/null @@ -1,420 +0,0 @@ -# Copyright 2022 The GPJax Contributors. 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 -# -# 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 warnings -from copy import deepcopy -from typing import Dict, Tuple -from warnings import warn - -import distrax as dx -import jax -import jax.numpy as jnp -import jax.random as jr -from jax.random import KeyArray -from jaxtyping import Array, Float -from jaxutils import PyTree - -from .config import Identity, get_global_config -from .dict import merge_dictionaries - - -################################ -# Base operations -################################ -class ParameterState(PyTree): - """ - The state of the model. This includes the parameter set, which parameters - are to be trained and bijectors that allow parameters to be constrained and - unconstrained. - """ - - def __init__(self, params: Dict, trainables: Dict, bijectors: Dict) -> None: - self.params = params - self.trainables = trainables - self.bijectors = bijectors - - def unpack(self): - """Unpack the state into a tuple of parameters, trainables and bijectors. - - Returns: - Tuple[Dict, Dict, Dict]: The parameters, trainables and bijectors. - """ - return self.params, self.trainables, self.bijectors - - -def initialise(model, key: KeyArray = None, **kwargs) -> ParameterState: - """ - Initialise the stateful parameters of any GPJax object. This function also - returns the trainability status of each parameter and set of bijectors that - allow parameters to be constrained and unconstrained. - - Args: - model: The GPJax object that is to be initialised. - key (KeyArray, optional): The random key that is to be used for - initialisation. Defaults to None. - - Returns: - ParameterState: The state of the model. This includes the parameter - set, which parameters are to be trained and bijectors that allow - parameters to be constrained and unconstrained. - """ - - if key is None: - warn("No PRNGKey specified. Defaulting to seed 123.", UserWarning, stacklevel=2) - key = jr.PRNGKey(123) - - # Initialise the parameters. - if hasattr(model, "init_params"): - params = model.init_params(key) - - elif hasattr(model, "_initialise_params"): - warn( - "`_initialise_params` is deprecated. Please use `init_params` instead.", - DeprecationWarning, - stacklevel=2, - ) - params = model._initialise_params(key) - - else: - raise AttributeError("No `init_params` or `_initialise_params` method found.") - - if kwargs: - _validate_kwargs(kwargs, params) - for k, v in kwargs.items(): - params[k] = merge_dictionaries(params[k], v) - - bijectors = build_bijectors(params) - trainables = build_trainables(params) - - return ParameterState( - params=params, - trainables=trainables, - bijectors=bijectors, - ) - - -def _validate_kwargs(kwargs, params): - for k, v in kwargs.items(): - if k not in params.keys(): - raise ValueError(f"Parameter {k} is not a valid parameter.") - - -def recursive_items(d1: Dict, d2: Dict): - """ - Recursive loop over pair of dictionaries whereby the value of a given key in - either dictionary can be itself a dictionary. - - Args: - d1 (_type_): _description_ - d2 (_type_): _description_ - - Yields: - _type_: _description_ - """ - for key, value in d1.items(): - if type(value) is dict: - yield from recursive_items(value, d2[key]) - else: - yield (key, value, d2[key]) - - -def recursive_complete(d1: Dict, d2: Dict) -> Dict: - """ - Recursive loop over pair of dictionaries whereby the value of a given key in - either dictionary can be itself a dictionary. If the value of the key in the - second dictionary is None, the value of the key in the first dictionary is - used. - - Args: - d1 (Dict): The reference dictionary. - d2 (Dict): The potentially incomplete dictionary. - - Returns: - Dict: A completed form of the second dictionary. - """ - for key, value in d1.items(): - if type(value) is dict: - if key in d2.keys(): - recursive_complete(value, d2[key]) - else: - if key in d2.keys(): - d1[key] = d2[key] - return d1 - - -################################ -# Parameter transformation -################################ -def build_bijectors(params: Dict) -> Dict: - """ - For each parameter, build the bijection pair that allows the parameter to be - constrained and unconstrained. - - Args: - params (Dict): _description_ - - Returns: - Dict: A dictionary that maps each parameter to a bijection. - """ - bijectors = copy_dict_structure(params) - config = get_global_config() - transform_set = config["transformations"] - - def recursive_bijectors_list(ps, bs): - return [recursive_bijectors(ps[i], bs[i]) for i in range(len(bs))] - - def recursive_bijectors(ps, bs) -> Tuple[Dict, Dict]: - if type(ps) is list: - bs = recursive_bijectors_list(ps, bs) - - else: - for key, value in ps.items(): - if type(value) is dict: - recursive_bijectors(value, bs[key]) - elif type(value) is list: - bs[key] = recursive_bijectors_list(value, bs[key]) - else: - if key in transform_set.keys(): - transform_type = transform_set[key] - bijector = transform_set[transform_type] - else: - bijector = Identity - warnings.warn( - f"Parameter {key} has no transform. Defaulting to identity transfom." - ) - bs[key] = bijector - return bs - - return recursive_bijectors(params, bijectors) - - -def constrain(params: Dict, bijectors: Dict) -> Dict: - """ - Transform the parameters to the constrained space for corresponding - bijectors. - - Args: - params (Dict): The parameters that are to be transformed. - bijectors (Dict): The bijectors that are to be used for - transformation. - - Returns: - Dict: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. - """ - map = lambda param, trans: trans.forward(param) - - return jax.tree_util.tree_map(map, params, bijectors) - - -def unconstrain(params: Dict, bijectors: Dict) -> Dict: - """Transform the parameters to the unconstrained space for corresponding - bijectors. - - Args: - params (Dict): The parameters that are to be transformed. - bijectors (Dict): The corresponding dictionary of transforms that - should be applied to the parameter set. - - Returns: - Dict: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. - """ - - map = lambda param, trans: trans.inverse(param) - - return jax.tree_util.tree_map(map, params, bijectors) - - -################################ -# Priors -################################ -def log_density( - param: Float[Array, "D"], density: dx.Distribution -) -> Float[Array, "1"]: - """Compute the log density of a parameter given a distribution. - - Args: - param (Float[Array, "D"]): The parameter that is to be evaluated. - density (dx.Distribution): The distribution that is to be evaluated. - - Returns: - Float[Array, "1"]: The log density of the parameter. - """ - if type(density) == type(None): - log_prob = jnp.array(0.0) - else: - log_prob = jnp.sum(density.log_prob(param)) - return log_prob - - -def copy_dict_structure(params: Dict) -> Dict: - """Copy the structure of a dictionary. - - Args: - params (Dict): The dictionary that is to be copied. - - Returns: - Dict: A copy of the input dictionary. - """ - # Copy dictionary structure - prior_container = deepcopy(params) - # Set all values to zero - prior_container = jax.tree_util.tree_map(lambda _: None, prior_container) - return prior_container - - -def structure_priors(params: Dict, priors: Dict) -> Dict: - """First create a dictionary with equal structure to the parameters. - Then, for each supplied prior, overwrite the None value if it exists. - - Args: - params (Dict): [description] - priors (Dict): [description] - - Returns: - Dict: [description] - """ - prior_container = copy_dict_structure(params) - # Where a prior has been supplied, override the None value by the prior distribution. - complete_prior = recursive_complete(prior_container, priors) - return complete_prior - - -def evaluate_priors(params: Dict, priors: Dict) -> Dict: - """ - Recursive loop over pair of dictionaries that correspond to a parameter's - current value and the parameter's respective prior distribution. For - parameters where a prior distribution is specified, the log-prior density is - evaluated at the parameter's current value. - - Args: params (Dict): Dictionary containing the current set of parameter - estimates. priors (Dict): Dictionary specifying the parameters' prior - distributions. - - Returns: - Dict: The log-prior density, summed over all parameters. - """ - lpd = jnp.array(0.0) - if priors is not None: - for name, param, prior in recursive_items(params, priors): - lpd += log_density(param, prior) - return lpd - - -def prior_checks(priors: Dict) -> Dict: - """ - Run checks on the parameters' prior distributions. This checks that for - Gaussian processes that are constructed with non-conjugate likelihoods, the - prior distribution on the function's latent values is a unit Gaussian. - - Args: - priors (Dict): Dictionary specifying the parameters' prior distributions. - - Returns: - Dict: Dictionary specifying the parameters' prior distributions. - """ - if "latent" in priors.keys(): - latent_prior = priors["latent"] - if latent_prior is not None: - if not isinstance(latent_prior, dx.Normal): - warnings.warn( - f"A {type(latent_prior)} distribution prior has been placed on" - " the latent function. It is strongly advised that a" - " unit Gaussian prior is used." - ) - else: - warnings.warn("Placing unit Gaussian prior on latent function.") - priors["latent"] = dx.Normal(loc=0.0, scale=1.0) - else: - priors["latent"] = dx.Normal(loc=0.0, scale=1.0) - - return priors - - -def build_trainables(params: Dict, status: bool = True) -> Dict: - """ - Construct a dictionary of trainable statuses for each parameter. By default, - every parameter within the model is trainable. - - Args: - params (Dict): The parameter set for which trainable statuses should be - derived from. - status (bool): The status of each parameter. Default is True. - - Returns: - Dict: A dictionary of boolean trainability statuses. The dictionary is - equal in structure to the input params dictionary. - """ - # Copy dictionary structure - prior_container = deepcopy(params) - # Set all values to zero - prior_container = jax.tree_util.tree_map(lambda _: status, prior_container) - return prior_container - - -def _stop_grad(param: Dict, trainable: Dict) -> Dict: - """ - When taking a gradient, we want to stop the gradient from flowing through a - parameter if it is not trainable. This is achieved using the model's - dictionary of parameters and the corresponding trainability status. - - Args: - param (Dict): The parameter set for which trainable statuses should be - derived from. - trainable (Dict): A boolean value denoting the training status the `param`. - - Returns: - Dict: The gradient is stopped for non-trainable parameters. - """ - return jax.lax.cond(trainable, lambda x: x, jax.lax.stop_gradient, param) - - -def trainable_params(params: Dict, trainables: Dict) -> Dict: - """ - Stop the gradients flowing through parameters whose trainable status is - False. - - Args: - params (Dict): The parameter set for which trainable statuses should - be derived from. - trainables (Dict): A dictionary of boolean trainability statuses. The - dictionary is equal in structure to the input params dictionary. - - Returns: - Dict: A dictionary parameters. The dictionary is equal in structure to - the input params dictionary. - """ - return jax.tree_util.tree_map( - lambda param, trainable: _stop_grad(param, trainable), params, trainables - ) - - -__all__ = [ - "ParameterState", - "initialise", - "recursive_items", - "recursive_complete", - "build_bijectors", - "constrain", - "unconstrain", - "log_density", - "copy_dict_structure", - "structure_priors", - "evaluate_priors", - "prior_checks", - "build_trainables", - "trainable_params", -] diff --git a/jaxutils/params.py b/jaxutils/params.py new file mode 100644 index 0000000..478a4dd --- /dev/null +++ b/jaxutils/params.py @@ -0,0 +1,193 @@ +# Copyright 2022 The GPJax Contributors. 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 +# +# 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. +# ============================================================================== + +from __future__ import annotations + +import equinox as eqx +from dataclasses import fields, field +from dataclasses import field, fields +from typing import List + +import jax.tree_util as jtu +import jax + +from .config import Identity + + +class Bijector(eqx.Module): + """Base class for bijectors.""" + # This is for typing. We will develop equinox bijectors as part of a separate probabilistic programming library in future. + pass + +class Base(eqx.Module): + """Base class for models.""" + pass + + # TODO: Add checks for param fields. + + +def build_bijectors(obj: Base) -> eqx.Module: + """Given a Base object, return an equinox Module of bijectors comprising the same structure. + + Args: + obj(Base): A Base object. + + Returns: + eqx.Module: A Module of bijectors. + """ + + _, treedef = jtu.tree_flatten(obj) + + def _from_meta(obj: Base) -> List[Bijector]: + """Unpack bijectors from metatdata.""" + bijectors_ = [] + + for field_ in fields(obj): + try: + value = obj.__dict__[field_.name] + except KeyError: + continue + + metadata_ = field_.metadata + + if metadata_.get("static", False): + + if metadata_.get("transform", None) is not None: + transform_ = metadata_["transform"] + bijectors_.append(transform_) + + elif isinstance(value, eqx.Module): + for value_ in _from_meta(value): + bijectors_.append(value_) + + else: + bijectors_.append(value) + + return bijectors_ + + return treedef.unflatten(_from_meta(obj)) + + + +def param(transform: Bijector = Identity, **kwargs): + """Set leaf node metadata for a parameter. + + Args: + transform: A bijector to apply to the parameter. + static: Whether the parameter is static or not. + **kwargs: Additional metadata to set on the parameter. + + Returns: + A field with the metadata set. + """ + + # Create metadata dictionary. + try: + metadata = dict(kwargs["metadata"]) + except KeyError: + metadata = kwargs["metadata"] = {} + + if "param" in metadata: + raise ValueError("Cannot use metadata with `param` already set.") + metadata["param"] = True + + + # Param has a transform. + if "transform" in metadata: + raise ValueError("Cannot use metadata with `transform` already set.") + metadata["transform"] = transform + + return field(**kwargs) + + +def constrain(obj: Base, bij: eqx.Module) -> Base: + """ + Transform the parameters to the constrained space for corresponding + bijectors. + + Args: + obj (Base): The Base that is to be transformed. + bij (Dict): The bijectors that are to be used for + transformation. + + Returns: + Base: A transformed parameter set. The dictionary is equal in + structure to the input params dictionary. + """ + #TODO: This will break if a leaf node is not a parameter, i.e., does not have a transform! + return jtu.tree_map(lambda param, trans: trans.forward(param), obj, bij) + + +def constrain(obj: Base, bij: eqx.Module) -> Base: + """ + Transform the parameters to the constrained space for corresponding + bijectors. + + Args: + obj (Base): The Base that is to be transformed. + bij (Dict): The bijectors that are to be used for + transformation. + + Returns: + Base: A transformed model object. + """ + #TODO: This will break if a leaf node is not a parameter, i.e., does not have a transform! + return jtu.tree_map(lambda param, trans: trans.inverse(param), obj, bij) + + +def build_trainables(obj: Base, status: bool = True) -> eqx.Module: + """ + Construct a dictionary of trainable statuses for each parameter. By default, + every parameter within the model is trainable. + + Args: + obj (Dict): The parameter set for which trainable statuses should be + derived from. + status (bool): The status of each parameter. Default is True. + + Returns: + Dict: A dictionary of boolean trainability statuses. The dictionary is + equal in structure to the input params dictionary. + """ + return jtu.tree_map(lambda _: status, obj) + + +def _stop_grad(param: jax.Array, trainable: bool) -> jax.Array: + """Stop the gradient flowing through a parameter if it is not trainable.""" + return jax.lax.cond(trainable, lambda x: x, jax.lax.stop_gradient, param) + + +def trainable_params(module: eqx.Module, trainables: eqx.Module) -> eqx.Module: + """ + Stop the gradients flowing through parameters whose trainable status is + False. + + Args: + params (eqx.Module): The equinox Module to set the trainability of. + trainables (eqx.Module): The equinox Module of trainability statuses. + + Returns: + eqx.Module: The equinox Module of parameters with stopped gradients. + """ + return jtu.tree_map(lambda param, trainable: _stop_grad(param, trainable), module, trainables) + + +__all__ = [ + + "constrain", + "unconstrain", + "build_trainables", + "trainable_params", +] diff --git a/tests/test_parameters.py b/tests/test_params.py similarity index 100% rename from tests/test_parameters.py rename to tests/test_params.py From ca6b5a3da5b8c7180a3a84dc93bb72476c4e8be7 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Feb 2023 15:38:17 +0000 Subject: [PATCH 04/81] Update structure. --- jaxutils/__init__.py | 41 ++++---- jaxutils/abstractions.py | 215 +++++++++++++++++++++++++++++++++++++++ jaxutils/base.py | 28 +++++ jaxutils/bijector.py | 26 +++++ jaxutils/config.py | 2 +- jaxutils/objective.py | 61 +++++++++++ jaxutils/params.py | 96 ++++++++--------- jaxutils/progress_bar.py | 112 ++++++++++++++++++++ 8 files changed, 503 insertions(+), 78 deletions(-) create mode 100644 jaxutils/abstractions.py create mode 100644 jaxutils/base.py create mode 100644 jaxutils/bijector.py create mode 100644 jaxutils/objective.py create mode 100644 jaxutils/progress_bar.py diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index 8fb732f..cadf7a7 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -14,20 +14,14 @@ # ============================================================================== -from .pytree import PyTree +from .base import Base +from .bijector import Bijector +from .objective import Objective from .data import Dataset, verify_dataset -from .dict import ( - concat_dictionaries, - merge_dictionaries, - sort_dictionary, - dict_array_coercion, -) -from .parameters import ( - ParameterState, - initialise, - recursive_items, - recursive_complete, -) +from .params import param, build_bijectors, build_trainables, constrain, unconstrain +from .abstractions import fit, fit_batches, get_batch +from .progress_bar import progress_bar_scan + __authors__ = "Thomas Pinder, Daniel Dodd" __license__ = "MIT" @@ -41,17 +35,20 @@ __all__ = [ - "PyTree", + "Base", + "Bijector", + "Objective", "Dataset", "verify_dataset", - "concat_dictionaries", - "merge_dictionaries", - "sort_dictionary", - "dict_array_coercion", - "ParameterState", - "initialise", - "recursive_items", - "recursive_complete", + "param", + "build_bijectors", + "build_trainables", + "constrain", + "unconstrain", + "fit", + "fit_batches", + "get_batch", + "progress_bar_scan", ] from . import _version diff --git a/jaxutils/abstractions.py b/jaxutils/abstractions.py new file mode 100644 index 0000000..aff7dbd --- /dev/null +++ b/jaxutils/abstractions.py @@ -0,0 +1,215 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from typing import Optional, Tuple + +import jax +import jax.numpy as jnp +import jax.random as jr +import optax as ox + +from jax.random import KeyArray +from jaxtyping import Array, Float + +from .params import constrain, trainable_params, unconstrain + +import equinox as eqx + +from .data import Dataset +from .base import Base +from .objective import Objective +from .progress_bar import progress_bar_scan + + +class InferenceState(eqx.Module): + """Imutable class for storing optimised parameters and training history.""" + + model: eqx.Module + history: Float[Array, "num_iters"] + + def unpack(self) -> Tuple[Base, Float[Array, "num_iters"]]: + """Unpack parameters and training history into a tuple. + + Returns: + Tuple[Base, Float[Array, "num_iters"]]: Tuple of parameters and training history. + """ + return self.model, self.history + + +def fit( + objective: Objective, + model: eqx.Module, + bijectors: eqx.Module, + trainables: eqx.Module, + train_data: Dataset, + optax_optim: ox.GradientTransformation, + num_iters: Optional[int] = 100, + log_rate: Optional[int] = 10, + verbose: Optional[bool] = True, +) -> InferenceState: + """Abstracted method for fitting a GP model with respect to a supplied objective function. + Optimisers used here should originate from Optax. + + Args: + objective (Objective): The objective function that we are optimising with respect to. + model (eqx.Module): The model that is to be optimised. + bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. + trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. + optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. + num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. + log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. + verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. + + Returns: + InferenceState: An InferenceState object comprising the optimised parameters and training history respectively. + """ + + # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False + def loss(model: eqx.Module) -> Float[Array, "1"]: + model = trainable_params(model, trainables) + model = constrain(model, bijectors) + return objective(model, train_data) + + # Tranform model to unconstrained space + model = unconstrain(model, bijectors) + + # Initialise optimiser state + opt_state = optax_optim.init(model) + + # Iteration loop numbers to scan over + iter_nums = jnp.arange(num_iters) + + # Optimisation step + def step(carry, iter_num: int): + model, opt_state = carry + loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model) + updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) + model = eqx.apply_updates(model, updates) + carry = model, opt_state + return carry, loss_val + + # Display progress bar if verbose is True + if verbose: + step = progress_bar_scan(num_iters, log_rate)(step) + + # Run the optimisation loop + (model, _), history = jax.lax.scan(step, (model, opt_state), iter_nums) + + # Tranform final model to constrained space + model = constrain(model, bijectors) + + return InferenceState(model=model, history=history) + + +def fit_batches( + objective: Objective, + model: eqx.Module, + bijectors: eqx.Module, + trainables: eqx.Module, + train_data: Dataset, + optax_optim: ox.GradientTransformation, + key: KeyArray, + batch_size: int, + num_iters: Optional[int] = 100, + log_rate: Optional[int] = 10, + verbose: Optional[bool] = True, +) -> InferenceState: + """Abstracted method for fitting a GP model with mini-batches respect to a + supplied objective function. + Optimisers used here should originate from Optax. + + Args: + objective (Objective): The objective function that we are optimising with respect to. + model (eqx.Module): The model that is to be optimised. + bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. + trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. + train_data (Dataset): The training dataset. + optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. + key (KeyArray): The PRNG key for the mini-batch sampling. + batch_size (int): The batch_size. + num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. + log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. + verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. + + Returns: + InferenceState: An InferenceState object comprising the optimised parameters and training history respectively. + """ + + # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False + def loss(model: eqx.Module, batch: Dataset) -> Float[Array, "1"]: + model = trainable_params(model, trainables) + model = constrain(model, bijectors) + return objective(model, batch) + + # Tranform model to unconstrained space + model = unconstrain(model, bijectors) + + # Initialise optimiser state + opt_state = optax_optim.init(model) + + # Mini-batch random keys and iteration loop numbers to scan over + keys = jr.split(key, num_iters) + iter_nums = jnp.arange(num_iters) + + # Optimisation step + def step(carry, iter_num__and__key): + iter_num, key = iter_num__and__key + model, opt_state = carry + + batch = get_batch(train_data, batch_size, key) + + loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model, batch) + updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) + model = eqx.apply_updates(model, updates) + + carry = model, opt_state + return carry, loss_val + + # Display progress bar if verbose is True + if verbose: + step = progress_bar_scan(num_iters, log_rate)(step) + + # Run the optimisation loop + (model, _), history = jax.lax.scan(step, (model, opt_state), (iter_nums, keys)) + + # Tranform final params to constrained space + model = constrain(model, bijectors) + + return InferenceState(model=model, history=history) + + +def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: + """Batch the data into mini-batches. Sampling is done with replacement. + + Args: + train_data (Dataset): The training dataset. + batch_size (int): The batch size. + + Returns: + Dataset: The batched dataset. + """ + x, y, n = train_data.X, train_data.y, train_data.n + + # Subsample data inidicies with replacement to get the mini-batch + indicies = jr.choice(key, n, (batch_size,), replace=True) + + return Dataset(X=x[indicies], y=y[indicies]) + + +__all__ = [ + "fit", + "fit_natgrads", + "get_batch", +] \ No newline at end of file diff --git a/jaxutils/base.py b/jaxutils/base.py new file mode 100644 index 0000000..5b6990b --- /dev/null +++ b/jaxutils/base.py @@ -0,0 +1,28 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 equinox as eqx + + +class Base(eqx.Module): + """Base class for all objects of the JaxGaussianProcesses ecosystem.""" + pass + + # TODO: Add checks for param fields. + + +__all__ = [ + "Base", +] diff --git a/jaxutils/bijector.py b/jaxutils/bijector.py new file mode 100644 index 0000000..64f1696 --- /dev/null +++ b/jaxutils/bijector.py @@ -0,0 +1,26 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 equinox as eqx + +class Bijector(eqx.Module): + """Base class for bijectors.""" + # This is for typing. We will develop equinox bijectors as part of a separate probabilistic programming library in future. + pass + + +__all__ = [ + "Bijector", +] diff --git a/jaxutils/config.py b/jaxutils/config.py index 03d8a95..06966bb 100644 --- a/jaxutils/config.py +++ b/jaxutils/config.py @@ -1,4 +1,4 @@ -# Copyright 2022 The GPJax Contributors. All Rights Reserved. +# Copyright 2022 The JaxGaussianProcesses Contributors. 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. diff --git a/jaxutils/objective.py b/jaxutils/objective.py new file mode 100644 index 0000000..51e2587 --- /dev/null +++ b/jaxutils/objective.py @@ -0,0 +1,61 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 abc +import equinox as eqx + +from .data import Dataset +from .base import Base + +class Objective(eqx.Module): + """Base class for objective functions.""" + negative: bool = eqx.static_field() + constant: float = eqx.static_field() + + def __init__(self, negative: bool = False): + """Initialise the objective function. + + Args: + negative(bool): Whether to negate the objective function. + + Returns: + Objective: An objective function. + """ + + self.negative = negative + self.constant = -1.0 if negative else 1.0 + + def __call__(self, model: Base, train_data: Dataset) -> float: + """Evaluate the objective function. + + Args: + model(Base): A model. + *args: Additional arguments. + **kwargs: Additional keyword arguments. + + Returns: + float: The objective function. + """ + return self.constant * self.evaluate(model, train_data) + + @abc.abstractmethod + def evaluate(self, model: Base, train_data: Dataset) -> float: + """Evaluate the objective function.""" + raise NotImplementedError + + +__all__ = [ + "Objective", +] diff --git a/jaxutils/params.py b/jaxutils/params.py index 478a4dd..a1edf96 100644 --- a/jaxutils/params.py +++ b/jaxutils/params.py @@ -1,4 +1,4 @@ -# Copyright 2022 The GPJax Contributors. All Rights Reserved. +# Copyright 2022 The JaxGaussianProcesses Contributors. 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. @@ -21,21 +21,11 @@ from typing import List import jax.tree_util as jtu -import jax +from jax import lax from .config import Identity - - -class Bijector(eqx.Module): - """Base class for bijectors.""" - # This is for typing. We will develop equinox bijectors as part of a separate probabilistic programming library in future. - pass - -class Base(eqx.Module): - """Base class for models.""" - pass - - # TODO: Add checks for param fields. +from .base import Base +from .bijector import Bijector def build_bijectors(obj: Base) -> eqx.Module: @@ -50,66 +40,65 @@ def build_bijectors(obj: Base) -> eqx.Module: _, treedef = jtu.tree_flatten(obj) - def _from_meta(obj: Base) -> List[Bijector]: + def _unpack_bijectors_from_meta(cls: eqx.Module): """Unpack bijectors from metatdata.""" - bijectors_ = [] + bijectors = [] - for field_ in fields(obj): + for field_ in fields(cls): + name = field_.name + try: - value = obj.__dict__[field_.name] + value = cls.__dict__[name] except KeyError: continue - metadata_ = field_.metadata + if not field_.metadata.get("static", False): - if metadata_.get("static", False): - - if metadata_.get("transform", None) is not None: - transform_ = metadata_["transform"] - bijectors_.append(transform_) + if field_.metadata.get("transform", None) is not None: + trans = field_.metadata["transform"] + bijectors.append(trans) elif isinstance(value, eqx.Module): - for value_ in _from_meta(value): - bijectors_.append(value_) + for value_ in _unpack_bijectors_from_meta(value): + bijectors.append(value_) else: - bijectors_.append(value) - - return bijectors_ + bijectors.append(value) + + return bijectors - return treedef.unflatten(_from_meta(obj)) + return treedef.unflatten(_unpack_bijectors_from_meta(obj)) -def param(transform: Bijector = Identity, **kwargs): +def param(transform: Bijector): """Set leaf node metadata for a parameter. Args: transform: A bijector to apply to the parameter. static: Whether the parameter is static or not. - **kwargs: Additional metadata to set on the parameter. Returns: A field with the metadata set. """ - # Create metadata dictionary. - try: - metadata = dict(kwargs["metadata"]) - except KeyError: - metadata = kwargs["metadata"] = {} + # # Create metadata dictionary. + # try: + # metadata = dict(kwargs["metadata"]) + # except KeyError: + # metadata = kwargs["metadata"] = {} - if "param" in metadata: - raise ValueError("Cannot use metadata with `param` already set.") - metadata["param"] = True + # if "param" in metadata: + # raise ValueError("Cannot use metadata with `param` already set.") + # metadata["param"] = True - # Param has a transform. - if "transform" in metadata: - raise ValueError("Cannot use metadata with `transform` already set.") - metadata["transform"] = transform + # # Param has a transform. + # if "transform" in metadata: + # raise ValueError("Cannot use metadata with `transform` already set.") + # metadata["transform"] = transform - return field(**kwargs) + return field(metadata={"transform": transform}) def constrain(obj: Base, bij: eqx.Module) -> Base: @@ -130,9 +119,9 @@ def constrain(obj: Base, bij: eqx.Module) -> Base: return jtu.tree_map(lambda param, trans: trans.forward(param), obj, bij) -def constrain(obj: Base, bij: eqx.Module) -> Base: +def unconstrain(obj: Base, bij: eqx.Module) -> Base: """ - Transform the parameters to the constrained space for corresponding + Transform the parameters to the unconstrained space for corresponding bijectors. Args: @@ -164,28 +153,25 @@ def build_trainables(obj: Base, status: bool = True) -> eqx.Module: return jtu.tree_map(lambda _: status, obj) -def _stop_grad(param: jax.Array, trainable: bool) -> jax.Array: - """Stop the gradient flowing through a parameter if it is not trainable.""" - return jax.lax.cond(trainable, lambda x: x, jax.lax.stop_gradient, param) - - def trainable_params(module: eqx.Module, trainables: eqx.Module) -> eqx.Module: """ Stop the gradients flowing through parameters whose trainable status is False. Args: - params (eqx.Module): The equinox Module to set the trainability of. + module (eqx.Module): The equinox Module to set the trainability of. trainables (eqx.Module): The equinox Module of trainability statuses. Returns: eqx.Module: The equinox Module of parameters with stopped gradients. """ - return jtu.tree_map(lambda param, trainable: _stop_grad(param, trainable), module, trainables) + return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), module, trainables) -__all__ = [ +__all__ = [ + "param", + "build_bijectors", "constrain", "unconstrain", "build_trainables", diff --git a/jaxutils/progress_bar.py b/jaxutils/progress_bar.py new file mode 100644 index 0000000..e3c36f8 --- /dev/null +++ b/jaxutils/progress_bar.py @@ -0,0 +1,112 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from typing import Callable, Any, Union + +from jax import lax +from jax.experimental import host_callback +from jaxtyping import Array, Float +from tqdm.auto import tqdm + + +#TODO: (Dan D) add a compilation message to the progress bar from your private code. + +def progress_bar_scan(num_iters: int, log_rate: int) -> Callable: + """Progress bar for Jax.lax scans (adapted from https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/).""" + + tqdm_bars = {} + remainder = num_iters % log_rate + + def _define_tqdm(args: Any, transform: Any) -> None: + """Define a tqdm progress bar.""" + tqdm_bars[0] = tqdm(range(num_iters)) + + def _update_tqdm(args: Any, transform: Any) -> None: + """Update the tqdm progress bar with the latest objective value.""" + loss_val, arg = args + tqdm_bars[0].update(arg) + tqdm_bars[0].set_postfix({"Objective": f"{loss_val: .2f}"}) + + def _close_tqdm(args: Any, transform: Any) -> None: + """Close the tqdm progress bar.""" + tqdm_bars[0].close() + + def _callback(cond: bool, func: Callable, arg: Any) -> None: + """Callback a function for a given argument if a condition is true.""" + dummy_result = 0 + + def _do_callback(_) -> int: + """Perform the callback.""" + return host_callback.id_tap(func, arg, result=dummy_result) + + def _not_callback(_) -> int: + """Do nothing.""" + return dummy_result + + _ = lax.cond(cond, _do_callback, _not_callback, operand=None) + + def _update_progress_bar(loss_val: Float[Array, "1"], iter_num: int) -> None: + """Updates tqdm progress bar of a JAX scan or loop.""" + + # Conditions for iteration number + is_first: bool = iter_num == 0 + is_multiple: bool = (iter_num % log_rate == 0) & ( + iter_num != num_iters - remainder + ) + is_remainder: bool = iter_num == num_iters - remainder + is_last: bool = iter_num == num_iters - 1 + + # Define progress bar, if first iteration + _callback(is_first, _define_tqdm, None) + + # Update progress bar, if multiple of log_rate + _callback(is_multiple, _update_tqdm, (loss_val, log_rate)) + + # Update progress bar, if remainder + _callback(is_remainder, _update_tqdm, (loss_val, remainder)) + + # Close progress bar, if last iteration + _callback(is_last, _close_tqdm, None) + + def _progress_bar_scan(body_fun: Callable) -> Callable: + """Decorator that adds a progress bar to `body_fun` used in `lax.scan`.""" + + def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any: + + # Get iteration number + if type(x) is tuple: + iter_num, *_ = x + else: + iter_num = x + + # Compute iteration step + result = body_fun(carry, x) + + # Get loss value + *_, loss_val = result + + # Update progress bar + _update_progress_bar(loss_val, iter_num) + + return result + + return wrapper_progress_bar + + return _progress_bar_scan + + +__all__ = [ + "progress_bar_scan", +] From cf76b0a6b4c418a2ba0cd5d7d2d331e5b5fa5d45 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Feb 2023 15:41:35 +0000 Subject: [PATCH 05/81] Update README.md --- README.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a3b0bf..31381f2 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,54 @@ `JaxUtils` provides utility functions for the [`JaxGaussianProcesses`]() ecosystem. -# Contents + +## Training a Linear Model is easy peasy. +```python +import jaxutils as ju + +from jaxutils.config import Identity + +import jax.numpy as jnp +import jax.random as jr +import optax as ox + + +class LinearModel(ju.Base): + weight: float = ju.param(Identity) + bias: float = ju.param(Identity) + + def __call__(self, x): + return self.weight * x + self.bias + + +class LeastSquares(ju.Objective): + + def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: + return jnp.sum((train_data.y - model(train_data.X)) ** 2) + + + +x = jnp.linspace(0.0, 1.0, 20).reshape(-1, 1) +y = 2.0 * x + 1.0 + jr.normal(jr.PRNGKey(0), x.shape).reshape(-1, 1) + +D = ju.Dataset(x, y) + +m = LinearModel(weight=1.0, bias=1.0) +bij = ju.build_bijectors(m) +tr = ju.build_trainables(m) +loss = LeastSquares() + + +infst = ju.fit(loss, m, bij, tr, D, ox.sgd(0.01), 10000) + +model = infst.model + +print(model.weight, model.bias) +``` + + + +# Contents - TO UPDATE. - [PyTree](#pytree) - [Dataset](#dataset) From e3640db671f1bb06318bbc0c65a440d862ee31e7 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 13:23:25 +0000 Subject: [PATCH 06/81] Remove base. Move to module. --- jaxutils/__init__.py | 9 +- jaxutils/abstractions.py | 201 ++++++++++++++++++--------------------- jaxutils/base.py | 28 ------ jaxutils/module.py | 139 +++++++++++++++++++++++++++ jaxutils/objective.py | 6 +- jaxutils/params.py | 121 +++-------------------- 6 files changed, 252 insertions(+), 252 deletions(-) delete mode 100644 jaxutils/base.py create mode 100644 jaxutils/module.py diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index cadf7a7..f71c1ac 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -14,12 +14,12 @@ # ============================================================================== -from .base import Base +from .module import Module from .bijector import Bijector from .objective import Objective from .data import Dataset, verify_dataset -from .params import param, build_bijectors, build_trainables, constrain, unconstrain -from .abstractions import fit, fit_batches, get_batch +from .params import param, constrain, unconstrain +from .abstractions import fit, get_batch from .progress_bar import progress_bar_scan @@ -35,7 +35,7 @@ __all__ = [ - "Base", + "Module", "Bijector", "Objective", "Dataset", @@ -46,7 +46,6 @@ "constrain", "unconstrain", "fit", - "fit_batches", "get_batch", "progress_bar_scan", ] diff --git a/jaxutils/abstractions.py b/jaxutils/abstractions.py index aff7dbd..20b477d 100644 --- a/jaxutils/abstractions.py +++ b/jaxutils/abstractions.py @@ -23,42 +23,23 @@ from jax.random import KeyArray from jaxtyping import Array, Float -from .params import constrain, trainable_params, unconstrain - -import equinox as eqx +from .params import constrain, stop_gradients, unconstrain +from .module import Module from .data import Dataset -from .base import Base from .objective import Objective from .progress_bar import progress_bar_scan -class InferenceState(eqx.Module): - """Imutable class for storing optimised parameters and training history.""" - - model: eqx.Module - history: Float[Array, "num_iters"] - - def unpack(self) -> Tuple[Base, Float[Array, "num_iters"]]: - """Unpack parameters and training history into a tuple. - - Returns: - Tuple[Base, Float[Array, "num_iters"]]: Tuple of parameters and training history. - """ - return self.model, self.history - - def fit( objective: Objective, - model: eqx.Module, - bijectors: eqx.Module, - trainables: eqx.Module, + model: Module, train_data: Dataset, optax_optim: ox.GradientTransformation, num_iters: Optional[int] = 100, log_rate: Optional[int] = 10, verbose: Optional[bool] = True, -) -> InferenceState: +) -> Tuple[Module, Array]: """Abstracted method for fitting a GP model with respect to a supplied objective function. Optimisers used here should originate from Optax. @@ -73,17 +54,17 @@ def fit( verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. Returns: - InferenceState: An InferenceState object comprising the optimised parameters and training history respectively. + Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False - def loss(model: eqx.Module) -> Float[Array, "1"]: - model = trainable_params(model, trainables) - model = constrain(model, bijectors) + def loss(model: Module) -> Float[Array, "1"]: + model = stop_gradients(model) + model = constrain(model) return objective(model, train_data) # Tranform model to unconstrained space - model = unconstrain(model, bijectors) + model = unconstrain(model) # Initialise optimiser state opt_state = optax_optim.init(model) @@ -94,9 +75,9 @@ def loss(model: eqx.Module) -> Float[Array, "1"]: # Optimisation step def step(carry, iter_num: int): model, opt_state = carry - loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model) + loss_val, loss_gradient = jax.value_and_grad(loss)(model) updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) - model = eqx.apply_updates(model, updates) + model = ox.apply_updates(model, updates) carry = model, opt_state return carry, loss_val @@ -108,86 +89,86 @@ def step(carry, iter_num: int): (model, _), history = jax.lax.scan(step, (model, opt_state), iter_nums) # Tranform final model to constrained space - model = constrain(model, bijectors) - - return InferenceState(model=model, history=history) - - -def fit_batches( - objective: Objective, - model: eqx.Module, - bijectors: eqx.Module, - trainables: eqx.Module, - train_data: Dataset, - optax_optim: ox.GradientTransformation, - key: KeyArray, - batch_size: int, - num_iters: Optional[int] = 100, - log_rate: Optional[int] = 10, - verbose: Optional[bool] = True, -) -> InferenceState: - """Abstracted method for fitting a GP model with mini-batches respect to a - supplied objective function. - Optimisers used here should originate from Optax. - - Args: - objective (Objective): The objective function that we are optimising with respect to. - model (eqx.Module): The model that is to be optimised. - bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. - trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. - train_data (Dataset): The training dataset. - optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. - key (KeyArray): The PRNG key for the mini-batch sampling. - batch_size (int): The batch_size. - num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. - log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. - verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. - - Returns: - InferenceState: An InferenceState object comprising the optimised parameters and training history respectively. - """ - - # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False - def loss(model: eqx.Module, batch: Dataset) -> Float[Array, "1"]: - model = trainable_params(model, trainables) - model = constrain(model, bijectors) - return objective(model, batch) - - # Tranform model to unconstrained space - model = unconstrain(model, bijectors) - - # Initialise optimiser state - opt_state = optax_optim.init(model) - - # Mini-batch random keys and iteration loop numbers to scan over - keys = jr.split(key, num_iters) - iter_nums = jnp.arange(num_iters) - - # Optimisation step - def step(carry, iter_num__and__key): - iter_num, key = iter_num__and__key - model, opt_state = carry - - batch = get_batch(train_data, batch_size, key) - - loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model, batch) - updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) - model = eqx.apply_updates(model, updates) - - carry = model, opt_state - return carry, loss_val - - # Display progress bar if verbose is True - if verbose: - step = progress_bar_scan(num_iters, log_rate)(step) - - # Run the optimisation loop - (model, _), history = jax.lax.scan(step, (model, opt_state), (iter_nums, keys)) - - # Tranform final params to constrained space - model = constrain(model, bijectors) - - return InferenceState(model=model, history=history) + model = constrain(model) + + return model, history + + +# def fit_batches( +# objective: Objective, +# model: eqx.Module, +# bijectors: eqx.Module, +# trainables: eqx.Module, +# train_data: Dataset, +# optax_optim: ox.GradientTransformation, +# key: KeyArray, +# batch_size: int, +# num_iters: Optional[int] = 100, +# log_rate: Optional[int] = 10, +# verbose: Optional[bool] = True, +# ) -> Tuple[eqx.Module, Array]: +# """Abstracted method for fitting a GP model with mini-batches respect to a +# supplied objective function. +# Optimisers used here should originate from Optax. + +# Args: +# objective (Objective): The objective function that we are optimising with respect to. +# model (eqx.Module): The model that is to be optimised. +# bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. +# trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. +# train_data (Dataset): The training dataset. +# optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. +# key (KeyArray): The PRNG key for the mini-batch sampling. +# batch_size (int): The batch_size. +# num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. +# log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. +# verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. + +# Returns: +# Tuple[eqx.Module, Array]: A Tuple comprising the optimised model and training history respectively. +# """ + +# # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False +# def loss(model: eqx.Module, batch: Dataset) -> Float[Array, "1"]: +# model = trainable_params(model, trainables) +# model = constrain(model, bijectors) +# return objective(model, batch) + +# # Tranform model to unconstrained space +# model = unconstrain(model, bijectors) + +# # Initialise optimiser state +# opt_state = optax_optim.init(model) + +# # Mini-batch random keys and iteration loop numbers to scan over +# keys = jr.split(key, num_iters) +# iter_nums = jnp.arange(num_iters) + +# # Optimisation step +# def step(carry, iter_num__and__key): +# iter_num, key = iter_num__and__key +# model, opt_state = carry + +# batch = get_batch(train_data, batch_size, key) + +# loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model, batch) +# updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) +# model = eqx.apply_updates(model, updates) + +# carry = model, opt_state +# return carry, loss_val + +# # Display progress bar if verbose is True +# if verbose: +# step = progress_bar_scan(num_iters, log_rate)(step) + +# # Run the optimisation loop +# (model, _), history = jax.lax.scan(step, (model, opt_state), (iter_nums, keys)) + +# # Tranform final params to constrained space +# model = constrain(model, bijectors) + +# return model, history def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: diff --git a/jaxutils/base.py b/jaxutils/base.py deleted file mode 100644 index 5b6990b..0000000 --- a/jaxutils/base.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 equinox as eqx - - -class Base(eqx.Module): - """Base class for all objects of the JaxGaussianProcesses ecosystem.""" - pass - - # TODO: Add checks for param fields. - - -__all__ = [ - "Base", -] diff --git a/jaxutils/module.py b/jaxutils/module.py new file mode 100644 index 0000000..138d5ea --- /dev/null +++ b/jaxutils/module.py @@ -0,0 +1,139 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 jax.tree_util as jtu +from dataclasses import fields +from typing import List + + +import equinox as eqx + + +class _cache_property_comprising_static_fields: + """Be careful with this --- highly JAX incompatible!! + + Courtesy of Kernex. + + Fine for properties that depend *only* on static fields. For dynamic fields, this will end in tears. + """ + + def __init__(self, prop): + """ Does your prop have a dynamic field? If so, STOP!""" + + self.name = prop.__name__ + self.prop = prop + + def __get__(self, instance, owner): + value = self.prop(instance) + object.__setattr__(instance, self.name, value) + return value + + +class Module(eqx.Module): + """Base class for all objects of the JaxGaussianProcesses ecosystem.""" + + # TODO: Add checks for param fields. WE NEED TO ENSURE ALL LEAVES ARE PARAMS AND ONLY PARAMS. + + def set_bijectors(self, bijectors): + + # TODO: Throwin hostcall back warning. This completely breaks the immutability of the object. + # YOU DO NOT WANT TO DO THIS WITHIN A JIT REGION. + # Really, this is a hack. We need to create a new object not modify the existing one. + object.__setattr__(self, "bijectors", bijectors) + + def set_trainables(self, trainables): + + # TODO: Throwin hostcall back warning. This completely breaks the immutability of the object. + # YOU DO NOT WANT TO DO THIS WITHIN A JIT REGION. + # Really, this is a hack. We need to create a new object not modify the existing one. + object.__setattr__(self, "trainables", trainables) + + + @_cache_property_comprising_static_fields + def bijectors(self): + """Return a default PyTree of model bijectors.""" + return _default_bijectors(self) + + @_cache_property_comprising_static_fields + def trainables(self): + return _default_trainables(self) + + + + +def _default_trainables(obj: Module) -> eqx.Module: + """ + Construct a dictionary of trainable statuses for each parameter. By default, + every parameter within the model is trainable. + + Args: + obj (Dict): The parameter set for which trainable statuses should be + derived from. + status (bool): The status of each parameter. Default is True. + + Returns: + Dict: A dictionary of boolean trainability statuses. The dictionary is + equal in structure to the input params dictionary. + """ + return jtu.tree_map(lambda _: True, obj) + + +def _default_bijectors(obj: Module) -> eqx.Module: + """Given a Base object, return an equinox Module of bijectors comprising the same structure. + + Args: + obj(Base): A Base object. + + Returns: + eqx.Module: A Module of bijectors. + """ + + _, treedef = jtu.tree_flatten(obj) + + def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[None]: + """Unpack bijectors from metatdata.""" + bijectors = [] + + for field_ in fields(cls): + name = field_.name + + try: + value = cls.__dict__[name] + except KeyError: + continue + + if not field_.metadata.get("static", False): + + if field_.metadata.get("transform", None) is not None: + trans = field_.metadata["transform"] + bijectors.append(trans) + + elif isinstance(value, eqx.Module): + for value_ in _unpack_bijectors_from_meta(value): + bijectors.append(value_) + + else: + bijectors.append(value) + + return bijectors + + return treedef.unflatten(_unpack_bijectors_from_meta(obj)) + + + + +__all__ = [ + "Module", +] diff --git a/jaxutils/objective.py b/jaxutils/objective.py index 51e2587..00ffe89 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -17,7 +17,7 @@ import equinox as eqx from .data import Dataset -from .base import Base +from .module import Module class Objective(eqx.Module): """Base class for objective functions.""" @@ -37,7 +37,7 @@ def __init__(self, negative: bool = False): self.negative = negative self.constant = -1.0 if negative else 1.0 - def __call__(self, model: Base, train_data: Dataset) -> float: + def __call__(self, model: Module, train_data: Dataset) -> float: """Evaluate the objective function. Args: @@ -51,7 +51,7 @@ def __call__(self, model: Base, train_data: Dataset) -> float: return self.constant * self.evaluate(model, train_data) @abc.abstractmethod - def evaluate(self, model: Base, train_data: Dataset) -> float: + def evaluate(self, model: Module, train_data: Dataset) -> float: """Evaluate the objective function.""" raise NotImplementedError diff --git a/jaxutils/params.py b/jaxutils/params.py index a1edf96..79c073c 100644 --- a/jaxutils/params.py +++ b/jaxutils/params.py @@ -13,62 +13,13 @@ # limitations under the License. # ============================================================================== -from __future__ import annotations - -import equinox as eqx -from dataclasses import fields, field -from dataclasses import field, fields -from typing import List +from dataclasses import field import jax.tree_util as jtu from jax import lax -from .config import Identity -from .base import Base from .bijector import Bijector - - -def build_bijectors(obj: Base) -> eqx.Module: - """Given a Base object, return an equinox Module of bijectors comprising the same structure. - - Args: - obj(Base): A Base object. - - Returns: - eqx.Module: A Module of bijectors. - """ - - _, treedef = jtu.tree_flatten(obj) - - def _unpack_bijectors_from_meta(cls: eqx.Module): - """Unpack bijectors from metatdata.""" - bijectors = [] - - for field_ in fields(cls): - name = field_.name - - try: - value = cls.__dict__[name] - except KeyError: - continue - - if not field_.metadata.get("static", False): - - if field_.metadata.get("transform", None) is not None: - trans = field_.metadata["transform"] - bijectors.append(trans) - - elif isinstance(value, eqx.Module): - for value_ in _unpack_bijectors_from_meta(value): - bijectors.append(value_) - - else: - bijectors.append(value) - - return bijectors - - return treedef.unflatten(_unpack_bijectors_from_meta(obj)) - +from .module import Module def param(transform: Bijector): @@ -81,99 +32,57 @@ def param(transform: Bijector): Returns: A field with the metadata set. """ - - # # Create metadata dictionary. - # try: - # metadata = dict(kwargs["metadata"]) - # except KeyError: - # metadata = kwargs["metadata"] = {} - - # if "param" in metadata: - # raise ValueError("Cannot use metadata with `param` already set.") - # metadata["param"] = True - - - # # Param has a transform. - # if "transform" in metadata: - # raise ValueError("Cannot use metadata with `transform` already set.") - # metadata["transform"] = transform - return field(metadata={"transform": transform}) -def constrain(obj: Base, bij: eqx.Module) -> Base: +def constrain(obj: Module) -> Module: """ - Transform the parameters to the constrained space for corresponding + Transform model parameters to the constrained space for corresponding bijectors. Args: - obj (Base): The Base that is to be transformed. - bij (Dict): The bijectors that are to be used for - transformation. + obj (Module): The Base that is to be transformed. Returns: Base: A transformed parameter set. The dictionary is equal in structure to the input params dictionary. """ - #TODO: This will break if a leaf node is not a parameter, i.e., does not have a transform! - return jtu.tree_map(lambda param, trans: trans.forward(param), obj, bij) + return jtu.tree_map(lambda p, t: t.forward(p), obj, obj.bijectors) -def unconstrain(obj: Base, bij: eqx.Module) -> Base: +def unconstrain(obj: Module) -> Module: """ - Transform the parameters to the unconstrained space for corresponding + Transform model parameters to the unconstrained space for corresponding bijectors. Args: - obj (Base): The Base that is to be transformed. - bij (Dict): The bijectors that are to be used for - transformation. - - Returns: - Base: A transformed model object. - """ - #TODO: This will break if a leaf node is not a parameter, i.e., does not have a transform! - return jtu.tree_map(lambda param, trans: trans.inverse(param), obj, bij) - - -def build_trainables(obj: Base, status: bool = True) -> eqx.Module: - """ - Construct a dictionary of trainable statuses for each parameter. By default, - every parameter within the model is trainable. - - Args: - obj (Dict): The parameter set for which trainable statuses should be - derived from. - status (bool): The status of each parameter. Default is True. + obj (Module): The Base that is to be transformed. Returns: - Dict: A dictionary of boolean trainability statuses. The dictionary is - equal in structure to the input params dictionary. + Base: A transformed parameter set. The dictionary is equal in + structure to the input params dictionary. """ - return jtu.tree_map(lambda _: status, obj) + return jtu.tree_map(lambda p, t: t.inverse(p), obj, obj.bijectors) -def trainable_params(module: eqx.Module, trainables: eqx.Module) -> eqx.Module: +def stop_gradients(obj: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is False. Args: module (eqx.Module): The equinox Module to set the trainability of. - trainables (eqx.Module): The equinox Module of trainability statuses. Returns: eqx.Module: The equinox Module of parameters with stopped gradients. """ - return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), module, trainables) + return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), obj, obj.trainables) __all__ = [ "param", - "build_bijectors", "constrain", "unconstrain", - "build_trainables", - "trainable_params", + "stop_gradients", ] From a7f4f656f81afc6bf001fb0df2bb6a3206a996a1 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 13:23:56 +0000 Subject: [PATCH 07/81] Update README.md --- README.md | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 31381f2..3c8b036 100644 --- a/README.md +++ b/README.md @@ -15,36 +15,33 @@ import jax.numpy as jnp import jax.random as jr import optax as ox +# (1) Create a dataset: +X = jnp.linspace(0.0, 1.0, 20).reshape(-1, 1) +y = 2.0 * X + 1.0 + jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) +D = ju.Dataset(X, y) -class LinearModel(ju.Base): + +# (2) Define your model: +class LinearModel(ju.Module): weight: float = ju.param(Identity) bias: float = ju.param(Identity) def __call__(self, x): return self.weight * x + self.bias +model = LinearModel(weight=1.0, bias=1.0) + -class LeastSquares(ju.Objective): +# (3) Define your loss function: +class MeanSqaureError(ju.Objective): def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: return jnp.sum((train_data.y - model(train_data.X)) ** 2) +loss = MeanSqaureError() - -x = jnp.linspace(0.0, 1.0, 20).reshape(-1, 1) -y = 2.0 * x + 1.0 + jr.normal(jr.PRNGKey(0), x.shape).reshape(-1, 1) - -D = ju.Dataset(x, y) - -m = LinearModel(weight=1.0, bias=1.0) -bij = ju.build_bijectors(m) -tr = ju.build_trainables(m) -loss = LeastSquares() - - -infst = ju.fit(loss, m, bij, tr, D, ox.sgd(0.01), 10000) - -model = infst.model +# (4) Train! +model, hist = ju.fit(loss, model, D, ox.sgd(0.01), 10000) print(model.weight, model.bias) ``` From 2aa295c7a170434c8f83ae3b52f601dd2810a1d5 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 14:42:42 +0000 Subject: [PATCH 08/81] Remove config. Drop distrax. --- jaxutils/__init__.py | 6 +- jaxutils/abstractions.py | 186 ++++++++++++------------- jaxutils/{bijector.py => bijectors.py} | 28 +++- jaxutils/config.py | 150 -------------------- jaxutils/data.py | 3 + jaxutils/module.py | 3 +- jaxutils/params.py | 9 +- setup.py | 1 - tests/test_config.py | 76 ---------- 9 files changed, 129 insertions(+), 333 deletions(-) rename jaxutils/{bijector.py => bijectors.py} (54%) delete mode 100644 jaxutils/config.py delete mode 100644 tests/test_config.py diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index f71c1ac..e71d383 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,9 +13,8 @@ # limitations under the License. # ============================================================================== - from .module import Module -from .bijector import Bijector +from .bijectors import Bijector, Identity, Softplus from .objective import Objective from .data import Dataset, verify_dataset from .params import param, constrain, unconstrain @@ -33,10 +32,11 @@ "https://github.com//JaxGaussianProcesses/JaxUtils/graphs/contributors" ) - __all__ = [ "Module", "Bijector", + "Identity", + "Softplus", "Objective", "Dataset", "verify_dataset", diff --git a/jaxutils/abstractions.py b/jaxutils/abstractions.py index 20b477d..298dd73 100644 --- a/jaxutils/abstractions.py +++ b/jaxutils/abstractions.py @@ -22,6 +22,7 @@ from jax.random import KeyArray from jaxtyping import Array, Float +from typing import Any from .params import constrain, stop_gradients, unconstrain from .module import Module @@ -31,12 +32,15 @@ from .progress_bar import progress_bar_scan + def fit( - objective: Objective, model: Module, + objective: Objective, train_data: Dataset, - optax_optim: ox.GradientTransformation, + optim: ox.GradientTransformation, num_iters: Optional[int] = 100, + batch_size: Optional[int] = -1, + key: Optional[KeyArray] = jr.PRNGKey(42), log_rate: Optional[int] = 10, verbose: Optional[bool] = True, ) -> Tuple[Module, Array]: @@ -48,8 +52,10 @@ def fit( model (eqx.Module): The model that is to be optimised. bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. - optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. + optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. + batch_size (Optional[int]): The size of the mini-batch to use. Defaults to -1 (i.e. full batch). + key (Optional[KeyArray]): The random key to use for the optimisation batch selection. Defaults to jr.PRNGKey(42). log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. @@ -57,119 +63,56 @@ def fit( Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ - # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False - def loss(model: Module) -> Float[Array, "1"]: + _check_types(model, objective, train_data, optim, num_iters, log_rate, verbose, None, None) + + # Unconstrained space loss function with stop-gradient rule for non-trainable params. + def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: model = stop_gradients(model) model = constrain(model) - return objective(model, train_data) + return objective(model, batch) - # Tranform model to unconstrained space + # Unconstrained space model. model = unconstrain(model) - # Initialise optimiser state - opt_state = optax_optim.init(model) + # Initialise optimiser state. + state = optim.init(model) - # Iteration loop numbers to scan over + # Mini-batch random keys and iteration loop numbers to scan over. + iter_keys = jr.split(key, num_iters) iter_nums = jnp.arange(num_iters) + # Optimisation step - def step(carry, iter_num: int): + def step(carry, iter_num__and__key): + iter_num, key = iter_num__and__key model, opt_state = carry - loss_val, loss_gradient = jax.value_and_grad(loss)(model) - updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) + + if batch_size == -1: + batch = train_data + + if batch_size != -1: + batch = get_batch(train_data, batch_size, key) + + loss_val, loss_gradient = jax.value_and_grad(loss)(model, batch) + updates, opt_state = optim.update(loss_gradient, opt_state, model) model = ox.apply_updates(model, updates) + carry = model, opt_state return carry, loss_val - # Display progress bar if verbose is True + # Progress bar, if verbose True. if verbose: step = progress_bar_scan(num_iters, log_rate)(step) - # Run the optimisation loop - (model, _), history = jax.lax.scan(step, (model, opt_state), iter_nums) + # Optimisation loop. + (model, _), history = jax.lax.scan(step, (model, state), (iter_nums, iter_keys)) - # Tranform final model to constrained space + # Constrained space. model = constrain(model) return model, history -# def fit_batches( -# objective: Objective, -# model: eqx.Module, -# bijectors: eqx.Module, -# trainables: eqx.Module, -# train_data: Dataset, -# optax_optim: ox.GradientTransformation, -# key: KeyArray, -# batch_size: int, -# num_iters: Optional[int] = 100, -# log_rate: Optional[int] = 10, -# verbose: Optional[bool] = True, -# ) -> Tuple[eqx.Module, Array]: -# """Abstracted method for fitting a GP model with mini-batches respect to a -# supplied objective function. -# Optimisers used here should originate from Optax. - -# Args: -# objective (Objective): The objective function that we are optimising with respect to. -# model (eqx.Module): The model that is to be optimised. -# bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. -# trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. -# train_data (Dataset): The training dataset. -# optax_optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. -# key (KeyArray): The PRNG key for the mini-batch sampling. -# batch_size (int): The batch_size. -# num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. -# log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. -# verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. - -# Returns: -# Tuple[eqx.Module, Array]: A Tuple comprising the optimised model and training history respectively. -# """ - -# # Define optimisation loss function on unconstrained space, with a stop gradient rule for trainables that are set to False -# def loss(model: eqx.Module, batch: Dataset) -> Float[Array, "1"]: -# model = trainable_params(model, trainables) -# model = constrain(model, bijectors) -# return objective(model, batch) - -# # Tranform model to unconstrained space -# model = unconstrain(model, bijectors) - -# # Initialise optimiser state -# opt_state = optax_optim.init(model) - -# # Mini-batch random keys and iteration loop numbers to scan over -# keys = jr.split(key, num_iters) -# iter_nums = jnp.arange(num_iters) - -# # Optimisation step -# def step(carry, iter_num__and__key): -# iter_num, key = iter_num__and__key -# model, opt_state = carry - -# batch = get_batch(train_data, batch_size, key) - -# loss_val, loss_gradient = eqx.filter_value_and_grad(loss)(model, batch) -# updates, opt_state = optax_optim.update(loss_gradient, opt_state, model) -# model = eqx.apply_updates(model, updates) - -# carry = model, opt_state -# return carry, loss_val - -# # Display progress bar if verbose is True -# if verbose: -# step = progress_bar_scan(num_iters, log_rate)(step) - -# # Run the optimisation loop -# (model, _), history = jax.lax.scan(step, (model, opt_state), (iter_nums, keys)) - -# # Tranform final params to constrained space -# model = constrain(model, bijectors) - -# return model, history - def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: """Batch the data into mini-batches. Sampling is done with replacement. @@ -183,12 +126,67 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: """ x, y, n = train_data.X, train_data.y, train_data.n - # Subsample data inidicies with replacement to get the mini-batch + # Subsample mini-batch indicies with replacement. indicies = jr.choice(key, n, (batch_size,), replace=True) return Dataset(X=x[indicies], y=y[indicies]) + +def _check_types( + model: Any, + objective: Any, + train_data: Any, + optax_optim: Any, + num_iters: Any, + log_rate: Any, + verbose: Any, + key: Any, + batch_size: Any, + ) -> None: + + if not isinstance(model, Module): + raise TypeError("model must be of type jaxutils.Module") + + if not isinstance(objective, Objective): + raise TypeError("objective must be of type jaxutils.Objective") + + if not isinstance(train_data, Dataset): + raise TypeError("train_data must be of type jaxutils.Dataset") + + if not isinstance(optax_optim, ox.GradientTransformation): + raise TypeError("optax_optim must be of type optax.GradientTransformation") + + if not isinstance(num_iters, int): + raise TypeError("num_iters must be of type int") + + if not num_iters > 0: + raise ValueError("num_iters must be positive, but got num_iters={num_iters}") + + if not isinstance(log_rate, int): + raise TypeError(f"log_rate must be of type int") + + if not log_rate > 0: + raise ValueError(f"log_rate must be positive, but got log_rate={log_rate}") + + if not isinstance(verbose, bool): + raise TypeError("verbose must be of type bool") + + if key is not None: + if not isinstance(key, KeyArray): + raise TypeError("key must be of type jax.random.KeyArray") + + if batch_size is not None: + if not isinstance(batch_size, int): + raise TypeError("batch_size must be of type int") + + if not batch_size > 0: + raise ValueError(f"batch_size must be positive, but got batch_size={batch_size}") + + if not batch_size < train_data.n: + raise ValueError(f"batch_size must be less than train_data.n, but got batch_size={batch_size} and train_data.n={train_data.n}") + + __all__ = [ "fit", "fit_natgrads", diff --git a/jaxutils/bijector.py b/jaxutils/bijectors.py similarity index 54% rename from jaxutils/bijector.py rename to jaxutils/bijectors.py index 64f1696..0ccdcf8 100644 --- a/jaxutils/bijector.py +++ b/jaxutils/bijectors.py @@ -14,13 +14,35 @@ # ============================================================================== import equinox as eqx +import jax.numpy as jnp +from typing import Callable class Bijector(eqx.Module): - """Base class for bijectors.""" - # This is for typing. We will develop equinox bijectors as part of a separate probabilistic programming library in future. - pass + """Base class for bijectors. + + All you need to do is define a forward and inverse transformation. + + Adding log_det_jacobian's etc., is on the TODO list of this class. + """ + forward: Callable = eqx.static_field() + inverse: Callable = eqx.static_field() + + +"""Identity bijector.""" +Identity = Bijector(forward=lambda x: x, inverse=lambda x: x) + +"""Softplus bijector.""" +Softplus = Bijector( + forward=lambda x: jnp.log(1 + jnp.exp(x)), + inverse=lambda x: jnp.log(jnp.exp(x) - 1.0), +) + +"""Triangular bijector.""" +#TODO: Add triangular bijector. __all__ = [ "Bijector", + "Identity", + "Softplus", ] diff --git a/jaxutils/config.py b/jaxutils/config.py deleted file mode 100644 index 06966bb..0000000 --- a/jaxutils/config.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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 jax -import distrax as dx -import jax.numpy as jnp -import jax.random as jr -import tensorflow_probability.substrates.jax.bijectors as tfb -from ml_collections import ConfigDict - -__config = None - -Identity = dx.Lambda(forward=lambda x: x, inverse=lambda x: x) -Softplus = dx.Lambda( - forward=lambda x: jnp.log(1 + jnp.exp(x)), - inverse=lambda x: jnp.log(jnp.exp(x) - 1.0), -) - - -def reset_global_config() -> None: - global __config - __config = get_default_config() - - -def get_global_config() -> ConfigDict: - """Get the global config file used within GPJax. - - Returns: - ConfigDict: A `ConfigDict` describing parameter transforms and default values. - """ - global __config - - if __config is None: - __config = get_default_config() - return __config - - # If the global config is available, check if the x64 state has changed - x64_state = jax.config.x64_enabled - - # If the x64 state has not changed, return the existing global config - if x64_state is __config.x64_state: - return __config - - # If the x64 state has changed, return the updated global config - update_x64_sensitive_settings() - return __config - - -def update_x64_sensitive_settings() -> None: - """Update the global config if x64 state changes.""" - global __config - - # Update the x64 state - x64_state = jax.config.x64_enabled - __config.x64_state = x64_state - - # Update the x64 sensitive bijectors - FillScaleTriL = dx.Chain( - [ - tfb.FillScaleTriL(diag_shift=jnp.array(__config.jitter)), - ] - ) - - transformations = __config.transformations - transformations.triangular_transform = FillScaleTriL - - -def get_default_config() -> ConfigDict: - """Construct and return the default config file. - - Returns: - ConfigDict: A `ConfigDict` describing parameter transforms and default values. - """ - - config = ConfigDict(type_safe=False) - config.key = jr.PRNGKey(123) - - # Set the x64 state - config.x64_state = jax.config.x64_enabled - - # Covariance matrix stabilising jitter - config.jitter = 1e-6 - - # FillScaleTriL = dx.Chain( - # [ - # tfb.FillScaleTriL(diag_shift=jnp.array(config.jitter)), - # ] - # ) - - # # Default bijections - # config.transformations = transformations = ConfigDict() - # transformations.positive_transform = Softplus - # transformations.identity_transform = Identity - # transformations.triangular_transform = FillScaleTriL - - # # Default parameter transforms - # transformations.alpha = "positive_transform" - # transformations.lengthscale = "positive_transform" - # transformations.variance = "positive_transform" - # transformations.smoothness = "positive_transform" - # transformations.shift = "positive_transform" - # transformations.obs_noise = "positive_transform" - # transformations.latent = "identity_transform" - # transformations.basis_fns = "identity_transform" - # transformations.offset = "identity_transform" - # transformations.inducing_inputs = "identity_transform" - # transformations.variational_mean = "identity_transform" - # transformations.variational_root_covariance = "triangular_transform" - # transformations.natural_vector = "identity_transform" - # transformations.natural_matrix = "identity_transform" - # transformations.expectation_vector = "identity_transform" - # transformations.expectation_matrix = "identity_transform" - - return config - - -# This function is created for testing purposes only -def get_global_config_if_exists() -> ConfigDict: - """Get the global config file used within GPJax if it is available. - - Returns: - ConfigDict: A `ConfigDict` describing parameter transforms and default values. - """ - global __config - return __config - - -def add_parameter(param_name: str, bijection: dx.Bijector) -> None: - """Add a parameter and its corresponding transform to GPJax's config file. - - Args: - param_name (str): The name of the parameter that is to be added. - bijection (dx.Bijector): The bijection that should be used to unconstrain the parameter's value. - """ - lookup_name = f"{param_name}_transform" - get_global_config() - __config.transformations[lookup_name] = bijection - __config.transformations[param_name] = lookup_name \ No newline at end of file diff --git a/jaxutils/data.py b/jaxutils/data.py index cdf6487..4c24364 100644 --- a/jaxutils/data.py +++ b/jaxutils/data.py @@ -118,6 +118,9 @@ def _check_shape(X: Float[Array, "N D"], y: Float[Array, "N Q"]) -> None: f"y must be a 2-dimensional array. Got y.ndim={y.ndim}." ) + __all__ = [ "Dataset", + "slice", + "verify_dataset", ] diff --git a/jaxutils/module.py b/jaxutils/module.py index 138d5ea..453db40 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -19,6 +19,7 @@ import equinox as eqx +from .bijectors import Bijector class _cache_property_comprising_static_fields: @@ -102,7 +103,7 @@ def _default_bijectors(obj: Module) -> eqx.Module: _, treedef = jtu.tree_flatten(obj) - def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[None]: + def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[Bijector]: """Unpack bijectors from metatdata.""" bijectors = [] diff --git a/jaxutils/params.py b/jaxutils/params.py index 79c073c..67ca48b 100644 --- a/jaxutils/params.py +++ b/jaxutils/params.py @@ -18,7 +18,7 @@ import jax.tree_util as jtu from jax import lax -from .bijector import Bijector +from .bijectors import Bijector from .module import Module @@ -27,7 +27,6 @@ def param(transform: Bijector): Args: transform: A bijector to apply to the parameter. - static: Whether the parameter is static or not. Returns: A field with the metadata set. @@ -67,14 +66,14 @@ def unconstrain(obj: Module) -> Module: def stop_gradients(obj: Module) -> Module: """ - Stop the gradients flowing through parameters whose trainable status is + Stop gradients flowing through parameters whose correponding leaf node status in the trainables PyTree is False. Args: - module (eqx.Module): The equinox Module to set the trainability of. + module (Module): The jaxutils Module to set the trainability of. Returns: - eqx.Module: The equinox Module of parameters with stopped gradients. + Module: The jaxutils Module of parameters with stopped gradients. """ return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), obj, obj.trainables) diff --git a/setup.py b/setup.py index dd69fb9..916f41c 100644 --- a/setup.py +++ b/setup.py @@ -42,7 +42,6 @@ def get_versions(): "jaxlib>=0.4.0", "jaxtyping", "ml-collections==0.1.0", - "distrax>=0.1.2", ] EXTRAS = { diff --git a/tests/test_config.py b/tests/test_config.py deleted file mode 100644 index 08ceaf1..0000000 --- a/tests/test_config.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright 2022 The GPJax Contributors. 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 -# -# 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 jax -import distrax as dx -from jax.config import config -from ml_collections import ConfigDict - -from jaxutils.config import ( - Identity, - add_parameter, - get_global_config, - get_global_config_if_exists, # ignore: unused-import -) - -# Enable Float64 for more stable matrix inversions. -config.update("jax_enable_x64", True) - -# TODO: Fix this test. -# This test needs to be run first to ensure that the global config is not set on library import. -# def test_config_on_library_import(): -# config = get_global_config_if_exists() -# assert config is None - - -def test_add_parameter(): - add_parameter("test_parameter", Identity) - config = get_global_config() - assert "test_parameter" in config.transformations - assert "test_parameter_transform" in config.transformations - assert config.transformations["test_parameter"] == "test_parameter_transform" - assert isinstance(config.transformations["test_parameter_transform"], dx.Bijector) - - -def test_add_parameter(): - config = get_global_config() - add_parameter("test_parameter", Identity) - config = get_global_config() - assert "test_parameter" in config.transformations - assert "test_parameter_transform" in config.transformations - assert config.transformations["test_parameter"] == "test_parameter_transform" - assert isinstance(config.transformations["test_parameter_transform"], dx.Bijector) - - -def test_get_global_config(): - config = get_global_config() - assert isinstance(config, ConfigDict) - assert isinstance(config.transformations, ConfigDict) - - -def test_x64_based_config_update(): - cached_jax_precision = jax.config.x64_enabled - - jax.config.update("jax_enable_x64", True) - config = get_global_config() - assert config.x64_state is True - - jax.config.update("jax_enable_x64", False) - config = get_global_config() - assert config.x64_state is False - - # Reset the JAX precision to the original value. - jax.config.update("jax_enable_x64", cached_jax_precision) - get_global_config() From 1c22a87a9ee99e7ae3f78f9c5c2d9af7875fc5d8 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 14:44:07 +0000 Subject: [PATCH 09/81] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3c8b036..c7ed7a5 100644 --- a/README.md +++ b/README.md @@ -9,14 +9,14 @@ ```python import jaxutils as ju -from jaxutils.config import Identity +from jaxutils.bijectors import Identity import jax.numpy as jnp import jax.random as jr import optax as ox # (1) Create a dataset: -X = jnp.linspace(0.0, 1.0, 20).reshape(-1, 1) +X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) y = 2.0 * X + 1.0 + jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) D = ju.Dataset(X, y) @@ -41,13 +41,13 @@ class MeanSqaureError(ju.Objective): loss = MeanSqaureError() # (4) Train! -model, hist = ju.fit(loss, model, D, ox.sgd(0.01), 10000) +model, hist = ju.fit(model, loss, D, ox.sgd(0.0001), 10000) +# (5) Check the results: print(model.weight, model.bias) ``` - # Contents - TO UPDATE. - [PyTree](#pytree) From 1cc7b543a052697de493b6de5bad65c778d55826 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 15:14:33 +0000 Subject: [PATCH 10/81] Update README.md --- README.md | 90 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 47 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index c7ed7a5..441008d 100644 --- a/README.md +++ b/README.md @@ -2,84 +2,88 @@ [![CircleCI](https://dl.circleci.com/status-badge/img/gh/JaxGaussianProcesses/JaxUtils/tree/master.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/JaxGaussianProcesses/JaxUtils/tree/master) -`JaxUtils` provides utility functions for the [`JaxGaussianProcesses`]() ecosystem. +[`JaxUtils`](https://github.com/JaxGaussianProcesses/JaxUtils) is a lightweight library built on [`Equinox`](https://github.com/patrick-kidger/equinox) purposed to provide clean (and fast) model training functionality. This library also serves as a backend for the [`JaxGaussianProcesses`]() ecosystem. -## Training a Linear Model is easy peasy. -```python -import jaxutils as ju +# Contents + +- [Overview](#overview) +- [Dataset](#dataset) + +# Overview + +## ... -from jaxutils.bijectors import Identity +## ... +## Linear Model example. + +We fit a simple one-dimensional linear regression model with a `weight` and a `bias` parameter. + +### (1) Ceate a dataset + +```python +# Import dependancies. +import jaxutils as ju import jax.numpy as jnp import jax.random as jr import optax as ox -# (1) Create a dataset: + +# Simulate labels. +key = jr.PRNGKey(42) X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) -y = 2.0 * X + 1.0 + jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) +y = 2.0 * X + 1.0 + jr.normal(key, X.shape) + +# Create dataset object. D = ju.Dataset(X, y) +``` +### (2) Define your model -# (2) Define your model: +A model is defined through inheriting from the `JaxUtils`'s `Module` object. + +```python class LinearModel(ju.Module): - weight: float = ju.param(Identity) - bias: float = ju.param(Identity) + weight: float = ju.param(ju.Identity) + bias: float = ju.param(ju.Identity) def __call__(self, x): return self.weight * x + self.bias model = LinearModel(weight=1.0, bias=1.0) +``` + +The parameters are marked via the `param` field, whose argument is the default `Bijector` transformation for mapping the parameters to the unconstrained space for optimisation. In this case both of our `weight` and `bias` parameters are defined on the reals, so we use the `Identity` transform. Just like in typicall `Equinox` code, we can (optionally) define a foward pass of the model through the `__call__` method. + + + +### (3) Define your objective +We can define any objective function, such as the mean-square-error, via inheriting from the `Objective` object as follows. -# (3) Define your loss function: +```python class MeanSqaureError(ju.Objective): def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: return jnp.sum((train_data.y - model(train_data.X)) ** 2) loss = MeanSqaureError() - -# (4) Train! -model, hist = ju.fit(model, loss, D, ox.sgd(0.0001), 10000) - -# (5) Check the results: -print(model.weight, model.bias) ``` +### (4) Train! -# Contents - TO UPDATE. - -- [PyTree](#pytree) -- [Dataset](#dataset) - -# PyTree - -## Overview - -`jaxutils.PyTree` is a mixin class for [registering a python class as a JAX PyTree](https://jax.readthedocs.io/en/latest/pytrees.html#extending-pytrees). You would define your Python class as follows. +We are now ready to train our model. This can simply be done using the `fit` callable. ```python -class MyClass(jaxutils.PyTree): - ... +# Optimisation loop. +model, hist = ju.fit(model, loss, D, ox.sgd(0.0001), 10000) +# Print parameter values. +print(model.weight, model.bias) ``` -## Example - -```python -import jaxutils - -from jaxtyping import Float, Array -class Line(jaxutils.PyTree): - def __init__(self, gradient: Float[Array, "1"], intercept: Float[Array, "1"]) -> None - self.gradient = gradient - self.intercept = intercept - - def y(self, x: Float[Array, "N"]) -> Float[Array, "N"] - return x * self.gradient + self.intercept -``` # Dataset From 74384788d50c44ab53005aeb110699ab656974d4 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 15:50:29 +0000 Subject: [PATCH 11/81] Refactor. --- jaxutils/__init__.py | 7 +- jaxutils/{data.py => dataset.py} | 0 jaxutils/{abstractions.py => fit.py} | 6 +- jaxutils/module.py | 93 ++++++-- jaxutils/objective.py | 2 +- jaxutils/params.py | 87 -------- tests/{test_data.py => test_dataset.py} | 2 +- tests/test_params.py | 273 ------------------------ 8 files changed, 86 insertions(+), 384 deletions(-) rename jaxutils/{data.py => dataset.py} (100%) rename jaxutils/{abstractions.py => fit.py} (98%) delete mode 100644 jaxutils/params.py rename tests/{test_data.py => test_dataset.py} (98%) delete mode 100644 tests/test_params.py diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index e71d383..ee38028 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,12 +13,11 @@ # limitations under the License. # ============================================================================== -from .module import Module +from .module import Module, param, constrain, unconstrain from .bijectors import Bijector, Identity, Softplus from .objective import Objective -from .data import Dataset, verify_dataset -from .params import param, constrain, unconstrain -from .abstractions import fit, get_batch +from .dataset import Dataset, verify_dataset +from .fit import fit, get_batch from .progress_bar import progress_bar_scan diff --git a/jaxutils/data.py b/jaxutils/dataset.py similarity index 100% rename from jaxutils/data.py rename to jaxutils/dataset.py diff --git a/jaxutils/abstractions.py b/jaxutils/fit.py similarity index 98% rename from jaxutils/abstractions.py rename to jaxutils/fit.py index 298dd73..28fef3f 100644 --- a/jaxutils/abstractions.py +++ b/jaxutils/fit.py @@ -24,10 +24,8 @@ from jaxtyping import Array, Float from typing import Any -from .params import constrain, stop_gradients, unconstrain -from .module import Module - -from .data import Dataset +from .module import Module, constrain, unconstrain, stop_gradients +from .dataset import Dataset from .objective import Objective from .progress_bar import progress_bar_scan diff --git a/jaxutils/module.py b/jaxutils/module.py index 453db40..f924281 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -14,11 +14,13 @@ # ============================================================================== import jax.tree_util as jtu -from dataclasses import fields -from typing import List +from jax import lax +from dataclasses import fields, field +from typing import List import equinox as eqx + from .bijectors import Bijector @@ -42,6 +44,8 @@ def __get__(self, instance, owner): return value + + class Module(eqx.Module): """Base class for all objects of the JaxGaussianProcesses ecosystem.""" @@ -69,41 +73,40 @@ def bijectors(self): @_cache_property_comprising_static_fields def trainables(self): + """Return a default PyTree of model trainability statuses.""" return _default_trainables(self) -def _default_trainables(obj: Module) -> eqx.Module: +def _default_trainables(obj: Module) -> Module: """ - Construct a dictionary of trainable statuses for each parameter. By default, + Construct trainable statuses for each parameter. By default, every parameter within the model is trainable. Args: - obj (Dict): The parameter set for which trainable statuses should be + obj (Module): The parameter set for which trainable statuses should be derived from. - status (bool): The status of each parameter. Default is True. Returns: - Dict: A dictionary of boolean trainability statuses. The dictionary is - equal in structure to the input params dictionary. + Module: A Module of boolean trainability statuses. """ return jtu.tree_map(lambda _: True, obj) -def _default_bijectors(obj: Module) -> eqx.Module: - """Given a Base object, return an equinox Module of bijectors comprising the same structure. +def _default_bijectors(obj: Module) -> Module: + """Given a Module object, return an equinox Module of bijectors comprising the same structure. Args: - obj(Base): A Base object. + obj(Module): A Module object. Returns: - eqx.Module: A Module of bijectors. + Module: A Module of bijectors. """ _, treedef = jtu.tree_flatten(obj) - def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[Bijector]: + def _unpack_bijectors_from_meta(cls: Module) -> List[Bijector]: """Unpack bijectors from metatdata.""" bijectors = [] @@ -121,7 +124,7 @@ def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[Bijector]: trans = field_.metadata["transform"] bijectors.append(trans) - elif isinstance(value, eqx.Module): + elif isinstance(value, Module): for value_ in _unpack_bijectors_from_meta(value): bijectors.append(value_) @@ -134,7 +137,69 @@ def _unpack_bijectors_from_meta(cls: eqx.Module) -> List[Bijector]: +def param(transform: Bijector): + """Set leaf node metadata for a parameter. + + Args: + transform: A bijector to apply to the parameter. + + Returns: + A field with the metadata set. + """ + return field(metadata={"transform": transform}) + + +def constrain(obj: Module) -> Module: + """ + Transform model parameters to the constrained space for corresponding + bijectors. + + Args: + obj (Module): The Base that is to be transformed. + + Returns: + Base: A transformed parameter set. The dictionary is equal in + structure to the input params dictionary. + """ + return jtu.tree_map(lambda p, t: t.forward(p), obj, obj.bijectors) + + +def unconstrain(obj: Module) -> Module: + """ + Transform model parameters to the unconstrained space for corresponding + bijectors. + + Args: + obj (Module): The Base that is to be transformed. + + Returns: + Base: A transformed parameter set. The dictionary is equal in + structure to the input params dictionary. + """ + return jtu.tree_map(lambda p, t: t.inverse(p), obj, obj.bijectors) + + +def stop_gradients(obj: Module) -> Module: + """ + Stop gradients flowing through parameters whose correponding leaf node status in the trainables PyTree is + False. + + Args: + module (Module): The jaxutils Module to set the trainability of. + + Returns: + Module: The jaxutils Module of parameters with stopped gradients. + """ + + return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), obj, obj.trainables) + + + __all__ = [ "Module", + "param", + "constrain", + "unconstrain", + "stop_gradients", ] diff --git a/jaxutils/objective.py b/jaxutils/objective.py index 00ffe89..cde21e9 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -16,7 +16,7 @@ import abc import equinox as eqx -from .data import Dataset +from .dataset import Dataset from .module import Module class Objective(eqx.Module): diff --git a/jaxutils/params.py b/jaxutils/params.py deleted file mode 100644 index 67ca48b..0000000 --- a/jaxutils/params.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from dataclasses import field - -import jax.tree_util as jtu -from jax import lax - -from .bijectors import Bijector -from .module import Module - - -def param(transform: Bijector): - """Set leaf node metadata for a parameter. - - Args: - transform: A bijector to apply to the parameter. - - Returns: - A field with the metadata set. - """ - return field(metadata={"transform": transform}) - - -def constrain(obj: Module) -> Module: - """ - Transform model parameters to the constrained space for corresponding - bijectors. - - Args: - obj (Module): The Base that is to be transformed. - - Returns: - Base: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. - """ - return jtu.tree_map(lambda p, t: t.forward(p), obj, obj.bijectors) - - -def unconstrain(obj: Module) -> Module: - """ - Transform model parameters to the unconstrained space for corresponding - bijectors. - - Args: - obj (Module): The Base that is to be transformed. - - Returns: - Base: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. - """ - return jtu.tree_map(lambda p, t: t.inverse(p), obj, obj.bijectors) - - -def stop_gradients(obj: Module) -> Module: - """ - Stop gradients flowing through parameters whose correponding leaf node status in the trainables PyTree is - False. - - Args: - module (Module): The jaxutils Module to set the trainability of. - - Returns: - Module: The jaxutils Module of parameters with stopped gradients. - """ - - return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), obj, obj.trainables) - - -__all__ = [ - "param", - "constrain", - "unconstrain", - "stop_gradients", -] diff --git a/tests/test_data.py b/tests/test_dataset.py similarity index 98% rename from tests/test_data.py rename to tests/test_dataset.py index 3ed45ba..8b60898 100644 --- a/tests/test_data.py +++ b/tests/test_dataset.py @@ -15,7 +15,7 @@ import jax.numpy as jnp import pytest -from jaxutils.data import Dataset, verify_dataset +from jaxutils.dataset import Dataset, verify_dataset @pytest.mark.parametrize("n", [1, 10]) diff --git a/tests/test_params.py b/tests/test_params.py deleted file mode 100644 index b532b23..0000000 --- a/tests/test_params.py +++ /dev/null @@ -1,273 +0,0 @@ -# # Copyright 2022 The GPJax Contributors. 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 -# # -# # 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 typing as tp - -# import distrax as dx -# import jax.numpy as jnp -# import jax.random as jr -# import pytest -# from jax.config import config - -# from gpjax.gps import Prior -# from gpjax.kernels import RBF -# from gpjax.likelihoods import Bernoulli, Gaussian -# from gpjax.parameters import ( -# build_bijectors, -# build_trainables, -# constrain, -# copy_dict_structure, -# evaluate_priors, -# initialise, -# log_density, -# prior_checks, -# recursive_complete, -# recursive_items, -# structure_priors, -# unconstrain, -# ) - -# # Enable Float64 for more stable matrix inversions. -# config.update("jax_enable_x64", True) - -# ######################### -# # Test base functionality -# ######################### -# @pytest.mark.parametrize("lik", [Gaussian]) -# def test_initialise(lik): -# key = jr.PRNGKey(123) -# posterior = Prior(kernel=RBF()) * lik(num_datapoints=10) -# params, _, _ = initialise(posterior, key).unpack() -# assert list(sorted(params.keys())) == [ -# "kernel", -# "likelihood", -# "mean_function", -# ] - - -# def test_non_conjugate_initialise(): -# posterior = Prior(kernel=RBF()) * Bernoulli(num_datapoints=10) -# params, _, _ = initialise(posterior, jr.PRNGKey(123)).unpack() -# assert list(sorted(params.keys())) == [ -# "kernel", -# "latent", -# "likelihood", -# "mean_function", -# ] - - -# ######################### -# # Test priors -# ######################### -# @pytest.mark.parametrize("x", [-1.0, 0.0, 1.0]) -# def test_lpd(x): -# val = jnp.array(x) -# dist = dx.Normal(loc=0.0, scale=1.0) -# lpd = log_density(val, dist) -# assert lpd is not None -# assert log_density(val, None) == 0.0 - - -# @pytest.mark.parametrize("lik", [Gaussian, Bernoulli]) -# def test_prior_template(lik): -# posterior = Prior(kernel=RBF()) * lik(num_datapoints=10) -# params, _, _ = initialise(posterior, jr.PRNGKey(123)).unpack() -# prior_container = copy_dict_structure(params) -# for ( -# k, -# v1, -# v2, -# ) in recursive_items(params, prior_container): -# assert v2 == None - - -# @pytest.mark.parametrize("lik", [Gaussian, Bernoulli]) -# def test_recursive_complete(lik): -# posterior = Prior(kernel=RBF()) * lik(num_datapoints=10) -# params, _, _ = initialise(posterior, jr.PRNGKey(123)).unpack() -# priors = {"kernel": {}} -# priors["kernel"]["lengthscale"] = dx.Laplace(loc=0.0, scale=1.0) -# container = copy_dict_structure(params) -# complete_priors = recursive_complete(container, priors) -# for ( -# k, -# v1, -# v2, -# ) in recursive_items(params, complete_priors): -# if k == "lengthscale": -# assert isinstance(v2, dx.Laplace) -# else: -# assert v2 == None - - -# def test_prior_evaluation(): -# """ -# Test the regular setup that every parameter has a corresponding prior distribution attached to its unconstrained -# value. -# """ -# params = { -# "kernel": { -# "lengthscale": jnp.array([1.0]), -# "variance": jnp.array([1.0]), -# }, -# "likelihood": {"obs_noise": jnp.array([1.0])}, -# } -# priors = { -# "kernel": { -# "lengthscale": dx.Gamma(1.0, 1.0), -# "variance": dx.Gamma(2.0, 2.0), -# }, -# "likelihood": {"obs_noise": dx.Gamma(3.0, 3.0)}, -# } -# lpd = evaluate_priors(params, priors) -# assert pytest.approx(lpd) == -2.0110168 - - -# def test_none_prior(): -# """ -# Test that multiple dispatch is working in the case of no priors. -# """ -# params = { -# "kernel": { -# "lengthscale": jnp.array([1.0]), -# "variance": jnp.array([1.0]), -# }, -# "likelihood": {"obs_noise": jnp.array([1.0])}, -# } -# priors = copy_dict_structure(params) -# lpd = evaluate_priors(params, priors) -# assert lpd == 0.0 - - -# def test_incomplete_priors(): -# """ -# Test the case where a user specifies priors for some, but not all, parameters. -# """ -# params = { -# "kernel": { -# "lengthscale": jnp.array([1.0]), -# "variance": jnp.array([1.0]), -# }, -# "likelihood": {"obs_noise": jnp.array([1.0])}, -# } -# priors = { -# "kernel": { -# "lengthscale": dx.Gamma(1.0, 1.0), -# "variance": dx.Gamma(2.0, 2.0), -# }, -# } -# container = copy_dict_structure(params) -# complete_priors = recursive_complete(container, priors) -# lpd = evaluate_priors(params, complete_priors) -# assert pytest.approx(lpd) == -1.6137061 - - -# @pytest.mark.parametrize("num_datapoints", [1, 10]) -# def test_checks(num_datapoints): -# incomplete_priors = {"lengthscale": jnp.array([1.0])} -# posterior = Prior(kernel=RBF()) * Bernoulli(num_datapoints=num_datapoints) -# priors = prior_checks(incomplete_priors) -# assert "latent" in priors.keys() -# assert "variance" not in priors.keys() -# assert isinstance(priors["latent"], dx.Normal) - - -# def test_structure_priors(): -# posterior = Prior(kernel=RBF()) * Gaussian(num_datapoints=10) -# params, _, _ = initialise(posterior, jr.PRNGKey(123)).unpack() -# priors = { -# "kernel": { -# "lengthscale": dx.Gamma(1.0, 1.0), -# "variance": dx.Gamma(2.0, 2.0), -# }, -# } -# structured_priors = structure_priors(params, priors) - -# def recursive_fn(d1, d2, fn: tp.Callable[[tp.Any], tp.Any]): -# for key, value in d1.items(): -# if type(value) is dict: -# yield from recursive_fn(value, d2[key], fn) -# else: -# yield fn(key, key) - -# for v in recursive_fn(params, structured_priors, lambda k1, k2: k1 == k2): -# assert v - - -# @pytest.mark.parametrize("latent_prior", [dx.Laplace(0.0, 1.0), dx.Laplace(0.0, 1.0)]) -# def test_prior_checks(latent_prior): -# priors = { -# "kernel": {"lengthscale": None, "variance": None}, -# "mean_function": {}, -# "liklelihood": {"variance": None}, -# "latent": None, -# } -# new_priors = prior_checks(priors) -# assert "latent" in new_priors.keys() -# assert isinstance(new_priors["latent"], dx.Normal) - -# priors = { -# "kernel": {"lengthscale": None, "variance": None}, -# "mean_function": {}, -# "liklelihood": {"variance": None}, -# } -# new_priors = prior_checks(priors) -# assert "latent" in new_priors.keys() -# assert isinstance(new_priors["latent"], dx.Normal) - -# priors = { -# "kernel": {"lengthscale": None, "variance": None}, -# "mean_function": {}, -# "liklelihood": {"variance": None}, -# "latent": latent_prior, -# } -# with pytest.warns(UserWarning): -# new_priors = prior_checks(priors) -# assert "latent" in new_priors.keys() -# assert isinstance(new_priors["latent"], dx.Laplace) - - -# ######################### -# # Test transforms -# ######################### -# @pytest.mark.parametrize("num_datapoints", [1, 10]) -# @pytest.mark.parametrize("likelihood", [Gaussian, Bernoulli]) -# def test_output(num_datapoints, likelihood): -# posterior = Prior(kernel=RBF()) * likelihood(num_datapoints=num_datapoints) -# params, _, bijectors = initialise(posterior, jr.PRNGKey(123)).unpack() - -# assert isinstance(bijectors, dict) -# for k, v1, v2 in recursive_items(bijectors, bijectors): -# assert isinstance(v1.forward, tp.Callable) -# assert isinstance(v2.inverse, tp.Callable) - -# unconstrained_params = unconstrain(params, bijectors) -# assert ( -# unconstrained_params["kernel"]["lengthscale"] != params["kernel"]["lengthscale"] -# ) -# backconstrained_params = constrain(unconstrained_params, bijectors) -# for k, v1, v2 in recursive_items(params, unconstrained_params): -# assert v1.dtype == v2.dtype - -# for k, v1, v2 in recursive_items(params, backconstrained_params): -# assert all(v1 == v2) - -# augmented_params = params -# augmented_params["test_param"] = jnp.array([1.0]) -# a_bijectors = build_bijectors(augmented_params) - -# assert "test_param" in list(a_bijectors.keys()) -# assert a_bijectors["test_param"].forward(jnp.array([1.0])) == 1.0 -# assert a_bijectors["test_param"].inverse(jnp.array([1.0])) == 1.0 From fc8010e9c6b549cc0f6d8d7fa59dbe0de94deeea Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 15:54:26 +0000 Subject: [PATCH 12/81] Create test_bijectors.py --- tests/test_bijectors.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 tests/test_bijectors.py diff --git a/tests/test_bijectors.py b/tests/test_bijectors.py new file mode 100644 index 0000000..e89529e --- /dev/null +++ b/tests/test_bijectors.py @@ -0,0 +1,36 @@ +# Copyright 2022 The JaxGaussianProcesses Contributors. 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 +# +# 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 jax.numpy as jnp +import pytest +from jaxutils.bijectors import Bijector, Identity, Softplus +from typing import Callable + +@pytest.mark.parametrize("fwd", [lambda x: x, lambda x: jnp.log(x)]) +@pytest.mark.parametrize("inv", [lambda x: x, lambda x: jnp.exp(x)]) +def test_bijector(fwd: Callable, inv: Callable) -> None: + b = Bijector(fwd, inv) + assert b.forward(1.0) == fwd(1.0) + assert b.inverse(1.0) == inv(1.0) + +def test_identity() -> None: + b = Identity + assert b.forward(10.0) == 10.0 + assert b.inverse(29.0) == 29.0 + +def test_softplus() -> None: + b = Softplus + assert b.forward(10.0) == jnp.log(1.0 + jnp.exp(10.0)) + assert b.inverse(29.0) == jnp.log(jnp.exp(29.0) - 1.0) \ No newline at end of file From 768716c43d5d3027aa6f138cae35f644acec9e10 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 16:10:09 +0000 Subject: [PATCH 13/81] Create test_objective.py --- tests/test_objective.py | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 tests/test_objective.py diff --git a/tests/test_objective.py b/tests/test_objective.py new file mode 100644 index 0000000..36088c5 --- /dev/null +++ b/tests/test_objective.py @@ -0,0 +1,47 @@ +# Copyright 2022 The JaxGaussianProcesses Contributors. 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 +# +# 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 jax.numpy as jnp +import pytest +from jaxutils.objective import Objective +from jaxutils.module import Module +from jaxutils.dataset import Dataset + +def test_objective() -> None: + with pytest.raises(TypeError): + Objective(negative=False) + + with pytest.raises(TypeError): + Objective(negative=True) + + class DummyModel(Module): + def __call__(self, x: jnp.ndarray) -> jnp.ndarray: + return x + + class DummyObjective(Objective): + def evaluate(self, model: Module, train_data: Dataset) -> float: + return jnp.sum((model(train_data.X) - train_data.y) ** 2) + + + # Test intialisation + objective = DummyObjective() + model = DummyModel() + data = Dataset(jnp.ones((10, 1)), jnp.ones((10, 1))) + assert objective(model, data) == 0.0 + + # Test negative + data_new = Dataset(jnp.linspace(0, 1, 10).reshape(-1, 1), jnp.linspace(2, 5, 10).reshape(-1, 1)) + objective_negative = DummyObjective(negative=True) + assert objective(model, data_new) + objective_negative(model, data_new) == 0.0 \ No newline at end of file From 6b1029aca44986cd960521268deceabffab96a85 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Feb 2023 23:01:16 +0000 Subject: [PATCH 14/81] Update. --- jaxutils/fit.py | 17 ++++----- jaxutils/module.py | 83 ++++++++++------------------------------ jaxutils/objective.py | 4 +- jaxutils/params.py | 33 ++++++++++++++++ tests/test_fit.py | 20 ++++++++++ tests/test_module.py | 85 +++++++++++++++++++++++++++++++++++++++++ tests/test_objective.py | 9 ++++- 7 files changed, 177 insertions(+), 74 deletions(-) create mode 100644 jaxutils/params.py create mode 100644 tests/test_fit.py create mode 100644 tests/test_module.py diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 28fef3f..6ed4513 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -29,9 +29,11 @@ from .objective import Objective from .progress_bar import progress_bar_scan +import equinox as eqx def fit( + *, model: Module, objective: Objective, train_data: Dataset, @@ -46,10 +48,8 @@ def fit( Optimisers used here should originate from Optax. Args: - objective (Objective): The objective function that we are optimising with respect to. model (eqx.Module): The model that is to be optimised. - bijectors (eqx.Module): The bijectors that are to be used to transform the model parameters. - trainables (eqx.Module): The trainables that are to be used to determine which parameters are to be optimised. + objective (Objective): The objective function that we are optimising with respect to. optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. batch_size (Optional[int]): The size of the mini-batch to use. Defaults to -1 (i.e. full batch). @@ -61,7 +61,7 @@ def fit( Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ - _check_types(model, objective, train_data, optim, num_iters, log_rate, verbose, None, None) + _check_types(model, objective, train_data, optim, num_iters, log_rate, verbose, key, batch_size) # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: @@ -169,17 +169,16 @@ def _check_types( if not isinstance(verbose, bool): raise TypeError("verbose must be of type bool") - - if key is not None: - if not isinstance(key, KeyArray): - raise TypeError("key must be of type jax.random.KeyArray") if batch_size is not None: if not isinstance(batch_size, int): raise TypeError("batch_size must be of type int") if not batch_size > 0: - raise ValueError(f"batch_size must be positive, but got batch_size={batch_size}") + if batch_size == -1: + pass + else: + raise ValueError(f"batch_size must be positive, but got batch_size={batch_size}") if not batch_size < train_data.n: raise ValueError(f"batch_size must be less than train_data.n, but got batch_size={batch_size} and train_data.n={train_data.n}") diff --git a/jaxutils/module.py b/jaxutils/module.py index f924281..15ab76e 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -13,6 +13,8 @@ # limitations under the License. # ============================================================================== +from __future__ import annotations + import jax.tree_util as jtu from jax import lax @@ -24,81 +26,32 @@ from .bijectors import Bijector -class _cache_property_comprising_static_fields: - """Be careful with this --- highly JAX incompatible!! - - Courtesy of Kernex. - - Fine for properties that depend *only* on static fields. For dynamic fields, this will end in tears. - """ - - def __init__(self, prop): - """ Does your prop have a dynamic field? If so, STOP!""" - - self.name = prop.__name__ - self.prop = prop - - def __get__(self, instance, owner): - value = self.prop(instance) - object.__setattr__(instance, self.name, value) - return value - - - - class Module(eqx.Module): """Base class for all objects of the JaxGaussianProcesses ecosystem.""" - - # TODO: Add checks for param fields. WE NEED TO ENSURE ALL LEAVES ARE PARAMS AND ONLY PARAMS. - - def set_bijectors(self, bijectors): - - # TODO: Throwin hostcall back warning. This completely breaks the immutability of the object. - # YOU DO NOT WANT TO DO THIS WITHIN A JIT REGION. - # Really, this is a hack. We need to create a new object not modify the existing one. - object.__setattr__(self, "bijectors", bijectors) - - def set_trainables(self, trainables): - - # TODO: Throwin hostcall back warning. This completely breaks the immutability of the object. - # YOU DO NOT WANT TO DO THIS WITHIN A JIT REGION. - # Really, this is a hack. We need to create a new object not modify the existing one. - object.__setattr__(self, "trainables", trainables) - - - @_cache_property_comprising_static_fields - def bijectors(self): - """Return a default PyTree of model bijectors.""" - return _default_bijectors(self) - - @_cache_property_comprising_static_fields + + @property def trainables(self): - """Return a default PyTree of model trainability statuses.""" - return _default_trainables(self) + return default_trainables(self) + @property + def bijectors(self): + return default_bijectors(self) -def _default_trainables(obj: Module) -> Module: +def default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, every parameter within the model is trainable. - Args: - obj (Module): The parameter set for which trainable statuses should be - derived from. - Returns: Module: A Module of boolean trainability statuses. """ return jtu.tree_map(lambda _: True, obj) -def _default_bijectors(obj: Module) -> Module: +def default_bijectors(obj: Module) -> Module: """Given a Module object, return an equinox Module of bijectors comprising the same structure. - - Args: - obj(Module): A Module object. Returns: Module: A Module of bijectors. @@ -181,19 +134,23 @@ def unconstrain(obj: Module) -> Module: def stop_gradients(obj: Module) -> Module: """ - Stop gradients flowing through parameters whose correponding leaf node status in the trainables PyTree is + Stop the gradients flowing through parameters whose trainable status is False. - Args: - module (Module): The jaxutils Module to set the trainability of. - + params (Dict): The parameter set for which trainable statuses should + be derived from. + trainables (Dict): A dictionary of boolean trainability statuses. The + dictionary is equal in structure to the input params dictionary. Returns: - Module: The jaxutils Module of parameters with stopped gradients. + Dict: A dictionary parameters. The dictionary is equal in structure to + the input params dictionary. """ - return jtu.tree_map(lambda p, t: lax.cond(t, lambda x: x, lax.stop_gradient, p), obj, obj.trainables) + def _stop_grad(p, t): + return lax.cond(t, lambda x: x, lax.stop_gradient, p) + return jtu.tree_map(lambda p, t: _stop_grad(p, t), obj, obj.trainables) __all__ = [ diff --git a/jaxutils/objective.py b/jaxutils/objective.py index cde21e9..db2c675 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -33,6 +33,9 @@ def __init__(self, negative: bool = False): Returns: Objective: An objective function. """ + + if not isinstance(negative, bool): + raise TypeError("negative must be a bool.") self.negative = negative self.constant = -1.0 if negative else 1.0 @@ -53,7 +56,6 @@ def __call__(self, model: Module, train_data: Dataset) -> float: @abc.abstractmethod def evaluate(self, model: Module, train_data: Dataset) -> float: """Evaluate the objective function.""" - raise NotImplementedError __all__ = [ diff --git a/jaxutils/params.py b/jaxutils/params.py new file mode 100644 index 0000000..3a0e0f6 --- /dev/null +++ b/jaxutils/params.py @@ -0,0 +1,33 @@ +# Copyright 2022 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from dataclasses import field + +import jax.tree_util as jtu +from jax import lax + +from .bijectors import Bijector +from .module import Module + + + + + +__all__ = [ + "param", + "constrain", + "unconstrain", + "stop_gradients", +] diff --git a/tests/test_fit.py b/tests/test_fit.py new file mode 100644 index 0000000..55543f3 --- /dev/null +++ b/tests/test_fit.py @@ -0,0 +1,20 @@ +# Copyright 2022 The JaxGaussianProcesses Contributors. 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 +# +# 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 jax.numpy as jnp +import pytest + +# Three models. + diff --git a/tests/test_module.py b/tests/test_module.py new file mode 100644 index 0000000..1ece5a0 --- /dev/null +++ b/tests/test_module.py @@ -0,0 +1,85 @@ +# Copyright 2022 The JaxGaussianProcesses Contributors. 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 +# +# 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 jax.numpy as jnp +import pytest +from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients +from jaxutils.bijectors import Bijector, Identity, Softplus +import jax.tree_util as jtu +import jax + +def test_module(): + + # Test init + class SubTree(Module): + param_c: float = param(Identity) + param_d: float = param(Softplus) + param_e: float = param(Softplus) + + class Tree(Module): + param_a: float = param(Identity) + sub_tree: SubTree + param_b: float = param(Softplus) + + tree = Tree(param_a=1.0, sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), param_b=5.0) + + assert tree.param_a == 1.0 + assert tree.sub_tree.param_c == 2.0 + assert tree.sub_tree.param_d == 3.0 + assert tree.sub_tree.param_e == 4.0 + assert tree.param_b == 5.0 + + + bijector_list = jtu.tree_leaves(tree.bijectors) + + for b1, b2 in zip(bijector_list, [Identity, Identity, Softplus, Softplus, Softplus]): + assert b1 == b2 + + trainable_list = jtu.tree_leaves(tree.trainables) + + for t1, t2 in zip(trainable_list, [True, True, True, True, True]): + assert t1 == t2 + + # Test constrain and unconstrain + constrained = constrain(tree) + unconstrained = unconstrain(tree) + + leafs = jtu.tree_leaves(tree) + + for l1, l2, bij in zip(leafs, jtu.tree_leaves(constrained), [Identity, Identity, Softplus, Softplus, Softplus]): + assert bij.forward(l1) == l2 + + for l1, l2, bij in zip(leafs, jtu.tree_leaves(unconstrained), [Identity, Identity, Softplus, Softplus, Softplus]): + assert bij.inverse(l1) == l2 + + + _, tree_def = jax.tree_flatten(tree) + tree = tree.set_trainables(tree_def.unflatten([True, False, True, False, False])) + + + # Test stop gradients + def loss(tree): + tree = stop_gradients(tree) + return jnp.sum(tree.param_a**2 + tree.sub_tree.param_c**2 + tree.sub_tree.param_d**2 + tree.sub_tree.param_e**2 + tree.param_b**2) + + g = jax.grad(loss)(tree) + + assert g.param_a == 2.0 + assert g.sub_tree.param_c == 4.0 + assert g.sub_tree.param_d == 6.0 + assert g.sub_tree.param_e == 8.0 + assert g.param_b == 10.0 + + diff --git a/tests/test_objective.py b/tests/test_objective.py index 36088c5..28a75bc 100644 --- a/tests/test_objective.py +++ b/tests/test_objective.py @@ -20,6 +20,9 @@ from jaxutils.dataset import Dataset def test_objective() -> None: + with pytest.raises(TypeError): + Objective() + with pytest.raises(TypeError): Objective(negative=False) @@ -44,4 +47,8 @@ def evaluate(self, model: Module, train_data: Dataset) -> float: # Test negative data_new = Dataset(jnp.linspace(0, 1, 10).reshape(-1, 1), jnp.linspace(2, 5, 10).reshape(-1, 1)) objective_negative = DummyObjective(negative=True) - assert objective(model, data_new) + objective_negative(model, data_new) == 0.0 \ No newline at end of file + assert objective(model, data_new) + objective_negative(model, data_new) == 0.0 + + # Test non-bool negative + with pytest.raises(TypeError): + objective_negative = DummyObjective(negative=123) \ No newline at end of file From a6d2d45fb27f213dd7f8bfbd2fbed567583424fa Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 17:39:41 +0000 Subject: [PATCH 15/81] Test module. --- jaxutils/fit.py | 24 +++++++++---- jaxutils/module.py | 84 ++++++++++++++++++++------------------------ tests/test_module.py | 26 +++++++------- 3 files changed, 70 insertions(+), 64 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 6ed4513..52d84fd 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -24,7 +24,7 @@ from jaxtyping import Array, Float from typing import Any -from .module import Module, constrain, unconstrain, stop_gradients +from .module import Module, constrain, unconstrain, stop_gradients, default_bijectors, default_trainables from .dataset import Dataset from .objective import Objective from .progress_bar import progress_bar_scan @@ -43,6 +43,8 @@ def fit( key: Optional[KeyArray] = jr.PRNGKey(42), log_rate: Optional[int] = 10, verbose: Optional[bool] = True, + bijectors: Any, + trainables: Any, ) -> Tuple[Module, Array]: """Abstracted method for fitting a GP model with respect to a supplied objective function. Optimisers used here should originate from Optax. @@ -56,21 +58,32 @@ def fit( key (Optional[KeyArray]): The random key to use for the optimisation batch selection. Defaults to jr.PRNGKey(42). log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. + bijectors (Any): The bijectors to use for the model. + trainables (Any): The trainables to use for the model. Returns: Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ _check_types(model, objective, train_data, optim, num_iters, log_rate, verbose, key, batch_size) + #TODO: Check bijectors and trainables are correct types and same structure as model. + + # Initialise bijectors from defaults if not supplied. + if bijectors is None: + bijectors = default_bijectors(model) + + # Initialise trainables from defaults if not supplied. + if trainables is None: + trainables = default_trainables(model) # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: - model = stop_gradients(model) - model = constrain(model) + model = stop_gradients(model, trainables) + model = constrain(model, bijectors) return objective(model, batch) # Unconstrained space model. - model = unconstrain(model) + model = unconstrain(model, bijectors) # Initialise optimiser state. state = optim.init(model) @@ -79,7 +92,6 @@ def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: iter_keys = jr.split(key, num_iters) iter_nums = jnp.arange(num_iters) - # Optimisation step def step(carry, iter_num__and__key): iter_num, key = iter_num__and__key @@ -106,7 +118,7 @@ def step(carry, iter_num__and__key): (model, _), history = jax.lax.scan(step, (model, state), (iter_nums, iter_keys)) # Constrained space. - model = constrain(model) + model = constrain(model, bijectors) return model, history diff --git a/jaxutils/module.py b/jaxutils/module.py index 15ab76e..9e393dd 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -16,6 +16,7 @@ from __future__ import annotations import jax.tree_util as jtu +import jax from jax import lax from dataclasses import fields, field @@ -27,16 +28,9 @@ class Module(eqx.Module): - """Base class for all objects of the JaxGaussianProcesses ecosystem.""" - - @property - def trainables(self): - return default_trainables(self) - - @property - def bijectors(self): - return default_bijectors(self) + """Base class for all objects of the JaxGaussianProcesses ecosystem.""" + #TODO: Check all (dynamic) leaf nodes are marked by the `param` field. def default_trainables(obj: Module) -> Module: @@ -52,41 +46,43 @@ def default_trainables(obj: Module) -> Module: def default_bijectors(obj: Module) -> Module: """Given a Module object, return an equinox Module of bijectors comprising the same structure. + + Args: + obj (Module): The PyTree object whoose default bijectors (from the param field) you would to obtain. Returns: - Module: A Module of bijectors. + Module: A PyTree of bijectors comprising the same structure as `obj`. """ _, treedef = jtu.tree_flatten(obj) - def _unpack_bijectors_from_meta(cls: Module) -> List[Bijector]: + def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: """Unpack bijectors from metatdata.""" - bijectors = [] + bijectors_ = [] - for field_ in fields(cls): - name = field_.name - + for field_ in fields(obj): try: - value = cls.__dict__[name] + value_ = obj.__dict__[field_.name] except KeyError: continue if not field_.metadata.get("static", False): if field_.metadata.get("transform", None) is not None: - trans = field_.metadata["transform"] - bijectors.append(trans) + bijectors_.append(field_.metadata["transform"]) - elif isinstance(value, Module): - for value_ in _unpack_bijectors_from_meta(value): - bijectors.append(value_) + elif isinstance(value_, Module): + for value__ in _unpack_bijectors_from_meta(value_): + bijectors_.append(value__) else: - bijectors.append(value) + bijectors_.append(value_) - return bijectors + return bijectors_ + + bijectors_ = _unpack_bijectors_from_meta(obj) - return treedef.unflatten(_unpack_bijectors_from_meta(obj)) + return treedef.unflatten(bijectors_) @@ -94,7 +90,7 @@ def param(transform: Bijector): """Set leaf node metadata for a parameter. Args: - transform: A bijector to apply to the parameter. + transform (Bijector): A default bijector transformation for the parameter. Returns: A field with the metadata set. @@ -102,55 +98,51 @@ def param(transform: Bijector): return field(metadata={"transform": transform}) -def constrain(obj: Module) -> Module: +def constrain(obj: Module, bij: Module) -> Module: """ Transform model parameters to the constrained space for corresponding bijectors. Args: - obj (Module): The Base that is to be transformed. + obj (Module): The PyTree object whoose leaves are to be transformed. + bij (Module): The PyTree object whoose leaves are the corresponding bijector transformations. Returns: - Base: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. + Module: PyTree tranformed to the constrained space. """ - return jtu.tree_map(lambda p, t: t.forward(p), obj, obj.bijectors) + return jtu.tree_map(lambda leaf, transform: transform.forward(leaf), obj, bij) -def unconstrain(obj: Module) -> Module: +def unconstrain(obj: Module, bij: Module) -> Module: """ Transform model parameters to the unconstrained space for corresponding bijectors. Args: - obj (Module): The Base that is to be transformed. + obj (Module): The PyTree object whoose leaves are to be transformed. + bij (Module): The PyTree object whoose leaves are the corresponding bijector transformations. Returns: - Base: A transformed parameter set. The dictionary is equal in - structure to the input params dictionary. + Module: PyTree tranformed to the unconstrained space. """ - return jtu.tree_map(lambda p, t: t.inverse(p), obj, obj.bijectors) + return jtu.tree_map(lambda leaf, transform: transform.inverse(leaf), obj, bij) -def stop_gradients(obj: Module) -> Module: +def stop_gradients(obj: Module, trn: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is False. Args: - params (Dict): The parameter set for which trainable statuses should - be derived from. - trainables (Dict): A dictionary of boolean trainability statuses. The - dictionary is equal in structure to the input params dictionary. + obj (Module): PyTree object to stop gradients for. + trn (Module): PyTree of booleans indicating whether to stop gradients for each leaf node. Returns: - Dict: A dictionary parameters. The dictionary is equal in structure to - the input params dictionary. + Module: PyTree with gradients stopped. """ - def _stop_grad(p, t): - return lax.cond(t, lambda x: x, lax.stop_gradient, p) - + def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: + return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - return jtu.tree_map(lambda p, t: _stop_grad(p, t), obj, obj.trainables) + return jtu.tree_map(lambda *_: _stop_grad(*_), obj, trn) __all__ = [ diff --git a/tests/test_module.py b/tests/test_module.py index 1ece5a0..9b18f04 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -15,7 +15,7 @@ import jax.numpy as jnp import pytest -from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients +from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients, default_bijectors, default_trainables from jaxutils.bijectors import Bijector, Identity, Softplus import jax.tree_util as jtu import jax @@ -42,19 +42,23 @@ class Tree(Module): assert tree.param_b == 5.0 - bijector_list = jtu.tree_leaves(tree.bijectors) + # Test default bijectors + bijectors = default_bijectors(tree) + bijector_list = jtu.tree_leaves(bijectors) for b1, b2 in zip(bijector_list, [Identity, Identity, Softplus, Softplus, Softplus]): assert b1 == b2 - trainable_list = jtu.tree_leaves(tree.trainables) + # Test default trainables + trainables = default_trainables(tree) + trainable_list = jtu.tree_leaves(trainables) for t1, t2 in zip(trainable_list, [True, True, True, True, True]): assert t1 == t2 # Test constrain and unconstrain - constrained = constrain(tree) - unconstrained = unconstrain(tree) + constrained = constrain(tree, bijectors) + unconstrained = unconstrain(tree, bijectors) leafs = jtu.tree_leaves(tree) @@ -66,20 +70,18 @@ class Tree(Module): _, tree_def = jax.tree_flatten(tree) - tree = tree.set_trainables(tree_def.unflatten([True, False, True, False, False])) + trainables = tree_def.unflatten([True, False, True, False, False]) # Test stop gradients def loss(tree): - tree = stop_gradients(tree) + tree = stop_gradients(tree, trainables) return jnp.sum(tree.param_a**2 + tree.sub_tree.param_c**2 + tree.sub_tree.param_d**2 + tree.sub_tree.param_e**2 + tree.param_b**2) g = jax.grad(loss)(tree) assert g.param_a == 2.0 - assert g.sub_tree.param_c == 4.0 + assert g.sub_tree.param_c == 0.0 assert g.sub_tree.param_d == 6.0 - assert g.sub_tree.param_e == 8.0 - assert g.param_b == 10.0 - - + assert g.sub_tree.param_e == 0.0 + assert g.param_b == 0.0 \ No newline at end of file From a2c65605475edfda3e9f457aa6cfb6f4544a9c08 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 17:42:26 +0000 Subject: [PATCH 16/81] Update setup.py --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 916f41c..0d88189 100644 --- a/setup.py +++ b/setup.py @@ -42,6 +42,7 @@ def get_versions(): "jaxlib>=0.4.0", "jaxtyping", "ml-collections==0.1.0", + "equinox" ] EXTRAS = { From 857cf8bbf4605dad77922bf60aa411797c12aa39 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 17:44:18 +0000 Subject: [PATCH 17/81] Update setup.py --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 0d88189..c8677db 100644 --- a/setup.py +++ b/setup.py @@ -43,6 +43,7 @@ def get_versions(): "jaxtyping", "ml-collections==0.1.0", "equinox" + "optax", ] EXTRAS = { From 9ba545175dc5002b51ddb86b58436e2b0b1c8009 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 17:46:11 +0000 Subject: [PATCH 18/81] Update setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index c8677db..a8552dd 100644 --- a/setup.py +++ b/setup.py @@ -42,7 +42,7 @@ def get_versions(): "jaxlib>=0.4.0", "jaxtyping", "ml-collections==0.1.0", - "equinox" + "equinox", "optax", ] From d5bf42d9ea07e5b27f87bc078eb816e096593b3d Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 17:48:08 +0000 Subject: [PATCH 19/81] Update setup.py --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index a8552dd..1d94e8c 100644 --- a/setup.py +++ b/setup.py @@ -44,6 +44,7 @@ def get_versions(): "ml-collections==0.1.0", "equinox", "optax", + "tqdm", ] EXTRAS = { From 7646a0f9f02ee41b102b16ad31a368bf023b9432 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 18:02:30 +0000 Subject: [PATCH 20/81] Update fit.py --- jaxutils/fit.py | 97 +++++++++++++++++++++++++++---------------------- 1 file changed, 53 insertions(+), 44 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 52d84fd..09a1965 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -29,8 +29,6 @@ from .objective import Objective from .progress_bar import progress_bar_scan -import equinox as eqx - def fit( *, @@ -43,8 +41,8 @@ def fit( key: Optional[KeyArray] = jr.PRNGKey(42), log_rate: Optional[int] = 10, verbose: Optional[bool] = True, - bijectors: Any, - trainables: Any, + bijectors: Module = None, + trainables: Module = None, ) -> Tuple[Module, Array]: """Abstracted method for fitting a GP model with respect to a supplied objective function. Optimisers used here should originate from Optax. @@ -64,10 +62,7 @@ def fit( Returns: Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ - - _check_types(model, objective, train_data, optim, num_iters, log_rate, verbose, key, batch_size) - #TODO: Check bijectors and trainables are correct types and same structure as model. - + # Initialise bijectors from defaults if not supplied. if bijectors is None: bijectors = default_bijectors(model) @@ -76,6 +71,20 @@ def fit( if trainables is None: trainables = default_trainables(model) + # Check inputs. + _check_model(model) + _check_objective(objective) + _check_train_data(train_data) + _check_optim(optim) + _check_num_iters(num_iters) + _check_batch_size(batch_size) + _check_key(key) + _check_log_rate(log_rate) + _check_verbose(verbose) + _check_bijectors(bijectors) + _check_trainables(trainables) + + # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: model = stop_gradients(model, trainables) @@ -92,16 +101,15 @@ def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: iter_keys = jr.split(key, num_iters) iter_nums = jnp.arange(num_iters) - # Optimisation step + # Optimisation step. def step(carry, iter_num__and__key): - iter_num, key = iter_num__and__key + _, key = iter_num__and__key model, opt_state = carry - if batch_size == -1: - batch = train_data - if batch_size != -1: batch = get_batch(train_data, batch_size, key) + else: + batch = train_data loss_val, loss_gradient = jax.value_and_grad(loss)(model, batch) updates, opt_state = optim.update(loss_gradient, opt_state, model) @@ -143,58 +151,59 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: -def _check_types( - model: Any, - objective: Any, - train_data: Any, - optax_optim: Any, - num_iters: Any, - log_rate: Any, - verbose: Any, - key: Any, - batch_size: Any, - ) -> None: - +def _check_model(model: Any) -> None: + """Check that the model is of type Module.""" if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") - + +def _check_objective(objective: Any) -> None: + """Check that the objective is of type Objective.""" if not isinstance(objective, Objective): raise TypeError("objective must be of type jaxutils.Objective") - + +def _check_train_data(train_data: Any) -> None: + """Check that the train_data is of type Dataset.""" if not isinstance(train_data, Dataset): raise TypeError("train_data must be of type jaxutils.Dataset") - if not isinstance(optax_optim, ox.GradientTransformation): +def _check_optim(optim: Any) -> None: + if not isinstance(optim, ox.GradientTransformation): raise TypeError("optax_optim must be of type optax.GradientTransformation") +def _check_num_iters(num_iters: Any) -> None: if not isinstance(num_iters, int): raise TypeError("num_iters must be of type int") if not num_iters > 0: - raise ValueError("num_iters must be positive, but got num_iters={num_iters}") - + raise ValueError("num_iters must be positive") + +def _check_log_rate(log_rate: Any) -> None: if not isinstance(log_rate, int): - raise TypeError(f"log_rate must be of type int") - + raise TypeError("log_rate must be of type int") + if not log_rate > 0: - raise ValueError(f"log_rate must be positive, but got log_rate={log_rate}") + raise ValueError("log_rate must be positive") +def _check_verbose(verbose: Any) -> None: if not isinstance(verbose, bool): raise TypeError("verbose must be of type bool") - - if batch_size is not None: - if not isinstance(batch_size, int): - raise TypeError("batch_size must be of type int") +def _check_key(key: Any) -> None: + pass + +def _check_batch_size(batch_size: Any) -> None: + if not isinstance(batch_size, int): + raise TypeError("batch_size must be of type int") + + if not batch_size == -1: if not batch_size > 0: - if batch_size == -1: - pass - else: - raise ValueError(f"batch_size must be positive, but got batch_size={batch_size}") - - if not batch_size < train_data.n: - raise ValueError(f"batch_size must be less than train_data.n, but got batch_size={batch_size} and train_data.n={train_data.n}") + raise ValueError("batch_size must be positive") + +def _check_bijectors(bijectors: Any) -> None: + pass +def _check_trainables(trainables: Any) -> None: + pass __all__ = [ "fit", From e9eb8d2eade2c9d60afc96e337d751dfc739b73d Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Feb 2023 18:03:23 +0000 Subject: [PATCH 21/81] Delete params.py --- jaxutils/params.py | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 jaxutils/params.py diff --git a/jaxutils/params.py b/jaxutils/params.py deleted file mode 100644 index 3a0e0f6..0000000 --- a/jaxutils/params.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from dataclasses import field - -import jax.tree_util as jtu -from jax import lax - -from .bijectors import Bijector -from .module import Module - - - - - -__all__ = [ - "param", - "constrain", - "unconstrain", - "stop_gradients", -] From 6f3f63d23c3e80c5f7ae89492c4a32a03e5fed6a Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 13:23:47 +0000 Subject: [PATCH 22/81] Update. --- jaxutils/fit.py | 30 ++------ jaxutils/module.py | 179 +++++++++++++++++++++++++++++++++++++++---- tests/test_module.py | 12 +-- 3 files changed, 175 insertions(+), 46 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 09a1965..8965fad 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -24,7 +24,7 @@ from jaxtyping import Array, Float from typing import Any -from .module import Module, constrain, unconstrain, stop_gradients, default_bijectors, default_trainables +from .module import Module, constrain, unconstrain, stop_gradients from .dataset import Dataset from .objective import Objective from .progress_bar import progress_bar_scan @@ -41,8 +41,6 @@ def fit( key: Optional[KeyArray] = jr.PRNGKey(42), log_rate: Optional[int] = 10, verbose: Optional[bool] = True, - bijectors: Module = None, - trainables: Module = None, ) -> Tuple[Module, Array]: """Abstracted method for fitting a GP model with respect to a supplied objective function. Optimisers used here should originate from Optax. @@ -56,20 +54,10 @@ def fit( key (Optional[KeyArray]): The random key to use for the optimisation batch selection. Defaults to jr.PRNGKey(42). log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. - bijectors (Any): The bijectors to use for the model. - trainables (Any): The trainables to use for the model. Returns: Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. """ - - # Initialise bijectors from defaults if not supplied. - if bijectors is None: - bijectors = default_bijectors(model) - - # Initialise trainables from defaults if not supplied. - if trainables is None: - trainables = default_trainables(model) # Check inputs. _check_model(model) @@ -81,18 +69,16 @@ def fit( _check_key(key) _check_log_rate(log_rate) _check_verbose(verbose) - _check_bijectors(bijectors) - _check_trainables(trainables) # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: - model = stop_gradients(model, trainables) - model = constrain(model, bijectors) + model = stop_gradients(model) + model = constrain(model) return objective(model, batch) # Unconstrained space model. - model = unconstrain(model, bijectors) + model = unconstrain(model) # Initialise optimiser state. state = optim.init(model) @@ -126,7 +112,7 @@ def step(carry, iter_num__and__key): (model, _), history = jax.lax.scan(step, (model, state), (iter_nums, iter_keys)) # Constrained space. - model = constrain(model, bijectors) + model = constrain(model) return model, history @@ -199,14 +185,8 @@ def _check_batch_size(batch_size: Any) -> None: if not batch_size > 0: raise ValueError("batch_size must be positive") -def _check_bijectors(bijectors: Any) -> None: - pass - -def _check_trainables(trainables: Any) -> None: - pass __all__ = [ "fit", - "fit_natgrads", "get_batch", ] \ No newline at end of file diff --git a/jaxutils/module.py b/jaxutils/module.py index 9e393dd..4c83706 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,19 +20,13 @@ from jax import lax from dataclasses import fields, field -from typing import List +from typing import List, Callable import equinox as eqx from .bijectors import Bijector -class Module(eqx.Module): - """Base class for all objects of the JaxGaussianProcesses ecosystem.""" - - #TODO: Check all (dynamic) leaf nodes are marked by the `param` field. - - def default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, @@ -98,43 +92,41 @@ def param(transform: Bijector): return field(metadata={"transform": transform}) -def constrain(obj: Module, bij: Module) -> Module: +def constrain(obj: Module) -> Module: """ Transform model parameters to the constrained space for corresponding bijectors. Args: obj (Module): The PyTree object whoose leaves are to be transformed. - bij (Module): The PyTree object whoose leaves are the corresponding bijector transformations. Returns: Module: PyTree tranformed to the constrained space. """ - return jtu.tree_map(lambda leaf, transform: transform.forward(leaf), obj, bij) + return jtu.tree_map(lambda leaf, transform: transform.forward(leaf), obj, obj.bijectors) -def unconstrain(obj: Module, bij: Module) -> Module: +def unconstrain(obj: Module) -> Module: """ Transform model parameters to the unconstrained space for corresponding bijectors. Args: obj (Module): The PyTree object whoose leaves are to be transformed. - bij (Module): The PyTree object whoose leaves are the corresponding bijector transformations. Returns: Module: PyTree tranformed to the unconstrained space. """ - return jtu.tree_map(lambda leaf, transform: transform.inverse(leaf), obj, bij) + return jtu.tree_map(lambda leaf, transform: transform.inverse(leaf), obj, obj.bijectors) -def stop_gradients(obj: Module, trn: Module) -> Module: +def stop_gradients(obj: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is False. Args: obj (Module): PyTree object to stop gradients for. - trn (Module): PyTree of booleans indicating whether to stop gradients for each leaf node. + Returns: Module: PyTree with gradients stopped. """ @@ -142,7 +134,162 @@ def stop_gradients(obj: Module, trn: Module) -> Module: def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - return jtu.tree_map(lambda *_: _stop_grad(*_), obj, trn) + return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) + + + +class Module(eqx.Module): + """Base class for all objects of the JaxGaussianProcesses ecosystem.""" + + def __new__( + cls, + trainables_func: Callable[[Module], Module] = default_trainables, + bijectors_func: Callable[[Module], Module] = default_bijectors, + *args, + **kwargs, + ) -> Module: + """ This is used to set the trainables and bijectors functions. As we are working with frozen dataclasses.""" + + instance = super().__new__(cls) + object.__setattr__(instance, "__trainables_func__", trainables_func) + object.__setattr__(instance, "__bijectors_func__", bijectors_func) + + return instance + + + @property + def _trainables_func(self) -> Callable[[Module], Module]: + """This is so we can acess the trainables function from the class.""" + return self.__trainables_func__ + + + @property + def _bijectors_func(self) -> Callable[[Module], Module]: + """This is so we can acess the bijectors function from the class.""" + return self.__bijectors_func__ + + @property + def trainables(self): + return self._trainables_func(self) + + @property + def bijectors(self): + return self._bijectors_func(self) + + + def set_trainables(self, tree: Module) -> Module: + + # TODO: Check PyTree leafs are boolean valued. + flat, _ = jtu.tree_flatten(tree) + + def _trainables_from_self(self: Module) -> Module: + _, tree_def = jtu.tree_flatten(self) + return tree_def.unflatten(flat) + + return self._set_trainables(_trainables_from_self) + + + def set_bijectors(self, tree: Module) -> Module: + + # TODO: Check PyTree leafs are Bijectors type. + flat, _ = jtu.tree_flatten(tree) + + def _bijectors_from_self(self: Module) -> Module: + _, tree_def = jtu.tree_flatten(self) + return tree_def.unflatten(flat) + + return self._set_bijectors(_bijectors_from_self) + + + def _set_trainables(self, func: Callable[[Module], Module]): + """Set the trainables function for the class.""" + + cls = self.__class__ + + # Create new class instance, with the adjusted trainable function. + new_instance = cls.__new__( + cls, + trainables_func=func, + bijectors_func = self.__bijectors_func__, + ) + + # TODO: Might have to filter attribute dict here? + for field_ in fields(self): + object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) + + return new_instance + + def _set_bijectors(self, func: Callable[[Module], Module]): + """Set the bijectors function for the class.""" + + cls = self.__class__ + + # Create new class instance, with the adjusted trainable function. + new_instance = cls.__new__( + cls, + trainables_func=self.__trainables_func__, + bijectors_func = func, + ) + + # TODO: Might have to filter attribute dict here? + for field_ in fields(self): + object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) + + return new_instance + + def tree_flatten(self): + """Same as Equinox, except for the addition of the `static_funcs`.""" + dynamic_field_names = [] + dynamic_field_values = [] + static_field_names = [] + static_field_values = [] + + static_funcs = [ + self.__trainables_func__, + self.__bijectors_func__, + ] + + for field_ in fields(self): + name = field_.name + try: + value = self.__dict__[name] + except KeyError: + continue + if field_.metadata.get("static", False): + static_field_names.append(name) + static_field_values.append(value) + else: + dynamic_field_names.append(name) + dynamic_field_values.append(value) + + return tuple(dynamic_field_values), ( + tuple(dynamic_field_names), + tuple(static_field_names), + tuple(static_field_values), + tuple(static_funcs) + ) + + @classmethod + def tree_unflatten(cls, aux, dynamic_field_values): + """Same as Equinox, except for the addition of the `static_funcs`.""" + + dynamic_field_names, static_field_names, static_field_values, static_funcs = aux + + # These are the static functions that determine the trainable and bijector PyTree's from self. + __trainables_func__, __bijectors_func__ = static_funcs + + self = cls.__new__( + cls, + trainables_func = __trainables_func__, + bijectors_func = __bijectors_func__, + ) + + for name, value in zip(dynamic_field_names, dynamic_field_values): + object.__setattr__(self, name, value) + for name, value in zip(static_field_names, static_field_values): + object.__setattr__(self, name, value) + + return self __all__ = [ diff --git a/tests/test_module.py b/tests/test_module.py index 9b18f04..c4ec969 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -16,7 +16,7 @@ import jax.numpy as jnp import pytest from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients, default_bijectors, default_trainables -from jaxutils.bijectors import Bijector, Identity, Softplus +from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax @@ -57,8 +57,8 @@ class Tree(Module): assert t1 == t2 # Test constrain and unconstrain - constrained = constrain(tree, bijectors) - unconstrained = unconstrain(tree, bijectors) + constrained = constrain(tree) + unconstrained = unconstrain(tree) leafs = jtu.tree_leaves(tree) @@ -72,13 +72,15 @@ class Tree(Module): _, tree_def = jax.tree_flatten(tree) trainables = tree_def.unflatten([True, False, True, False, False]) + new_tree = tree.set_trainables(trainables) + # Test stop gradients def loss(tree): - tree = stop_gradients(tree, trainables) + tree = stop_gradients(tree) return jnp.sum(tree.param_a**2 + tree.sub_tree.param_c**2 + tree.sub_tree.param_d**2 + tree.sub_tree.param_e**2 + tree.param_b**2) - g = jax.grad(loss)(tree) + g = jax.grad(loss)(new_tree) assert g.param_a == 2.0 assert g.sub_tree.param_c == 0.0 From 4d037a6239c5be5170e2d0cd1f28c1e457f7b2b4 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 13:37:31 +0000 Subject: [PATCH 23/81] Add test. --- jaxutils/test_fit.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_fit.py | 43 ++++++++++++++++++++++++++++++--- 2 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 jaxutils/test_fit.py diff --git a/jaxutils/test_fit.py b/jaxutils/test_fit.py new file mode 100644 index 0000000..442680d --- /dev/null +++ b/jaxutils/test_fit.py @@ -0,0 +1,57 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from jaxutils.dataset import Dataset +from jaxutils.fit import fit +from jaxutils.bijectors import Identity +from jaxutils.module import param, Module +from jaxutils.objective import Objective + +import jax.numpy as jnp +import jax.random as jr +import optax as ox + +def test_simple_linear_model(): + # (1) Create a dataset: + X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) + y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) + D = Dataset(X, y) + + + # (2) Define your model: + class LinearModel(Module): + weight: float = param(Identity) + bias: float = param(Identity) + + def __call__(self, x): + return self.weight * x + self.bias + + model = LinearModel(weight=1.0, bias=1.0) + + + # (3) Define your loss function: + class MeanSqaureError(Objective): + + def evaluate(self, model: LinearModel, train_data: Dataset) -> float: + return jnp.mean((train_data.y - model(train_data.X)) ** 2) + + loss = MeanSqaureError() + + # (4) Train! + trained_model, hist = fit(model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=100) + + assert len(hist) == 10000 + assert isinstance(trained_model, LinearModel) + assert loss(trained_model, D) < loss(model, D) \ No newline at end of file diff --git a/tests/test_fit.py b/tests/test_fit.py index 55543f3..9abfe0f 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -1,4 +1,4 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. All Rights Reserved. +# Copyright 2023 The JaxGaussianProcesses Contributors. 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. @@ -13,8 +13,45 @@ # limitations under the License. # ============================================================================== +from jaxutils.dataset import Dataset +from jaxutils.fit import fit +from jaxutils.bijectors import Identity +from jaxutils.module import param, Module +from jaxutils.objective import Objective + import jax.numpy as jnp -import pytest +import jax.random as jr +import optax as ox + +def test_simple_linear_model(): + # (1) Create a dataset: + X = jnp.linspace(0.0, 10.0, 1000050).reshape(-1, 1) + y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) + D = Dataset(X, y) + + + # (2) Define your model: + class LinearModel(Module): + weight: float = param(Identity) + bias: float = param(Identity) + + def __call__(self, x): + return self.weight * x + self.bias + + model = LinearModel(weight=1.0, bias=1.0) + + + # (3) Define your loss function: + class MeanSqaureError(Objective): + + def evaluate(self, model: LinearModel, train_data: Dataset) -> float: + return jnp.mean((train_data.y - model(train_data.X)) ** 2) + + loss = MeanSqaureError() -# Three models. + # (4) Train! + trained_model, hist = fit(model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=10000) + assert len(hist) == 10000 + assert isinstance(trained_model, LinearModel) + assert loss(trained_model, D) < loss(model, D) \ No newline at end of file From 4aee5179c92db8154eac07137bbd055c9ddae904 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 14:33:31 +0000 Subject: [PATCH 24/81] Update. --- .pre-commit-config.yaml | 30 +++++++ jaxutils/module.py | 173 +++++++++++++++++++++++----------------- jaxutils/test_fit.py | 57 ------------- tests/test_fit.py | 14 ++-- 4 files changed, 138 insertions(+), 136 deletions(-) create mode 100644 .pre-commit-config.yaml delete mode 100644 jaxutils/test_fit.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..b73828e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,30 @@ +repos: + - repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + # - repo: https://github.com/pycqa/isort + # rev: 5.10.1 + # hooks: + # - id: isort + # args: ["--profile", "black"] + - repo: https://github.com/kynan/nbstripout + rev: 0.5.0 + hooks: + - id: nbstripout + - repo: https://github.com/nbQA-dev/nbQA + rev: 1.3.1 + hooks: + - id: nbqa-black + - id: nbqa-pyupgrade + args: [--py37-plus] + - id: nbqa-flake8 + args: ['--ignore=E501,E203,E302,E402,E731,W503'] + - repo: https://github.com/PyCQA/autoflake + rev: v2.0.0 + hooks: + - id: autoflake + args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports", "--recursive"] + name: AutoFlake + description: "Format with AutoFlake" + stages: [commit] \ No newline at end of file diff --git a/jaxutils/module.py b/jaxutils/module.py index 4c83706..10d7c6f 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,7 +20,7 @@ from jax import lax from dataclasses import fields, field -from typing import List, Callable +from typing import Any, Callable, List import equinox as eqx @@ -43,7 +43,7 @@ def default_bijectors(obj: Module) -> Module: Args: obj (Module): The PyTree object whoose default bijectors (from the param field) you would to obtain. - + Returns: Module: A PyTree of bijectors comprising the same structure as `obj`. """ @@ -71,13 +71,12 @@ def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: else: bijectors_.append(value_) - + return bijectors_ - + bijectors_ = _unpack_bijectors_from_meta(obj) - - return treedef.unflatten(bijectors_) + return treedef.unflatten(bijectors_) def param(transform: Bijector): @@ -103,7 +102,9 @@ def constrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the constrained space. """ - return jtu.tree_map(lambda leaf, transform: transform.forward(leaf), obj, obj.bijectors) + return jtu.tree_map( + lambda leaf, transform: transform.forward(leaf), obj, obj.bijectors + ) def unconstrain(obj: Module) -> Module: @@ -117,13 +118,16 @@ def unconstrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the unconstrained space. """ - return jtu.tree_map(lambda leaf, transform: transform.inverse(leaf), obj, obj.bijectors) + return jtu.tree_map( + lambda leaf, transform: transform.inverse(leaf), obj, obj.bijectors + ) def stop_gradients(obj: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is False. + Args: obj (Module): PyTree object to stop gradients for. @@ -137,104 +141,129 @@ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) +# TODO: Leaf node typing. E.g., to distiguish between boolean PyTree and one that is jax.Arrays. +# TODO: Leaf node checking. + class Module(eqx.Module): - """Base class for all objects of the JaxGaussianProcesses ecosystem.""" + """Base Module object. + + This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), + with modifications to handle bijector transformations and trainability statuses. + + """ def __new__( cls, trainables_func: Callable[[Module], Module] = default_trainables, bijectors_func: Callable[[Module], Module] = default_bijectors, - *args, - **kwargs, - ) -> Module: - """ This is used to set the trainables and bijectors functions. As we are working with frozen dataclasses.""" - + *args: Any, + **kwargs: Any, + ) -> Module: + """This is used to set the trainables and bijectors functions. As we are working with frozen dataclasses. + + Args: + trainables_func (Callable[[Module], Module]). The function that constructs the trainables PyTree from `self`. + bijectors_func (Callable[[Module], Module]). The function that constructs the bijectors PyTree from `self`. + *args (Any). Arguments. + **kwargs (Any). Keyword arguments. + + Returns: + Module. An instance of the JaxUtils Module class. + """ + instance = super().__new__(cls) object.__setattr__(instance, "__trainables_func__", trainables_func) object.__setattr__(instance, "__bijectors_func__", bijectors_func) - + return instance - @property - def _trainables_func(self) -> Callable[[Module], Module]: - """This is so we can acess the trainables function from the class.""" - return self.__trainables_func__ + def tree_def(self): + """Return the tree definition.""" + _, tree_def_ = jtu.tree_flatten(self) + return tree_def_ - @property - def _bijectors_func(self) -> Callable[[Module], Module]: - """This is so we can acess the bijectors function from the class.""" - return self.__bijectors_func__ - + def leaves(self): + """Return pytree tree leaves.""" + leaves_, _ = jtu.tree_flatten(self) + return leaves_ + @property - def trainables(self): - return self._trainables_func(self) + def trainables(self) -> Module: + """Return the boolean Module comprising trainability statuses. + + Returns: + Module. The boolean Module comprising trainability statuses for the Module. + """ + return self.__trainables_func__(self) @property - def bijectors(self): - return self._bijectors_func(self) + def bijectors(self) -> Module: + """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. + Returns: + Module. The Bijector Module of parameter transformations. + """ + return self.__bijectors_func__(self) def set_trainables(self, tree: Module) -> Module: + """Set parameter trainability status for the Module. - # TODO: Check PyTree leafs are boolean valued. - flat, _ = jtu.tree_flatten(tree) + Args: + tree (Module). The boolean tree of trainability status comprising the same tree structure as the underlying Module. - def _trainables_from_self(self: Module) -> Module: - _, tree_def = jtu.tree_flatten(self) - return tree_def.unflatten(flat) - - return self._set_trainables(_trainables_from_self) + Returns: + Module. A new instance with the updated trainablility status tree. + """ + return self.__set_trainables_func__( + lambda obj: obj.tree_def.unflatten(tree.leaves) + ) - def set_bijectors(self, tree: Module) -> Module: + """Set parameter transformations for the Module. - # TODO: Check PyTree leafs are Bijectors type. - flat, _ = jtu.tree_flatten(tree) + Args: + tree (Module). The Bijector tree of parameter transformations comprising the same tree structure as the underlying Module. - def _bijectors_from_self(self: Module) -> Module: - _, tree_def = jtu.tree_flatten(self) - return tree_def.unflatten(flat) - - return self._set_bijectors(_bijectors_from_self) + Returns: + Module. A new instance with the updated trainablility status tree. + """ + return self.__set_bijectors_func__( + lambda obj: obj.tree_def.unflatten(tree.leaves) + ) - - def _set_trainables(self, func: Callable[[Module], Module]): + def __set_trainables_func__(self, func: Callable[[Module], Module]) -> Module: """Set the trainables function for the class.""" - cls = self.__class__ - # Create new class instance, with the adjusted trainable function. - new_instance = cls.__new__( - cls, + new_instance = self.__class__.__new__( + self.__class__, trainables_func=func, - bijectors_func = self.__bijectors_func__, - ) + bijectors_func=self.__bijectors_func__, + ) # TODO: Might have to filter attribute dict here? for field_ in fields(self): object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) - + return new_instance - def _set_bijectors(self, func: Callable[[Module], Module]): + def __set_bijectors_func__(self, func: Callable[[Module], Module]) -> Module: """Set the bijectors function for the class.""" - cls = self.__class__ - # Create new class instance, with the adjusted trainable function. - new_instance = cls.__new__( - cls, + new_instance = self.__class__.__new__( + self.__class__, trainables_func=self.__trainables_func__, - bijectors_func = func, - ) + bijectors_func=func, + ) # TODO: Might have to filter attribute dict here? for field_ in fields(self): object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) - + return new_instance def tree_flatten(self): @@ -243,12 +272,12 @@ def tree_flatten(self): dynamic_field_values = [] static_field_names = [] static_field_values = [] - + static_funcs = [ - self.__trainables_func__, + self.__trainables_func__, self.__bijectors_func__, - ] - + ] + for field_ in fields(self): name = field_.name try: @@ -261,12 +290,12 @@ def tree_flatten(self): else: dynamic_field_names.append(name) dynamic_field_values.append(value) - + return tuple(dynamic_field_values), ( tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(static_funcs) + tuple(static_funcs), ) @classmethod @@ -276,14 +305,14 @@ def tree_unflatten(cls, aux, dynamic_field_values): dynamic_field_names, static_field_names, static_field_values, static_funcs = aux # These are the static functions that determine the trainable and bijector PyTree's from self. - __trainables_func__, __bijectors_func__ = static_funcs - + trainables_func, bijectors_func = static_funcs + self = cls.__new__( - cls, - trainables_func = __trainables_func__, - bijectors_func = __bijectors_func__, + cls, + trainables_func=trainables_func, + bijectors_func=bijectors_func, ) - + for name, value in zip(dynamic_field_names, dynamic_field_values): object.__setattr__(self, name, value) for name, value in zip(static_field_names, static_field_values): diff --git a/jaxutils/test_fit.py b/jaxutils/test_fit.py deleted file mode 100644 index 442680d..0000000 --- a/jaxutils/test_fit.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from jaxutils.dataset import Dataset -from jaxutils.fit import fit -from jaxutils.bijectors import Identity -from jaxutils.module import param, Module -from jaxutils.objective import Objective - -import jax.numpy as jnp -import jax.random as jr -import optax as ox - -def test_simple_linear_model(): - # (1) Create a dataset: - X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) - y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) - D = Dataset(X, y) - - - # (2) Define your model: - class LinearModel(Module): - weight: float = param(Identity) - bias: float = param(Identity) - - def __call__(self, x): - return self.weight * x + self.bias - - model = LinearModel(weight=1.0, bias=1.0) - - - # (3) Define your loss function: - class MeanSqaureError(Objective): - - def evaluate(self, model: LinearModel, train_data: Dataset) -> float: - return jnp.mean((train_data.y - model(train_data.X)) ** 2) - - loss = MeanSqaureError() - - # (4) Train! - trained_model, hist = fit(model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=100) - - assert len(hist) == 10000 - assert isinstance(trained_model, LinearModel) - assert loss(trained_model, D) < loss(model, D) \ No newline at end of file diff --git a/tests/test_fit.py b/tests/test_fit.py index 9abfe0f..ecf989f 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -23,13 +23,13 @@ import jax.random as jr import optax as ox + def test_simple_linear_model(): # (1) Create a dataset: - X = jnp.linspace(0.0, 10.0, 1000050).reshape(-1, 1) + X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) D = Dataset(X, y) - # (2) Define your model: class LinearModel(Module): weight: float = param(Identity) @@ -40,18 +40,18 @@ def __call__(self, x): model = LinearModel(weight=1.0, bias=1.0) - # (3) Define your loss function: class MeanSqaureError(Objective): - def evaluate(self, model: LinearModel, train_data: Dataset) -> float: return jnp.mean((train_data.y - model(train_data.X)) ** 2) loss = MeanSqaureError() # (4) Train! - trained_model, hist = fit(model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=10000) + trained_model, hist = fit( + model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=100 + ) - assert len(hist) == 10000 + assert len(hist) == 100 assert isinstance(trained_model, LinearModel) - assert loss(trained_model, D) < loss(model, D) \ No newline at end of file + assert loss(trained_model, D) < loss(model, D) From 02c5fa15b8e5e7aabe69d5a5d90d1309e38e68c3 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 14:35:58 +0000 Subject: [PATCH 25/81] Update module.py --- jaxutils/module.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 10d7c6f..78cd6a0 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -234,13 +234,15 @@ def set_bijectors(self, tree: Module) -> Module: lambda obj: obj.tree_def.unflatten(tree.leaves) ) - def __set_trainables_func__(self, func: Callable[[Module], Module]) -> Module: + def __set_trainables_func__( + self, __trainables_func__: Callable[[Module], Module] + ) -> Module: """Set the trainables function for the class.""" # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( self.__class__, - trainables_func=func, + trainables_func=__trainables_func__, bijectors_func=self.__bijectors_func__, ) @@ -250,14 +252,16 @@ def __set_trainables_func__(self, func: Callable[[Module], Module]) -> Module: return new_instance - def __set_bijectors_func__(self, func: Callable[[Module], Module]) -> Module: + def __set_bijectors_func__( + self, __bijectors_func__: Callable[[Module], Module] + ) -> Module: """Set the bijectors function for the class.""" # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( self.__class__, trainables_func=self.__trainables_func__, - bijectors_func=func, + bijectors_func=__bijectors_func__, ) # TODO: Might have to filter attribute dict here? From 509cf19e65d88d9b3543a1fcef9d319e75b8105a Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 16:05:42 +0000 Subject: [PATCH 26/81] Update module.py --- jaxutils/module.py | 93 +++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 38 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 78cd6a0..f18cb98 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,6 +27,18 @@ from .bijectors import Bijector +def tree_def(obj: Module): + """Return Module tree definition.""" + _, tree_def_ = jtu.tree_flatten(obj) + return tree_def_ + + +def leaves(obj: Module): + """Return Module leaves.""" + leaves_, _ = jtu.tree_flatten(obj) + return leaves_ + + def default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, @@ -48,7 +60,7 @@ def default_bijectors(obj: Module) -> Module: Module: A PyTree of bijectors comprising the same structure as `obj`. """ - _, treedef = jtu.tree_flatten(obj) + tree_def_ = tree_def(obj) def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: """Unpack bijectors from metatdata.""" @@ -76,19 +88,35 @@ def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: bijectors_ = _unpack_bijectors_from_meta(obj) - return treedef.unflatten(bijectors_) + return tree_def_.unflatten(bijectors_) -def param(transform: Bijector): - """Set leaf node metadata for a parameter. +def param(transform: Bijector, **kwargs: Any): + """Used for marking default parameter transformations. - Args: - transform (Bijector): A default bijector transformation for the parameter. + !!! example - Returns: - A field with the metadata set. + ```python + class MyModule(jaxutils.Module): + param_a: float = jaxutils.param(jaxutils.Identity) + param_b: float = jaxutils.param(jaxutils.Softplus) + ``` + + All PyTree leaves of the Module must be marked. + + Args: + transform (Bijector). The default bijector that should be should upon Module initialisation. + **kwargs (Any). If any are passed then they are passed on to `datacalss.field`. + (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) """ - return field(metadata={"transform": transform}) + try: + metadata = dict(kwargs["metadata"]) + except KeyError: + metadata = kwargs["metadata"] = {} + if "transform" in metadata: + raise ValueError("Cannot use metadata with `transform` already set.") + metadata["transform"] = transform + return field(**kwargs) def constrain(obj: Module) -> Module: @@ -155,16 +183,16 @@ class Module(eqx.Module): def __new__( cls, - trainables_func: Callable[[Module], Module] = default_trainables, - bijectors_func: Callable[[Module], Module] = default_bijectors, + __trainables_func__: Callable[[Module], Module] = default_trainables, + __bijectors_func__: Callable[[Module], Module] = default_bijectors, *args: Any, **kwargs: Any, ) -> Module: """This is used to set the trainables and bijectors functions. As we are working with frozen dataclasses. Args: - trainables_func (Callable[[Module], Module]). The function that constructs the trainables PyTree from `self`. - bijectors_func (Callable[[Module], Module]). The function that constructs the bijectors PyTree from `self`. + __trainables_func__ (Callable[[Module], Module]). The function that constructs the trainables PyTree from `self`. + __bijectors_func__ (Callable[[Module], Module]). The function that constructs the bijectors PyTree from `self`. *args (Any). Arguments. **kwargs (Any). Keyword arguments. @@ -173,23 +201,11 @@ def __new__( """ instance = super().__new__(cls) - object.__setattr__(instance, "__trainables_func__", trainables_func) - object.__setattr__(instance, "__bijectors_func__", bijectors_func) + object.__setattr__(instance, "__trainables_func__", __trainables_func__) + object.__setattr__(instance, "__bijectors_func__", __bijectors_func__) return instance - @property - def tree_def(self): - """Return the tree definition.""" - _, tree_def_ = jtu.tree_flatten(self) - return tree_def_ - - @property - def leaves(self): - """Return pytree tree leaves.""" - leaves_, _ = jtu.tree_flatten(self) - return leaves_ - @property def trainables(self) -> Module: """Return the boolean Module comprising trainability statuses. @@ -218,7 +234,7 @@ def set_trainables(self, tree: Module) -> Module: Module. A new instance with the updated trainablility status tree. """ return self.__set_trainables_func__( - lambda obj: obj.tree_def.unflatten(tree.leaves) + lambda obj: tree_def(obj).unflatten(leaves(tree)) ) def set_bijectors(self, tree: Module) -> Module: @@ -231,7 +247,7 @@ def set_bijectors(self, tree: Module) -> Module: Module. A new instance with the updated trainablility status tree. """ return self.__set_bijectors_func__( - lambda obj: obj.tree_def.unflatten(tree.leaves) + lambda obj: tree_def(obj).unflatten(leaves(tree)) ) def __set_trainables_func__( @@ -241,9 +257,9 @@ def __set_trainables_func__( # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( - self.__class__, - trainables_func=__trainables_func__, - bijectors_func=self.__bijectors_func__, + cls=self.__class__, + __trainables_func__=__trainables_func__, + __bijectors_func__=self.__bijectors_func__, ) # TODO: Might have to filter attribute dict here? @@ -260,8 +276,8 @@ def __set_bijectors_func__( # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( self.__class__, - trainables_func=self.__trainables_func__, - bijectors_func=__bijectors_func__, + __trainables_func_=self.__trainables_func__, + __bijectors_func_=__bijectors_func__, ) # TODO: Might have to filter attribute dict here? @@ -309,16 +325,17 @@ def tree_unflatten(cls, aux, dynamic_field_values): dynamic_field_names, static_field_names, static_field_values, static_funcs = aux # These are the static functions that determine the trainable and bijector PyTree's from self. - trainables_func, bijectors_func = static_funcs + __trainables_func__, __bijectors_func__ = static_funcs self = cls.__new__( - cls, - trainables_func=trainables_func, - bijectors_func=bijectors_func, + cls=cls, + __trainables_func__=__trainables_func__, + __bijectors_func__=__bijectors_func__, ) for name, value in zip(dynamic_field_names, dynamic_field_values): object.__setattr__(self, name, value) + for name, value in zip(static_field_names, static_field_values): object.__setattr__(self, name, value) From 63cad7f07278432a147bc630f5fa2046d27103c1 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 16:22:57 +0000 Subject: [PATCH 27/81] Update fit.py --- jaxutils/fit.py | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 8965fad..2552b61 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -21,6 +21,7 @@ import optax as ox from jax.random import KeyArray +from jax._src.random import _check_prng_key from jaxtyping import Array, Float from typing import Any @@ -42,11 +43,10 @@ def fit( log_rate: Optional[int] = 10, verbose: Optional[bool] = True, ) -> Tuple[Module, Array]: - """Abstracted method for fitting a GP model with respect to a supplied objective function. - Optimisers used here should originate from Optax. + """Train a Module model with respect to a supplied Objective function. Optimisers used here should originate from Optax. Args: - model (eqx.Module): The model that is to be optimised. + model (Module): The model Module to be optimised. objective (Objective): The objective function that we are optimising with respect to. optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. @@ -66,10 +66,9 @@ def fit( _check_optim(optim) _check_num_iters(num_iters) _check_batch_size(batch_size) - _check_key(key) + _check_prng_key(key) _check_log_rate(log_rate) _check_verbose(verbose) - # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: @@ -117,7 +116,6 @@ def step(carry, iter_num__and__key): return model, history - def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: """Batch the data into mini-batches. Sampling is done with replacement. @@ -136,57 +134,60 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: return Dataset(X=x[indicies], y=y[indicies]) - def _check_model(model: Any) -> None: """Check that the model is of type Module.""" if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") + def _check_objective(objective: Any) -> None: """Check that the objective is of type Objective.""" if not isinstance(objective, Objective): raise TypeError("objective must be of type jaxutils.Objective") + def _check_train_data(train_data: Any) -> None: """Check that the train_data is of type Dataset.""" if not isinstance(train_data, Dataset): raise TypeError("train_data must be of type jaxutils.Dataset") + def _check_optim(optim: Any) -> None: if not isinstance(optim, ox.GradientTransformation): raise TypeError("optax_optim must be of type optax.GradientTransformation") + def _check_num_iters(num_iters: Any) -> None: if not isinstance(num_iters, int): raise TypeError("num_iters must be of type int") - if not num_iters > 0: + if not num_iters > 0: raise ValueError("num_iters must be positive") - + + def _check_log_rate(log_rate: Any) -> None: if not isinstance(log_rate, int): raise TypeError("log_rate must be of type int") - - if not log_rate > 0: + + if not log_rate > 0: raise ValueError("log_rate must be positive") + def _check_verbose(verbose: Any) -> None: if not isinstance(verbose, bool): raise TypeError("verbose must be of type bool") -def _check_key(key: Any) -> None: - pass def _check_batch_size(batch_size: Any) -> None: if not isinstance(batch_size, int): raise TypeError("batch_size must be of type int") - + if not batch_size == -1: - if not batch_size > 0: + if not batch_size > 0: raise ValueError("batch_size must be positive") __all__ = [ "fit", "get_batch", -] \ No newline at end of file +] From 026d045603c539e375ff9e9dfc392d3c3203df3d Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 16:42:16 +0000 Subject: [PATCH 28/81] Add some checks to fit. --- jaxutils/fit.py | 13 +++++++++++++ jaxutils/module.py | 31 +++++++++++++++---------------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 2552b61..6e44e0c 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -20,6 +20,7 @@ import jax.random as jr import optax as ox +import jax.tree_util as jtu from jax.random import KeyArray from jax._src.random import _check_prng_key from jaxtyping import Array, Float @@ -139,6 +140,18 @@ def _check_model(model: Any) -> None: if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") + uncstr_ = unconstrain(model) + cstr_ = constrain(uncstr_) + + if not jtu.tree_structure(model) == jtu.tree_structure(model.trainables): + raise TypeError("trainables should have same tree structure as model") + + if not jtu.tree_structure(model) == jtu.tree_structure(uncstr_): + raise TypeError("bijectors should have same tree structure as model") + + if not jtu.tree_structure(model) == jtu.tree_structure(cstr_): + raise TypeError("bijectors should have same tree structure as model") + def _check_objective(objective: Any) -> None: """Check that the objective is of type Objective.""" diff --git a/jaxutils/module.py b/jaxutils/module.py index f18cb98..0791dca 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,18 +27,6 @@ from .bijectors import Bijector -def tree_def(obj: Module): - """Return Module tree definition.""" - _, tree_def_ = jtu.tree_flatten(obj) - return tree_def_ - - -def leaves(obj: Module): - """Return Module leaves.""" - leaves_, _ = jtu.tree_flatten(obj) - return leaves_ - - def default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, @@ -60,7 +48,7 @@ def default_bijectors(obj: Module) -> Module: Module: A PyTree of bijectors comprising the same structure as `obj`. """ - tree_def_ = tree_def(obj) + tree_def_ = jtu.tree_structure(obj) def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: """Unpack bijectors from metatdata.""" @@ -233,8 +221,15 @@ def set_trainables(self, tree: Module) -> Module: Returns: Module. A new instance with the updated trainablility status tree. """ + + if not isinstance(tree, Module): + raise TypeError("Tree must be a JaxUtils Module.") + + if not jtu.tree_structure(tree) == jtu.tree_structure(self): + raise ValueError("Tree must have the same structure as the Module.") + return self.__set_trainables_func__( - lambda obj: tree_def(obj).unflatten(leaves(tree)) + lambda obj: jtu.tree_structure(obj).unflatten(jtu.tree_leaves(tree)) ) def set_bijectors(self, tree: Module) -> Module: @@ -246,8 +241,12 @@ def set_bijectors(self, tree: Module) -> Module: Returns: Module. A new instance with the updated trainablility status tree. """ + + if not isinstance(tree, Module): + raise TypeError("tree must be a JaxUtils Module.") + return self.__set_bijectors_func__( - lambda obj: tree_def(obj).unflatten(leaves(tree)) + lambda obj: jtu.tree_structure(obj).unflatten(jtu.tree_leaves(tree)) ) def __set_trainables_func__( @@ -345,7 +344,7 @@ def tree_unflatten(cls, aux, dynamic_field_values): __all__ = [ "Module", "param", - "constrain", + "default_trainables" "default_bijectors" "constrain", "unconstrain", "stop_gradients", ] From 2765c3014be272b8a493b931dd2f169f8b14ddce Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 16:51:10 +0000 Subject: [PATCH 29/81] Update checks. --- jaxutils/fit.py | 14 +++++++------- jaxutils/module.py | 10 ++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 6e44e0c..ce30412 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -28,6 +28,7 @@ from .module import Module, constrain, unconstrain, stop_gradients from .dataset import Dataset +from .bijectors import Bijector from .objective import Objective from .progress_bar import progress_bar_scan @@ -140,17 +141,16 @@ def _check_model(model: Any) -> None: if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") - uncstr_ = unconstrain(model) - cstr_ = constrain(uncstr_) - if not jtu.tree_structure(model) == jtu.tree_structure(model.trainables): raise TypeError("trainables should have same tree structure as model") - if not jtu.tree_structure(model) == jtu.tree_structure(uncstr_): - raise TypeError("bijectors should have same tree structure as model") + def _is_bij(x): + return isinstance(x, Bijector) - if not jtu.tree_structure(model) == jtu.tree_structure(cstr_): - raise TypeError("bijectors should have same tree structure as model") + if not jtu.tree_structure( + jtu.tree_map(lambda _: True, model.bijectors, is_leaf=_is_bij) + ) == jtu.tree_structure(model): + raise ValueError("bijectors tree must have the same structure as the Module.") def _check_objective(objective: Any) -> None: diff --git a/jaxutils/module.py b/jaxutils/module.py index 0791dca..275fc74 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -245,6 +245,16 @@ def set_bijectors(self, tree: Module) -> Module: if not isinstance(tree, Module): raise TypeError("tree must be a JaxUtils Module.") + def _is_bij(x): + return isinstance(x, Bijector) + + if not jtu.tree_structure( + jtu.tree_map(lambda _: True, tree, is_leaf=_is_bij) + ) == jtu.tree_structure(self): + raise ValueError( + "bijectors tree must have the same structure as the Module." + ) + return self.__set_bijectors_func__( lambda obj: jtu.tree_structure(obj).unflatten(jtu.tree_leaves(tree)) ) From d36ad74d7e57250aa4ea6dc314d5798755b8842d Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 16:58:09 +0000 Subject: [PATCH 30/81] Add default trainable status to param field. --- jaxutils/module.py | 46 +++++++++++++++++++++++++++++++++++++------- tests/test_module.py | 45 +++++++++++++++++++++++++++++-------------- 2 files changed, 70 insertions(+), 21 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 275fc74..ba13d53 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,7 +27,7 @@ from .bijectors import Bijector -def default_trainables(obj: Module) -> Module: +def _default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, every parameter within the model is trainable. @@ -35,10 +35,38 @@ def default_trainables(obj: Module) -> Module: Returns: Module: A Module of boolean trainability statuses. """ - return jtu.tree_map(lambda _: True, obj) + tree_def_ = jtu.tree_structure(obj) + + def _unpack_trainables_from_meta(obj: Module) -> List[bool]: + """Unpack trainables from metatdata.""" + trainables_ = [] + + for field_ in fields(obj): + try: + value_ = obj.__dict__[field_.name] + except KeyError: + continue + + if not field_.metadata.get("static", False): + if field_.metadata.get("transform", None) is not None: + trainables_.append(field_.metadata["trainable"]) + + elif isinstance(value_, Module): + for value__ in _unpack_trainables_from_meta(value_): + trainables_.append(value__) + + else: + trainables_.append(value_) -def default_bijectors(obj: Module) -> Module: + return trainables_ + + trainables_ = _unpack_trainables_from_meta(obj) + + return tree_def_.unflatten(trainables_) + + +def _default_bijectors(obj: Module) -> Module: """Given a Module object, return an equinox Module of bijectors comprising the same structure. Args: @@ -79,7 +107,7 @@ def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: return tree_def_.unflatten(bijectors_) -def param(transform: Bijector, **kwargs: Any): +def param(transform: Bijector, trainable: bool = True, **kwargs: Any): """Used for marking default parameter transformations. !!! example @@ -104,6 +132,10 @@ class MyModule(jaxutils.Module): if "transform" in metadata: raise ValueError("Cannot use metadata with `transform` already set.") metadata["transform"] = transform + if "trainable" in metadata: + raise ValueError("Cannot use metadata with `trainable` already set.") + metadata["trainable"] = trainable + return field(**kwargs) @@ -171,8 +203,8 @@ class Module(eqx.Module): def __new__( cls, - __trainables_func__: Callable[[Module], Module] = default_trainables, - __bijectors_func__: Callable[[Module], Module] = default_bijectors, + __trainables_func__: Callable[[Module], Module] = _default_trainables, + __bijectors_func__: Callable[[Module], Module] = _default_bijectors, *args: Any, **kwargs: Any, ) -> Module: @@ -354,7 +386,7 @@ def tree_unflatten(cls, aux, dynamic_field_values): __all__ = [ "Module", "param", - "default_trainables" "default_bijectors" "constrain", + "constrain", "unconstrain", "stop_gradients", ] diff --git a/tests/test_module.py b/tests/test_module.py index c4ec969..e0c4eb0 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,12 +14,12 @@ # ============================================================================== import jax.numpy as jnp -import pytest -from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients, default_bijectors, default_trainables +from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax + def test_module(): # Test init @@ -33,7 +33,11 @@ class Tree(Module): sub_tree: SubTree param_b: float = param(Softplus) - tree = Tree(param_a=1.0, sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), param_b=5.0) + tree = Tree( + param_a=1.0, + sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), + param_b=5.0, + ) assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 @@ -41,16 +45,17 @@ class Tree(Module): assert tree.sub_tree.param_e == 4.0 assert tree.param_b == 5.0 - # Test default bijectors - bijectors = default_bijectors(tree) + bijectors = tree.bijectors bijector_list = jtu.tree_leaves(bijectors) - for b1, b2 in zip(bijector_list, [Identity, Identity, Softplus, Softplus, Softplus]): + for b1, b2 in zip( + bijector_list, [Identity, Identity, Softplus, Softplus, Softplus] + ): assert b1 == b2 # Test default trainables - trainables = default_trainables(tree) + trainables = tree.trainables trainable_list = jtu.tree_leaves(trainables) for t1, t2 in zip(trainable_list, [True, True, True, True, True]): @@ -59,26 +64,38 @@ class Tree(Module): # Test constrain and unconstrain constrained = constrain(tree) unconstrained = unconstrain(tree) - + leafs = jtu.tree_leaves(tree) - for l1, l2, bij in zip(leafs, jtu.tree_leaves(constrained), [Identity, Identity, Softplus, Softplus, Softplus]): + for l1, l2, bij in zip( + leafs, + jtu.tree_leaves(constrained), + [Identity, Identity, Softplus, Softplus, Softplus], + ): assert bij.forward(l1) == l2 - for l1, l2, bij in zip(leafs, jtu.tree_leaves(unconstrained), [Identity, Identity, Softplus, Softplus, Softplus]): + for l1, l2, bij in zip( + leafs, + jtu.tree_leaves(unconstrained), + [Identity, Identity, Softplus, Softplus, Softplus], + ): assert bij.inverse(l1) == l2 - _, tree_def = jax.tree_flatten(tree) trainables = tree_def.unflatten([True, False, True, False, False]) new_tree = tree.set_trainables(trainables) - # Test stop gradients def loss(tree): tree = stop_gradients(tree) - return jnp.sum(tree.param_a**2 + tree.sub_tree.param_c**2 + tree.sub_tree.param_d**2 + tree.sub_tree.param_e**2 + tree.param_b**2) + return jnp.sum( + tree.param_a**2 + + tree.sub_tree.param_c**2 + + tree.sub_tree.param_d**2 + + tree.sub_tree.param_e**2 + + tree.param_b**2 + ) g = jax.grad(loss)(new_tree) @@ -86,4 +103,4 @@ def loss(tree): assert g.sub_tree.param_c == 0.0 assert g.sub_tree.param_d == 6.0 assert g.sub_tree.param_e == 0.0 - assert g.param_b == 0.0 \ No newline at end of file + assert g.param_b == 0.0 From fad45c0ec4b719134044a1696adcfc3ffa3dd880 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:06:12 +0000 Subject: [PATCH 31/81] Update module.py --- jaxutils/module.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index ba13d53..6a88e71 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,6 +27,24 @@ from .bijectors import Bijector +class _cache_static_property: + """decorator to caches result of static immutable properties of a PyTree. + + Courtesy of Kernex library. + + The property must not contain any dynamic leaves. + """ + + def __init__(self, static_property: Callable): + self.name = static_property.__name__ + self.func = static_property + + def __get__(self, instance, owner): + attr = self.func(instance) + object.__setattr__(instance, self.name, attr) + return attr + + def _default_trainables(obj: Module) -> Module: """ Construct trainable statuses for each parameter. By default, @@ -226,7 +244,7 @@ def __new__( return instance - @property + @_cache_static_property def trainables(self) -> Module: """Return the boolean Module comprising trainability statuses. @@ -235,7 +253,7 @@ def trainables(self) -> Module: """ return self.__trainables_func__(self) - @property + @_cache_static_property def bijectors(self) -> Module: """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. From 0fb7b8d51454d507f414608a6faf594ab56afde6 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:07:33 +0000 Subject: [PATCH 32/81] Update module.py --- jaxutils/module.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 6a88e71..dd42759 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,8 +27,8 @@ from .bijectors import Bijector -class _cache_static_property: - """decorator to caches result of static immutable properties of a PyTree. +class _cached_static_property: + """Decorator to cache result of static immutable properties of a PyTree. Courtesy of Kernex library. @@ -244,7 +244,7 @@ def __new__( return instance - @_cache_static_property + @_cached_static_property def trainables(self) -> Module: """Return the boolean Module comprising trainability statuses. @@ -253,7 +253,7 @@ def trainables(self) -> Module: """ return self.__trainables_func__(self) - @_cache_static_property + @_cached_static_property def bijectors(self) -> Module: """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. From d1a2d3dbefd0bc8db8f7f3bd9a9a6e5d6e5aa7c5 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:18:34 +0000 Subject: [PATCH 33/81] Update bijectors.py --- jaxutils/bijectors.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/jaxutils/bijectors.py b/jaxutils/bijectors.py index 0ccdcf8..b7878f8 100644 --- a/jaxutils/bijectors.py +++ b/jaxutils/bijectors.py @@ -12,18 +12,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Bijectors for use in model optimisation.""" -import equinox as eqx import jax.numpy as jnp +import equinox as eqx from typing import Callable + class Bijector(eqx.Module): - """Base class for bijectors. + """Base class for parameter bijector transformations. These are useful for model optimisation, where gradients are taken in the "unconstrained" (real) parameter space, while evaluating the model takes place in the "constrained" parameter space. - All you need to do is define a forward and inverse transformation. + For example, the Softplus bijector, f, is defined as: + f(x) = log(1 + exp(x)) + f^{-1}(y) = log(exp(y) - 1) + + gives the "unconstrained" parameter space as the real line, while the "constrained" parameter space is the positive real line. + This means we can ensure that the corresponding model parameter remains positive during optimisation. + + To implement your own bijector, you need to do is define a `forward` and `inverse` transformation! Adding log_det_jacobian's etc., is on the TODO list of this class. """ + forward: Callable = eqx.static_field() inverse: Callable = eqx.static_field() @@ -38,11 +48,11 @@ class Bijector(eqx.Module): ) """Triangular bijector.""" -#TODO: Add triangular bijector. +# TODO: Add triangular bijector. __all__ = [ "Bijector", "Identity", - "Softplus", + "Softplus", ] From 3089fcb595eb13c9f13cda81875924921f3dfde8 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:18:55 +0000 Subject: [PATCH 34/81] Update bijectors.py --- jaxutils/bijectors.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jaxutils/bijectors.py b/jaxutils/bijectors.py index b7878f8..c9401f2 100644 --- a/jaxutils/bijectors.py +++ b/jaxutils/bijectors.py @@ -20,7 +20,9 @@ class Bijector(eqx.Module): - """Base class for parameter bijector transformations. These are useful for model optimisation, where gradients are taken in the "unconstrained" (real) parameter space, while evaluating the model takes place in the "constrained" parameter space. + """Base class for parameter bijector transformations. These are useful for model optimisation, where + gradients are taken in the "unconstrained" (real) parameter space, while evaluating the model takes place + in the "constrained" parameter space. For example, the Softplus bijector, f, is defined as: f(x) = log(1 + exp(x)) From fad89c67bbec0524ba793d51885e2b96e83ebe34 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:33:32 +0000 Subject: [PATCH 35/81] Remove legacy verify dataset. --- jaxutils/__init__.py | 13 ++++------ jaxutils/dataset.py | 58 +++++++++++++++---------------------------- tests/test_dataset.py | 21 ++++++++-------- 3 files changed, 35 insertions(+), 57 deletions(-) diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index ee38028..e4d5ddf 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,11 +13,11 @@ # limitations under the License. # ============================================================================== -from .module import Module, param, constrain, unconstrain +from .module import Module, constrain, param, unconstrain from .bijectors import Bijector, Identity, Softplus from .objective import Objective -from .dataset import Dataset, verify_dataset -from .fit import fit, get_batch +from .dataset import Dataset +from .fit import get_batch from .progress_bar import progress_bar_scan @@ -32,19 +32,16 @@ ) __all__ = [ - "Module", "Bijector", "Identity", "Softplus", "Objective", "Dataset", - "verify_dataset", + "Module", "param", - "build_bijectors", - "build_trainables", "constrain", "unconstrain", - "fit", + "stop_gradients" "fit", "get_batch", "progress_bar_scan", ] diff --git a/jaxutils/dataset.py b/jaxutils/dataset.py index 4c24364..3f6d702 100644 --- a/jaxutils/dataset.py +++ b/jaxutils/dataset.py @@ -20,13 +20,14 @@ import equinox as eqx + class Dataset(eqx.Module): + """Base class for datasets.""" + X: Optional[Float[Array, "N D"]] = None y: Optional[Float[Array, "N Q"]] = None - """Dataset class.""" - - #TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. + # TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. def __init__( self, @@ -34,6 +35,8 @@ def __init__( y: Optional[Float[Array, "N Q"]] = None, ) -> None: """ + Initialise a dataset object. + Args: X(Float[Array, "N D"]]): Input data. y(Float[Array, "N Q"]]): Output data. @@ -47,57 +50,38 @@ def __init__( self.y = y def __repr__(self) -> str: - return ( - f"- Number of datapoints: {self.X.shape[0]}\n- Dimension: {self.X.shape[1]}" - ) + """Returns a string representation of the dataset.""" + return f"- Number of observations: {self.n}\n- Input dimension: {self.in_dim}\n- Output dimension: {self.out_dim}" def is_supervised(self) -> bool: - """Returns True if the dataset is supervised.""" + """Returns `True` if the dataset is supervised.""" return self.X is not None and self.y is not None def is_unsupervised(self) -> bool: - """Returns True if the dataset is unsupervised.""" + """Returns `True` if the dataset is unsupervised.""" return self.X is None and self.y is not None - def __add__(self, other: Dataset) -> Dataset: - """Combines two datasets into one. The right-hand dataset is stacked beneath left.""" - x = jnp.concatenate((self.X, other.X)) + """Combine two datasets. Right hand dataset is stacked beneath the left.""" + X = jnp.concatenate((self.X, other.X)) y = jnp.concatenate((self.y, other.y)) - return Dataset(X=x, y=y) + return Dataset(X=X, y=y) @property def n(self) -> int: - """The number of observations in the dataset.""" + """Number of observations.""" return self.X.shape[0] @property def in_dim(self) -> int: - """The dimension of the input data.""" + """Dimension of the inputs, X.""" return self.X.shape[1] @property def out_dim(self) -> int: - """The dimension of the output data.""" + """Dimension of the outputs, y.""" return self.y.shape[1] - - -def verify_dataset(ds: Dataset) -> None: - """Apply a series of checks to the dataset to ensure that downstream operations are safe.""" - assert ds.X.ndim == 2, ( - "2-dimensional training inputs are required. Current dimension:" - f" {ds.X.ndim}." - ) - if ds.y is not None: - assert ds.y.ndim == 2, ( - "2-dimensional training outputs are required. Current dimension:" - f" {ds.y.ndim}." - ) - assert ds.X.shape[0] == ds.y.shape[0], ( - "Number of inputs must equal the number of outputs. \nCurrent" - f" counts:\n- X: {ds.X.shape[0]}\n- y: {ds.y.shape[0]}" - ) def _check_shape(X: Float[Array, "N D"], y: Float[Array, "N Q"]) -> None: @@ -105,22 +89,20 @@ def _check_shape(X: Float[Array, "N D"], y: Float[Array, "N Q"]) -> None: if X is not None and y is not None: if X.shape[0] != y.shape[0]: raise ValueError( - f"X and y must have the same number of rows. Got X.shape={X.shape} and y.shape={y.shape}." + f"Inputs, X, and outputs, y, must have the same number of rows. Got X.shape={X.shape} and y.shape={y.shape}." ) - + if X is not None and X.ndim != 2: raise ValueError( - f"X must be a 2-dimensional array. Got X.ndim={X.ndim}." + f"Inputs, X, must be a 2-dimensional array. Got X.ndim={X.ndim}." ) if y is not None and y.ndim != 2: raise ValueError( - f"y must be a 2-dimensional array. Got y.ndim={y.ndim}." + f"Outputs, y, must be a 2-dimensional array. Got y.ndim={y.ndim}." ) __all__ = [ "Dataset", - "slice", - "verify_dataset", ] diff --git a/tests/test_dataset.py b/tests/test_dataset.py index 8b60898..d4e8daa 100644 --- a/tests/test_dataset.py +++ b/tests/test_dataset.py @@ -15,7 +15,7 @@ import jax.numpy as jnp import pytest -from jaxutils.dataset import Dataset, verify_dataset +from jaxutils.dataset import Dataset @pytest.mark.parametrize("n", [1, 10]) @@ -26,14 +26,14 @@ def test_dataset(n: int, outd: int, ind: int, n2: int) -> None: x = jnp.ones((n, ind)) y = jnp.ones((n, outd)) d = Dataset(X=x, y=y) - - verify_dataset(d) + assert d.n == n assert d.in_dim == ind assert d.out_dim == outd - - assert d.__repr__() == f"- Number of datapoints: {n}\n- Dimension: {ind}" - + assert ( + d.__repr__() + == f"- Number of observations: {n}\n- Input dimension: {ind}\n- Output dimension: {outd}" + ) # Test combine datasets. x2 = 2 * jnp.ones((n2, ind)) @@ -54,22 +54,24 @@ def test_dataset(n: int, outd: int, ind: int, n2: int) -> None: dunsup = Dataset(y=y) assert dunsup.is_unsupervised() is True + @pytest.mark.parametrize("nx, ny", [(1, 2), (2, 1), (10, 5), (5, 10)]) @pytest.mark.parametrize("outd", [1, 2, 10]) @pytest.mark.parametrize("ind", [1, 2, 10]) def test_dataset_assertions(nx: int, ny: int, outd: int, ind: int) -> None: x = jnp.ones((nx, ind)) y = jnp.ones((ny, outd)) - + with pytest.raises(ValueError): ds = Dataset(X=x, y=y) + @pytest.mark.parametrize("n", [1, 2, 10]) @pytest.mark.parametrize("outd", [1, 2, 10]) @pytest.mark.parametrize("ind", [1, 2, 10]) def test_2d_inputs(n: int, outd: int, ind: int) -> None: x = jnp.ones((n, ind)) - y = jnp.ones((n, )) + y = jnp.ones((n,)) with pytest.raises(ValueError): ds = Dataset(X=x, y=y) @@ -81,10 +83,7 @@ def test_2d_inputs(n: int, outd: int, ind: int) -> None: ds = Dataset(X=x, y=y) - - def test_y_none() -> None: x = jnp.ones((10, 1)) d = Dataset(X=x) - verify_dataset(d) assert d.y is None From 0737314e90ead7ec4f78ec2f3b62d823714b4e1e Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 17:39:13 +0000 Subject: [PATCH 36/81] Update fit.py --- jaxutils/fit.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/jaxutils/fit.py b/jaxutils/fit.py index ce30412..d35b098 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -47,9 +47,61 @@ def fit( ) -> Tuple[Module, Array]: """Train a Module model with respect to a supplied Objective function. Optimisers used here should originate from Optax. + !!! example + ```python + import jax.numpy as jnp + import jaxutils as ju + import optax as ox + + # (1) Create a dataset: + X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) + y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) + D = ju.Dataset(X, y) + + # (2) Define your model: + class LinearModel(ju.Module): + weight: float = ju.param(transform=ju.Identity, trainable=True) + bias: float = ju.param(transform=ju.Identity, trainable=True) + + def __call__(self, x): + return self.weight * x + self.bias + + model = LinearModel(weight=1.0, bias=1.0) + + # (3) Define your loss function: + class MeanSqaureError(Objective): + def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: + y_pred = model(train_data.X) + return jnp.mean((y_pred - train_data.y) ** 2) + + loss = MeanSqaureError() + + # (4) Define your optimiser: + optim = ox.adam(1e-3) + + # (5) Train your model: + model, history = ju.fit(model=model, objective=loss, train_data=D, optim=optim, num_iters=1000) + + # (6) Plot the training history: + import matplotlib.pyplot as plt + plt.plot(history) + plt.show() + + # (7) Plot the model predictions: + X_test = jnp.linspace(0.0, 10.0, 1000).reshape(-1, 1) + y_test = model(X_test) + plt.plot(X_test, y_test) + plt.scatter(D.X, D.y) + plt.show() + + # (8) Print the final model parameters: + print(model) + ``` + Args: model (Module): The model Module to be optimised. objective (Objective): The objective function that we are optimising with respect to. + train_data (Dataset): The training data to be used for the optimisation. optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. batch_size (Optional[int]): The size of the mini-batch to use. Defaults to -1 (i.e. full batch). @@ -124,6 +176,7 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: Args: train_data (Dataset): The training dataset. batch_size (int): The batch size. + key (KeyArray): The random key to use for the batch selection. Returns: Dataset: The batched dataset. @@ -137,7 +190,7 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: def _check_model(model: Any) -> None: - """Check that the model is of type Module.""" + """Check that the model is of type Module. Check trainables and bijectors tree structure.""" if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") @@ -166,11 +219,13 @@ def _check_train_data(train_data: Any) -> None: def _check_optim(optim: Any) -> None: + """Check that the optimiser is of type GradientTransformation.""" if not isinstance(optim, ox.GradientTransformation): raise TypeError("optax_optim must be of type optax.GradientTransformation") def _check_num_iters(num_iters: Any) -> None: + """Check that the number of iterations is of type int and positive.""" if not isinstance(num_iters, int): raise TypeError("num_iters must be of type int") @@ -179,6 +234,7 @@ def _check_num_iters(num_iters: Any) -> None: def _check_log_rate(log_rate: Any) -> None: + """Check that the log rate is of type int and positive.""" if not isinstance(log_rate, int): raise TypeError("log_rate must be of type int") @@ -187,11 +243,13 @@ def _check_log_rate(log_rate: Any) -> None: def _check_verbose(verbose: Any) -> None: + """Check that the verbose is of type bool.""" if not isinstance(verbose, bool): raise TypeError("verbose must be of type bool") def _check_batch_size(batch_size: Any) -> None: + """Check that the batch size is of type int and positive if not minus 1.""" if not isinstance(batch_size, int): raise TypeError("batch_size must be of type int") From daf5d2268adea350c3fd16d37d2ed98b618ade0b Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 18:12:07 +0000 Subject: [PATCH 37/81] Add compilation message to progress bar. --- jaxutils/__init__.py | 4 ++-- jaxutils/fit.py | 4 ++-- jaxutils/progress_bar.py | 44 ++++++++++++++++++++++++++-------------- 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index e4d5ddf..81341fd 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -18,7 +18,7 @@ from .objective import Objective from .dataset import Dataset from .fit import get_batch -from .progress_bar import progress_bar_scan +from .progress_bar import progress_bar __authors__ = "Thomas Pinder, Daniel Dodd" @@ -43,7 +43,7 @@ "unconstrain", "stop_gradients" "fit", "get_batch", - "progress_bar_scan", + "progress_bar", ] from . import _version diff --git a/jaxutils/fit.py b/jaxutils/fit.py index d35b098..10ecc93 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -30,7 +30,7 @@ from .dataset import Dataset from .bijectors import Bijector from .objective import Objective -from .progress_bar import progress_bar_scan +from .progress_bar import progress_bar def fit( @@ -159,7 +159,7 @@ def step(carry, iter_num__and__key): # Progress bar, if verbose True. if verbose: - step = progress_bar_scan(num_iters, log_rate)(step) + step = progress_bar(num_iters, log_rate)(step) # Optimisation loop. (model, _), history = jax.lax.scan(step, (model, state), (iter_nums, iter_keys)) diff --git a/jaxutils/progress_bar.py b/jaxutils/progress_bar.py index e3c36f8..603cd93 100644 --- a/jaxutils/progress_bar.py +++ b/jaxutils/progress_bar.py @@ -21,21 +21,39 @@ from tqdm.auto import tqdm -#TODO: (Dan D) add a compilation message to the progress bar from your private code. +def progress_bar(num_iters: int, log_rate: int) -> Callable: + """Progress bar decorator for the body function of a `jax.lax.scan`. -def progress_bar_scan(num_iters: int, log_rate: int) -> Callable: - """Progress bar for Jax.lax scans (adapted from https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/).""" + !!! example + ```python + + carry = jnp.array(0.0) + iteration_numbers = jnp.arange(100) + + @progress_bar(num_iters=x.shape[0], log_rate=10) + def body_func(carry, x): + return carry, x + + carry, _ = jax.lax.scan(body_func, carry, iteration_numbers) + ``` + + Adapted from the excellent blog post: https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/. + + Might be nice in future to directly create a general purpose `verbose scan` inplace of a for a jax.lax.scan, + that takes the same arguments as a jax.lax.scan, but prints a progress bar. + """ tqdm_bars = {} remainder = num_iters % log_rate - def _define_tqdm(args: Any, transform: Any) -> None: - """Define a tqdm progress bar.""" - tqdm_bars[0] = tqdm(range(num_iters)) + """Define a tqdm progress bar.""" + tqdm_bars[0] = tqdm(range(num_iters)) + tqdm_bars[0].set_description("Compiling...", refresh=True) def _update_tqdm(args: Any, transform: Any) -> None: """Update the tqdm progress bar with the latest objective value.""" loss_val, arg = args + tqdm_bars[0].set_description(f"Training", refresh=False) tqdm_bars[0].update(arg) tqdm_bars[0].set_postfix({"Objective": f"{loss_val: .2f}"}) @@ -58,19 +76,15 @@ def _not_callback(_) -> int: _ = lax.cond(cond, _do_callback, _not_callback, operand=None) def _update_progress_bar(loss_val: Float[Array, "1"], iter_num: int) -> None: - """Updates tqdm progress bar of a JAX scan or loop.""" + """Update the tqdm progress bar.""" # Conditions for iteration number - is_first: bool = iter_num == 0 is_multiple: bool = (iter_num % log_rate == 0) & ( iter_num != num_iters - remainder ) is_remainder: bool = iter_num == num_iters - remainder is_last: bool = iter_num == num_iters - 1 - # Define progress bar, if first iteration - _callback(is_first, _define_tqdm, None) - # Update progress bar, if multiple of log_rate _callback(is_multiple, _update_tqdm, (loss_val, log_rate)) @@ -80,8 +94,8 @@ def _update_progress_bar(loss_val: Float[Array, "1"], iter_num: int) -> None: # Close progress bar, if last iteration _callback(is_last, _close_tqdm, None) - def _progress_bar_scan(body_fun: Callable) -> Callable: - """Decorator that adds a progress bar to `body_fun` used in `lax.scan`.""" + def _progress_bar(body_fun: Callable) -> Callable: + """Decorator that adds a progress bar to `body_fun` used in `jax.lax.scan`.""" def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any: @@ -104,9 +118,9 @@ def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any: return wrapper_progress_bar - return _progress_bar_scan + return _progress_bar __all__ = [ - "progress_bar_scan", + "progress_bar", ] From 15fce76a1a1ff0949cd9267efed588c59ef7fd18 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 18:41:46 +0000 Subject: [PATCH 38/81] Leaf node checking. --- jaxutils/module.py | 74 +++++++++++++++++++++++++++++++------------ jaxutils/objective.py | 21 +++++++++--- 2 files changed, 70 insertions(+), 25 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index dd42759..68a50d1 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -32,7 +32,8 @@ class _cached_static_property: Courtesy of Kernex library. - The property must not contain any dynamic leaves. + !!! note + The decorated property must *NOT* contain any dynamic attributes / PyTree leaves. """ def __init__(self, static_property: Callable): @@ -56,7 +57,7 @@ def _default_trainables(obj: Module) -> Module: tree_def_ = jtu.tree_structure(obj) def _unpack_trainables_from_meta(obj: Module) -> List[bool]: - """Unpack trainables from metatdata.""" + """Unpack trainables from metatdata defined by the `param` field.""" trainables_ = [] for field_ in fields(obj): @@ -97,7 +98,8 @@ def _default_bijectors(obj: Module) -> Module: tree_def_ = jtu.tree_structure(obj) def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: - """Unpack bijectors from metatdata.""" + """Unpack bijectors from metatdata defined by the `param` field.""" + bijectors_ = [] for field_ in fields(obj): @@ -139,8 +141,8 @@ class MyModule(jaxutils.Module): All PyTree leaves of the Module must be marked. Args: - transform (Bijector). The default bijector that should be should upon Module initialisation. - **kwargs (Any). If any are passed then they are passed on to `datacalss.field`. + transform (Bijector): The default bijector that should be should upon Module initialisation. + **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) """ try: @@ -153,6 +155,9 @@ class MyModule(jaxutils.Module): if "trainable" in metadata: raise ValueError("Cannot use metadata with `trainable` already set.") metadata["trainable"] = trainable + if "is_param" in metadata: + raise ValueError("Cannot use metadata with `is_param` already set.") + metadata["__is_param__"] = True return field(**kwargs) @@ -207,18 +212,24 @@ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) -# TODO: Leaf node typing. E.g., to distiguish between boolean PyTree and one that is jax.Arrays. -# TODO: Leaf node checking. - - class Module(eqx.Module): """Base Module object. This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), with modifications to handle bijector transformations and trainability statuses. + !!! example + ```python + class MyModule(jaxutils.Module): + param_a: float = jaxutils.param(jaxutils.Identity) + param_b: float = jaxutils.param(jaxutils.Softplus) + ``` + + All PyTree leaves of the Module must be marked with the `param` field. """ + # TODO: Leaf node typing. E.g., to distiguish between boolean PyTree and one that is jax.Arrays. + def __new__( cls, __trainables_func__: Callable[[Module], Module] = _default_trainables, @@ -238,27 +249,48 @@ def __new__( Module. An instance of the JaxUtils Module class. """ - instance = super().__new__(cls) - object.__setattr__(instance, "__trainables_func__", __trainables_func__) - object.__setattr__(instance, "__bijectors_func__", __bijectors_func__) + obj = super().__new__(cls) + + # Leaf node checking. + for field_ in fields(obj): + + if field_.metadata.get("__is_param__") is None: + + if field_.metadata.get("static", False): + continue + + try: + value_ = obj.__dict__[field_.name] + except KeyError: + continue + + if isinstance(value_, Module): + continue + + raise ValueError( + f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." + ) + + object.__setattr__(obj, "__trainables_func__", __trainables_func__) + object.__setattr__(obj, "__bijectors_func__", __bijectors_func__) - return instance + return obj - @_cached_static_property + @_cached_static_property # Cacheing is fine here as the trainables are static and `Module` is frozen/inmutable. def trainables(self) -> Module: """Return the boolean Module comprising trainability statuses. Returns: - Module. The boolean Module comprising trainability statuses for the Module. + Module: The boolean Module comprising trainability statuses for the Module. """ return self.__trainables_func__(self) - @_cached_static_property + @_cached_static_property # Cacheing is fine here as the trainables are static and `Module` is frozen/inmutable. def bijectors(self) -> Module: """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. Returns: - Module. The Bijector Module of parameter transformations. + Module: The Bijector Module of parameter transformations. """ return self.__bijectors_func__(self) @@ -266,10 +298,10 @@ def set_trainables(self, tree: Module) -> Module: """Set parameter trainability status for the Module. Args: - tree (Module). The boolean tree of trainability status comprising the same tree structure as the underlying Module. + tree (Module): The boolean tree of trainability status comprising the same tree structure as the underlying Module. Returns: - Module. A new instance with the updated trainablility status tree. + Module: A new instance with the updated trainablility status tree. """ if not isinstance(tree, Module): @@ -286,10 +318,10 @@ def set_bijectors(self, tree: Module) -> Module: """Set parameter transformations for the Module. Args: - tree (Module). The Bijector tree of parameter transformations comprising the same tree structure as the underlying Module. + tree (Module): The Bijector tree of parameter transformations comprising the same tree structure as the underlying Module. Returns: - Module. A new instance with the updated trainablility status tree. + Module: A new instance with the updated trainablility status tree. """ if not isinstance(tree, Module): diff --git a/jaxutils/objective.py b/jaxutils/objective.py index db2c675..bdf2600 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -19,8 +19,21 @@ from .dataset import Dataset from .module import Module + class Objective(eqx.Module): - """Base class for objective functions.""" + """Base class for objective functions. + + !!! example + ```python + class MeanSquaredError(Objective): + def evaluate(self, model, train_data): + return jnp.mean((train_data.y - model(train_data.X)) ** 2) + ``` + + !!! note + The objective function is negated if `negative=True`. + """ + negative: bool = eqx.static_field() constant: float = eqx.static_field() @@ -29,14 +42,14 @@ def __init__(self, negative: bool = False): Args: negative(bool): Whether to negate the objective function. - + Returns: Objective: An objective function. """ if not isinstance(negative, bool): raise TypeError("negative must be a bool.") - + self.negative = negative self.constant = -1.0 if negative else 1.0 @@ -47,7 +60,7 @@ def __call__(self, model: Module, train_data: Dataset) -> float: model(Base): A model. *args: Additional arguments. **kwargs: Additional keyword arguments. - + Returns: float: The objective function. """ From 425348508decc5664a3c846caf17bc9fe9c1cdb6 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 18:48:12 +0000 Subject: [PATCH 39/81] Update module.py --- jaxutils/module.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/jaxutils/module.py b/jaxutils/module.py index 68a50d1..db39b40 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -229,6 +229,10 @@ class MyModule(jaxutils.Module): """ # TODO: Leaf node typing. E.g., to distiguish between boolean PyTree and one that is jax.Arrays. + # TODO: remove the need for the `__trainables_func__` and `__bijectors_func__` arguments, instead unpack the + # trainables' and bijectors' leaves during the __new__ given the checks already performed in the `param` field, + # and define `__trainables_leaves__` and `__bijectors_leaves__` as properties. + # This would reduce the number of times we have to traverse the PyTree. def __new__( cls, From 51b33ffaae20bbea5f148c1a3b202a3315ad6bfd Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 22:01:37 +0000 Subject: [PATCH 40/81] Switch from functional to leaf approach --- jaxutils/module.py | 188 ++++++++++++++------------------------------- 1 file changed, 59 insertions(+), 129 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index db39b40..7c69613 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,7 +20,7 @@ from jax import lax from dataclasses import fields, field -from typing import Any, Callable, List +from typing import Any, Callable, List, Tuple import equinox as eqx @@ -46,87 +46,6 @@ def __get__(self, instance, owner): return attr -def _default_trainables(obj: Module) -> Module: - """ - Construct trainable statuses for each parameter. By default, - every parameter within the model is trainable. - - Returns: - Module: A Module of boolean trainability statuses. - """ - tree_def_ = jtu.tree_structure(obj) - - def _unpack_trainables_from_meta(obj: Module) -> List[bool]: - """Unpack trainables from metatdata defined by the `param` field.""" - trainables_ = [] - - for field_ in fields(obj): - try: - value_ = obj.__dict__[field_.name] - except KeyError: - continue - - if not field_.metadata.get("static", False): - - if field_.metadata.get("transform", None) is not None: - trainables_.append(field_.metadata["trainable"]) - - elif isinstance(value_, Module): - for value__ in _unpack_trainables_from_meta(value_): - trainables_.append(value__) - - else: - trainables_.append(value_) - - return trainables_ - - trainables_ = _unpack_trainables_from_meta(obj) - - return tree_def_.unflatten(trainables_) - - -def _default_bijectors(obj: Module) -> Module: - """Given a Module object, return an equinox Module of bijectors comprising the same structure. - - Args: - obj (Module): The PyTree object whoose default bijectors (from the param field) you would to obtain. - - Returns: - Module: A PyTree of bijectors comprising the same structure as `obj`. - """ - - tree_def_ = jtu.tree_structure(obj) - - def _unpack_bijectors_from_meta(obj: Module) -> List[Bijector]: - """Unpack bijectors from metatdata defined by the `param` field.""" - - bijectors_ = [] - - for field_ in fields(obj): - try: - value_ = obj.__dict__[field_.name] - except KeyError: - continue - - if not field_.metadata.get("static", False): - - if field_.metadata.get("transform", None) is not None: - bijectors_.append(field_.metadata["transform"]) - - elif isinstance(value_, Module): - for value__ in _unpack_bijectors_from_meta(value_): - bijectors_.append(value__) - - else: - bijectors_.append(value_) - - return bijectors_ - - bijectors_ = _unpack_bijectors_from_meta(obj) - - return tree_def_.unflatten(bijectors_) - - def param(transform: Bijector, trainable: bool = True, **kwargs: Any): """Used for marking default parameter transformations. @@ -155,9 +74,9 @@ class MyModule(jaxutils.Module): if "trainable" in metadata: raise ValueError("Cannot use metadata with `trainable` already set.") metadata["trainable"] = trainable - if "is_param" in metadata: - raise ValueError("Cannot use metadata with `is_param` already set.") - metadata["__is_param__"] = True + if "param" in metadata: + raise ValueError("Cannot use metadata with `param` already set.") + metadata["param"] = True return field(**kwargs) @@ -228,16 +147,11 @@ class MyModule(jaxutils.Module): All PyTree leaves of the Module must be marked with the `param` field. """ - # TODO: Leaf node typing. E.g., to distiguish between boolean PyTree and one that is jax.Arrays. - # TODO: remove the need for the `__trainables_func__` and `__bijectors_func__` arguments, instead unpack the - # trainables' and bijectors' leaves during the __new__ given the checks already performed in the `param` field, - # and define `__trainables_leaves__` and `__bijectors_leaves__` as properties. - # This would reduce the number of times we have to traverse the PyTree. - def __new__( cls, - __trainables_func__: Callable[[Module], Module] = _default_trainables, - __bijectors_func__: Callable[[Module], Module] = _default_bijectors, + __trainables_leaves__: List[bool] = None, + __bijectors_leaves__: List[Bijector] = None, + __unpack_meta__: bool = True, *args: Any, **kwargs: Any, ) -> Module: @@ -246,6 +160,7 @@ def __new__( Args: __trainables_func__ (Callable[[Module], Module]). The function that constructs the trainables PyTree from `self`. __bijectors_func__ (Callable[[Module], Module]). The function that constructs the bijectors PyTree from `self`. + __unpack_meta__ (bool). Whether to unpack the metadata from the `param` field. *args (Any). Arguments. **kwargs (Any). Keyword arguments. @@ -255,28 +170,47 @@ def __new__( obj = super().__new__(cls) - # Leaf node checking. - for field_ in fields(obj): + def _unpack_meta(obj: Module) -> Tuple[List[bool], List[Bijector]]: + """Unpack trainables from metadata defined by the `param` field. + + If a leaf is not marked as a parameter then this will raise an error. + """ + train_meta_ = [] + bij_meta_ = [] - if field_.metadata.get("__is_param__") is None: + for field_ in fields(obj): if field_.metadata.get("static", False): continue - try: - value_ = obj.__dict__[field_.name] - except KeyError: + if field_.metadata.get("param", False): + train_meta_.append(field_.metadata["trainable"]) + bij_meta_.append(field_.metadata["transform"]) continue - if isinstance(value_, Module): + if issubclass(field_.type, Module): + for trainable_, bijector_ in zip(*_unpack_meta(field_.type)): + train_meta_.append(trainable_) + bij_meta_.append(bijector_) continue raise ValueError( f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." ) - object.__setattr__(obj, "__trainables_func__", __trainables_func__) - object.__setattr__(obj, "__bijectors_func__", __bijectors_func__) + return train_meta_, bij_meta_ + + if __unpack_meta__: + train_meta_, bij_meta_ = _unpack_meta(obj) + + if __trainables_leaves__ is None: + __trainables_leaves__ = train_meta_ + + if __bijectors_leaves__ is None: + __bijectors_leaves__ = bij_meta_ + + object.__setattr__(obj, "__trainables_leaves__", __trainables_leaves__) + object.__setattr__(obj, "__bijectors_leaves__", __bijectors_leaves__) return obj @@ -287,7 +221,7 @@ def trainables(self) -> Module: Returns: Module: The boolean Module comprising trainability statuses for the Module. """ - return self.__trainables_func__(self) + return jtu.tree_structure(self).unflatten(self.__trainables_leaves__) @_cached_static_property # Cacheing is fine here as the trainables are static and `Module` is frozen/inmutable. def bijectors(self) -> Module: @@ -296,7 +230,7 @@ def bijectors(self) -> Module: Returns: Module: The Bijector Module of parameter transformations. """ - return self.__bijectors_func__(self) + return jtu.tree_structure(self).unflatten(self.__bijectors_leaves__) def set_trainables(self, tree: Module) -> Module: """Set parameter trainability status for the Module. @@ -314,9 +248,7 @@ def set_trainables(self, tree: Module) -> Module: if not jtu.tree_structure(tree) == jtu.tree_structure(self): raise ValueError("Tree must have the same structure as the Module.") - return self.__set_trainables_func__( - lambda obj: jtu.tree_structure(obj).unflatten(jtu.tree_leaves(tree)) - ) + return self.__set_trainables_leaves__(jtu.tree_leaves(tree)) def set_bijectors(self, tree: Module) -> Module: """Set parameter transformations for the Module. @@ -341,20 +273,17 @@ def _is_bij(x): "bijectors tree must have the same structure as the Module." ) - return self.__set_bijectors_func__( - lambda obj: jtu.tree_structure(obj).unflatten(jtu.tree_leaves(tree)) - ) + return self.__set_bijectors_leaves__(jtu.tree_leaves(tree)) - def __set_trainables_func__( - self, __trainables_func__: Callable[[Module], Module] - ) -> Module: + def __set_trainables_leaves__(self, __trainables_leaves__: List[bool]) -> Module: """Set the trainables function for the class.""" # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( cls=self.__class__, - __trainables_func__=__trainables_func__, - __bijectors_func__=self.__bijectors_func__, + __trainables_leaves__=__trainables_leaves__, + __bijectors_leaves__=self.__bijectors_leaves__, + __unpack_meta__=False, ) # TODO: Might have to filter attribute dict here? @@ -363,16 +292,17 @@ def __set_trainables_func__( return new_instance - def __set_bijectors_func__( - self, __bijectors_func__: Callable[[Module], Module] + def __set_bijectors_leaves__( + self, __bijectors_leaves__: Callable[[Module], Module] ) -> Module: """Set the bijectors function for the class.""" # Create new class instance, with the adjusted trainable function. new_instance = self.__class__.__new__( self.__class__, - __trainables_func_=self.__trainables_func__, - __bijectors_func_=__bijectors_func__, + __trainables_leaves__=self.__trainables_leaves__, + __bijectors_leaves__=__bijectors_leaves__, + __unpack_meta__=False, ) # TODO: Might have to filter attribute dict here? @@ -382,15 +312,15 @@ def __set_bijectors_func__( return new_instance def tree_flatten(self): - """Same as Equinox, except for the addition of the `static_funcs`.""" + """Same as Equinox, except for the addition of the `static_meta`.""" dynamic_field_names = [] dynamic_field_values = [] static_field_names = [] static_field_values = [] - static_funcs = [ - self.__trainables_func__, - self.__bijectors_func__, + static_meta = [ + self.__trainables_leaves__, + self.__bijectors_leaves__, ] for field_ in fields(self): @@ -410,22 +340,22 @@ def tree_flatten(self): tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(static_funcs), + tuple(static_meta), ) @classmethod def tree_unflatten(cls, aux, dynamic_field_values): - """Same as Equinox, except for the addition of the `static_funcs`.""" + """Same as Equinox, except for the addition of the `static_meta`.""" - dynamic_field_names, static_field_names, static_field_values, static_funcs = aux + dynamic_field_names, static_field_names, static_field_values, static_meta = aux # These are the static functions that determine the trainable and bijector PyTree's from self. - __trainables_func__, __bijectors_func__ = static_funcs + __trainables_leaves__, __bijectors_leaves__ = static_meta self = cls.__new__( cls=cls, - __trainables_func__=__trainables_func__, - __bijectors_func__=__bijectors_func__, + __trainables_leaves__=__trainables_leaves__, + __bijectors_leaves__=__bijectors_leaves__, ) for name, value in zip(dynamic_field_names, dynamic_field_values): From 7f4a7f6cc75d8f81950c27ab3be69df17e250903 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 23:09:44 +0000 Subject: [PATCH 41/81] Switch to metadata. --- jaxutils/module.py | 193 +++++++++++++++++-------------------------- tests/test_module.py | 2 +- 2 files changed, 78 insertions(+), 117 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 7c69613..7952f62 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,13 +20,18 @@ from jax import lax from dataclasses import fields, field -from typing import Any, Callable, List, Tuple +from typing import Any, Callable, NamedTuple +from collections import namedtuple import equinox as eqx from .bijectors import Bijector +"""NamedTuple for storing metadata (i.e., trainables and bijectors). """ +_Meta = namedtuple("_Meta", ["trainables", "bijectors"]) + + class _cached_static_property: """Decorator to cache result of static immutable properties of a PyTree. @@ -131,6 +136,43 @@ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) +def _unpack_meta(obj: Module) -> NamedTuple: + """Unpack metadata (i.e., trainables and bijectors) defined by the `param` field. + + Args: + obj (Module): The PyTree object whoose leaves are to be transformed. + + Returns: + NamedTuple: A namedtuple with fields `trainables` and `bijectors`. + + Raises: + ValueError: If a leaf is not marked as a parameter and its type is not a subclass of `Module`. + """ + trainables, bijectors = [], [] + + for field_ in fields(obj): + + if field_.metadata.get("static", False): + continue + + if field_.metadata.get("param", False): + trainables.append(field_.metadata["trainable"]) + bijectors.append(field_.metadata["transform"]) + continue + + if issubclass(field_.type, Module): + for trainable, bijector in zip(*_unpack_meta(field_.type)): + trainables.append(trainable) + bijectors.append(bijector) + continue + + raise ValueError( + f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." + ) + + return _Meta(trainables, bijectors) + + class Module(eqx.Module): """Base Module object. @@ -149,88 +191,43 @@ class MyModule(jaxutils.Module): def __new__( cls, - __trainables_leaves__: List[bool] = None, - __bijectors_leaves__: List[Bijector] = None, - __unpack_meta__: bool = True, + __meta__: _Meta = None, *args: Any, **kwargs: Any, ) -> Module: - """This is used to set the trainables and bijectors functions. As we are working with frozen dataclasses. + """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). Args: - __trainables_func__ (Callable[[Module], Module]). The function that constructs the trainables PyTree from `self`. - __bijectors_func__ (Callable[[Module], Module]). The function that constructs the bijectors PyTree from `self`. - __unpack_meta__ (bool). Whether to unpack the metadata from the `param` field. + __meta__ (_Meta.) Metadata that define the models' trainables and bijectors PyTree leaves. *args (Any). Arguments. **kwargs (Any). Keyword arguments. Returns: Module. An instance of the JaxUtils Module class. """ - obj = super().__new__(cls) - - def _unpack_meta(obj: Module) -> Tuple[List[bool], List[Bijector]]: - """Unpack trainables from metadata defined by the `param` field. - - If a leaf is not marked as a parameter then this will raise an error. - """ - train_meta_ = [] - bij_meta_ = [] - - for field_ in fields(obj): - - if field_.metadata.get("static", False): - continue - - if field_.metadata.get("param", False): - train_meta_.append(field_.metadata["trainable"]) - bij_meta_.append(field_.metadata["transform"]) - continue - - if issubclass(field_.type, Module): - for trainable_, bijector_ in zip(*_unpack_meta(field_.type)): - train_meta_.append(trainable_) - bij_meta_.append(bijector_) - continue - - raise ValueError( - f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." - ) - - return train_meta_, bij_meta_ - - if __unpack_meta__: - train_meta_, bij_meta_ = _unpack_meta(obj) - - if __trainables_leaves__ is None: - __trainables_leaves__ = train_meta_ - - if __bijectors_leaves__ is None: - __bijectors_leaves__ = bij_meta_ - - object.__setattr__(obj, "__trainables_leaves__", __trainables_leaves__) - object.__setattr__(obj, "__bijectors_leaves__", __bijectors_leaves__) - + if __meta__ is None: + __meta__ = _unpack_meta(obj) + object.__setattr__(obj, "__meta__", __meta__) return obj - @_cached_static_property # Cacheing is fine here as the trainables are static and `Module` is frozen/inmutable. + @_cached_static_property # Caching fine here since `trainables` are static and `Module` is frozen/inmutable. def trainables(self) -> Module: - """Return the boolean Module comprising trainability statuses. + """Return boolean Module comprising trainability statuses for the Module. Returns: - Module: The boolean Module comprising trainability statuses for the Module. + Module: Boolean Module comprising trainability statuses for the Module. """ - return jtu.tree_structure(self).unflatten(self.__trainables_leaves__) + return jtu.tree_structure(self).unflatten(self.__meta__.trainables) - @_cached_static_property # Cacheing is fine here as the trainables are static and `Module` is frozen/inmutable. + @_cached_static_property # Caching fine here since bijectors are static and `Module` is frozen/inmutable. def bijectors(self) -> Module: """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. Returns: - Module: The Bijector Module of parameter transformations. + Module: The Bijector Module of parameter transformations for the Module. """ - return jtu.tree_structure(self).unflatten(self.__bijectors_leaves__) + return jtu.tree_structure(self).unflatten(self.__meta__.bijectors) def set_trainables(self, tree: Module) -> Module: """Set parameter trainability status for the Module. @@ -248,80 +245,53 @@ def set_trainables(self, tree: Module) -> Module: if not jtu.tree_structure(tree) == jtu.tree_structure(self): raise ValueError("Tree must have the same structure as the Module.") - return self.__set_trainables_leaves__(jtu.tree_leaves(tree)) + return self.__update_meta__( + trainables=jtu.tree_leaves(tree), bijectors=self.__meta__.bijectors + ) def set_bijectors(self, tree: Module) -> Module: """Set parameter transformations for the Module. Args: - tree (Module): The Bijector tree of parameter transformations comprising the same tree structure as the underlying Module. + tree (Module): The bijector tree of parameter transformations comprising the same tree structure as the underlying Module. Returns: Module: A new instance with the updated trainablility status tree. """ - if not isinstance(tree, Module): raise TypeError("tree must be a JaxUtils Module.") - def _is_bij(x): - return isinstance(x, Bijector) - if not jtu.tree_structure( - jtu.tree_map(lambda _: True, tree, is_leaf=_is_bij) + jtu.tree_map( + lambda _: True, tree, is_leaf=lambda x: isinstance(x, Bijector) + ) ) == jtu.tree_structure(self): raise ValueError( "bijectors tree must have the same structure as the Module." ) - return self.__set_bijectors_leaves__(jtu.tree_leaves(tree)) - - def __set_trainables_leaves__(self, __trainables_leaves__: List[bool]) -> Module: - """Set the trainables function for the class.""" - - # Create new class instance, with the adjusted trainable function. - new_instance = self.__class__.__new__( - cls=self.__class__, - __trainables_leaves__=__trainables_leaves__, - __bijectors_leaves__=self.__bijectors_leaves__, - __unpack_meta__=False, + return self.__update_meta__( + trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree) ) - # TODO: Might have to filter attribute dict here? - for field_ in fields(self): - object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) - - return new_instance - - def __set_bijectors_leaves__( - self, __bijectors_leaves__: Callable[[Module], Module] - ) -> Module: - """Set the bijectors function for the class.""" - - # Create new class instance, with the adjusted trainable function. - new_instance = self.__class__.__new__( - self.__class__, - __trainables_leaves__=self.__trainables_leaves__, - __bijectors_leaves__=__bijectors_leaves__, - __unpack_meta__=False, + def __update_meta__(self, trainables, bijectors) -> Module: + """Update Module meta through a new instance.""" + new = self.__class__.__new__( + cls=self.__class__, __meta__=_Meta(trainables, bijectors) ) - # TODO: Might have to filter attribute dict here? for field_ in fields(self): - object.__setattr__(new_instance, field_.name, self.__dict__[field_.name]) + object.__setattr__(new, field_.name, self.__dict__[field_.name]) - return new_instance + return new def tree_flatten(self): - """Same as Equinox, except for the addition of the `static_meta`.""" + """Identical to that of Equinox, except for the addition of the `meta` component.""" dynamic_field_names = [] dynamic_field_values = [] static_field_names = [] static_field_values = [] - - static_meta = [ - self.__trainables_leaves__, - self.__bijectors_leaves__, - ] + meta = [self.__meta__.trainables, self.__meta__.bijectors] for field_ in fields(self): name = field_.name @@ -340,27 +310,18 @@ def tree_flatten(self): tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(static_meta), + tuple(meta), ) @classmethod def tree_unflatten(cls, aux, dynamic_field_values): - """Same as Equinox, except for the addition of the `static_meta`.""" - - dynamic_field_names, static_field_names, static_field_values, static_meta = aux + """Identical to that of Equinox, except for the addition of the `meta` component.""" - # These are the static functions that determine the trainable and bijector PyTree's from self. - __trainables_leaves__, __bijectors_leaves__ = static_meta - - self = cls.__new__( - cls=cls, - __trainables_leaves__=__trainables_leaves__, - __bijectors_leaves__=__bijectors_leaves__, - ) + dynamic_field_names, static_field_names, static_field_values, meta = aux + self = cls.__new__(cls=cls, __meta__=_Meta(*meta)) for name, value in zip(dynamic_field_names, dynamic_field_values): object.__setattr__(self, name, value) - for name, value in zip(static_field_names, static_field_values): object.__setattr__(self, name, value) diff --git a/tests/test_module.py b/tests/test_module.py index e0c4eb0..269d88e 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -81,7 +81,7 @@ class Tree(Module): ): assert bij.inverse(l1) == l2 - _, tree_def = jax.tree_flatten(tree) + _, tree_def = jtu.tree_flatten(tree) trainables = tree_def.unflatten([True, False, True, False, False]) new_tree = tree.set_trainables(trainables) From 580a36ceb28bf97d6ecafc081363685f8896aad7 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 23:37:28 +0000 Subject: [PATCH 42/81] Add minimal verbose scan. Need to generalise and cleanup! --- jaxutils/fit.py | 6 ++- jaxutils/progress_bar.py | 20 ++++----- jaxutils/verbose_scan.py | 96 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 11 deletions(-) create mode 100644 jaxutils/verbose_scan.py diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 10ecc93..b3dbf7b 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -44,6 +44,7 @@ def fit( key: Optional[KeyArray] = jr.PRNGKey(42), log_rate: Optional[int] = 10, verbose: Optional[bool] = True, + unroll: int = 1, ) -> Tuple[Module, Array]: """Train a Module model with respect to a supplied Objective function. Optimisers used here should originate from Optax. @@ -108,6 +109,7 @@ def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: key (Optional[KeyArray]): The random key to use for the optimisation batch selection. Defaults to jr.PRNGKey(42). log_rate (Optional[int]): How frequently the objective function's value should be printed. Defaults to 10. verbose (Optional[bool]): Whether to print the training loading bar. Defaults to True. + unroll (int): The number of unrolled steps to use for the optimisation. Defaults to 1. Returns: Tuple[Module, Array]: A Tuple comprising the optimised model and training history respectively. @@ -162,7 +164,9 @@ def step(carry, iter_num__and__key): step = progress_bar(num_iters, log_rate)(step) # Optimisation loop. - (model, _), history = jax.lax.scan(step, (model, state), (iter_nums, iter_keys)) + (model, _), history = jax.lax.scan( + step, (model, state), (iter_nums, iter_keys), unroll=unroll + ) # Constrained space. model = constrain(model) diff --git a/jaxutils/progress_bar.py b/jaxutils/progress_bar.py index 603cd93..0944ae3 100644 --- a/jaxutils/progress_bar.py +++ b/jaxutils/progress_bar.py @@ -52,10 +52,10 @@ def body_func(carry, x): def _update_tqdm(args: Any, transform: Any) -> None: """Update the tqdm progress bar with the latest objective value.""" - loss_val, arg = args - tqdm_bars[0].set_description(f"Training", refresh=False) - tqdm_bars[0].update(arg) - tqdm_bars[0].set_postfix({"Objective": f"{loss_val: .2f}"}) + value, iter_num = args + tqdm_bars[0].set_description(f"Running", refresh=False) + tqdm_bars[0].update(iter_num) + tqdm_bars[0].set_postfix({"Value": f"{value: .2f}"}) def _close_tqdm(args: Any, transform: Any) -> None: """Close the tqdm progress bar.""" @@ -75,7 +75,7 @@ def _not_callback(_) -> int: _ = lax.cond(cond, _do_callback, _not_callback, operand=None) - def _update_progress_bar(loss_val: Float[Array, "1"], iter_num: int) -> None: + def _update_progress_bar(value: Float[Array, "1"], iter_num: int) -> None: """Update the tqdm progress bar.""" # Conditions for iteration number @@ -86,10 +86,10 @@ def _update_progress_bar(loss_val: Float[Array, "1"], iter_num: int) -> None: is_last: bool = iter_num == num_iters - 1 # Update progress bar, if multiple of log_rate - _callback(is_multiple, _update_tqdm, (loss_val, log_rate)) + _callback(is_multiple, _update_tqdm, (value, log_rate)) # Update progress bar, if remainder - _callback(is_remainder, _update_tqdm, (loss_val, remainder)) + _callback(is_remainder, _update_tqdm, (value, remainder)) # Close progress bar, if last iteration _callback(is_last, _close_tqdm, None) @@ -108,11 +108,11 @@ def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any: # Compute iteration step result = body_fun(carry, x) - # Get loss value - *_, loss_val = result + # Get value + *_, value = result # Update progress bar - _update_progress_bar(loss_val, iter_num) + _update_progress_bar(value, iter_num) return result diff --git a/jaxutils/verbose_scan.py b/jaxutils/verbose_scan.py new file mode 100644 index 0000000..b996a62 --- /dev/null +++ b/jaxutils/verbose_scan.py @@ -0,0 +1,96 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from typing import Callable, List, Optional, Tuple, TypeVar + +Carry = TypeVar("Carry") +X = TypeVar("X") +Y = TypeVar("Y") + +from jaxutils import progress_bar +import jax +import jax.numpy as jnp + +# TODO: Either remove Value printing altogether or make it an optional argument. + + +def verbose_scan( + f: Callable[[Carry, X], Tuple[Carry, Y]], + init: Carry, + xs: X, + length: Optional[int] = None, + reverse: bool = False, + unroll: int = 1, + log_rate: int = 10, +) -> Tuple[Carry, List[Y]]: + """Scan with verbose output. + + !!! example + ```python + import jax.numpy as jnp + import jaxutils as ju + + def f(carry, x): + return carry + x, carry + x + + init = 0 + xs = jnp.arange(10) + carry, ys = ju.verbose_scan(f, init, xs) + print(carry, ys) + + # 45 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] + + # The above is equivalent to: + carry, ys = jax.lax.scan(f, init, xs) + print(carry, ys) + + # 45 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] + ``` + + Args: + f (Callable[[Carry, X], Tuple[Carry, Y]]): A function that takes in a carry and an input and returns a tuple of a new carry and an output. + init (Carry): The initial carry. + xs (X): The inputs. + length (Optional[int]): The length of the inputs. If None, then the length of the inputs is inferred. + reverse (bool): Whether to scan in reverse. + unroll (int): The number of iterations to unroll. + log_rate (int): The rate at which to log the progress bar. + + Returns: + Tuple[Carry, List[Y]]: A tuple of the final carry and the outputs. + """ + + length = len(xs) + + @progress_bar(num_iters=length, log_rate=log_rate) + def body_fun(carry: Carry, iter_num_and_xs: Tuple[int, X]) -> Tuple[Carry, Y]: + iter_num, x = iter_num_and_xs + carry, y = f(carry, x) + return carry, y + + carry, ys = jax.lax.scan( + body_fun, + init, + (jnp.arange(length), xs), + length=length, + reverse=reverse, + unroll=unroll, + ) + return carry, ys + + +__all__ = [ + "verbose_scan", +] From 29d44f67cf84decaeae9fce7988154690ebba5a9 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 12 Feb 2023 23:53:02 +0000 Subject: [PATCH 43/81] Update module.py --- jaxutils/module.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 7952f62..849bf8b 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -27,7 +27,6 @@ from .bijectors import Bijector - """NamedTuple for storing metadata (i.e., trainables and bijectors). """ _Meta = namedtuple("_Meta", ["trainables", "bijectors"]) @@ -86,6 +85,36 @@ class MyModule(jaxutils.Module): return field(**kwargs) +def static(**kwargs: Any): + """Alias of `equinox.static_field`. Provided for convenience. + + Used for marking that a field should _not_ be treated as a leaf of the PyTree + of a `jaxutils.Module`/ `equinox.Module`. (And is instead treated as part of the structure, i.e. + as extra metadata.) + !!! example + ```python + class MyModule(jaxutils.Module): + normal_field: int + static_field: int = equinox.static_field() + mymodule = MyModule("normal", "static") + leaves, treedef = jtu.tree_flatten(mymodule) + assert leaves == ["normal"] + assert "static" in str(treedef) + ``` + Args: + **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. + (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) + """ + try: + metadata = dict(kwargs["metadata"]) + except KeyError: + metadata = kwargs["metadata"] = {} + if "static" in metadata: + raise ValueError("Cannot use metadata with `static` already set.") + metadata["static"] = True + return field(**kwargs) + + def constrain(obj: Module) -> Module: """ Transform model parameters to the constrained space for corresponding @@ -331,6 +360,7 @@ def tree_unflatten(cls, aux, dynamic_field_values): __all__ = [ "Module", "param", + "static", "constrain", "unconstrain", "stop_gradients", From 79dace9549768b6df5eea240c730859b8417d3e3 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 14 Feb 2023 21:36:15 +0000 Subject: [PATCH 44/81] Fix `jaxutils.fit` `__init__.py` import, add documentation to `module.py` --- README.md | 32 ++-- jaxutils/__init__.py | 7 +- jaxutils/fit.py | 82 ++++------ jaxutils/module.py | 357 +++++++++++++++++++++++++++++++++++++------ 4 files changed, 354 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index 441008d..17f9bee 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,19 @@ # Contents - [Overview](#overview) +- [Module] (#) - [Dataset](#dataset) # Overview -## ... +`JaxUtils` is designed.... -## ... ## Linear Model example. We fit a simple one-dimensional linear regression model with a `weight` and a `bias` parameter. -### (1) Ceate a dataset +### (1) Dataset ```python # Import dependancies. @@ -28,7 +28,7 @@ import jaxutils as ju import jax.numpy as jnp import jax.random as jr import optax as ox - +import matplotlib.pyplot as plt # Simulate labels. key = jr.PRNGKey(42) @@ -39,10 +39,9 @@ y = 2.0 * X + 1.0 + jr.normal(key, X.shape) D = ju.Dataset(X, y) ``` -### (2) Define your model +### (2) Model A model is defined through inheriting from the `JaxUtils`'s `Module` object. - ```python class LinearModel(ju.Module): weight: float = ju.param(ju.Identity) @@ -53,38 +52,29 @@ class LinearModel(ju.Module): model = LinearModel(weight=1.0, bias=1.0) ``` - The parameters are marked via the `param` field, whose argument is the default `Bijector` transformation for mapping the parameters to the unconstrained space for optimisation. In this case both of our `weight` and `bias` parameters are defined on the reals, so we use the `Identity` transform. Just like in typicall `Equinox` code, we can (optionally) define a foward pass of the model through the `__call__` method. +### (3) Objective - -### (3) Define your objective - -We can define any objective function, such as the mean-square-error, via inheriting from the `Objective` object as follows. - +We can define any objective function, such as the mean squared error, via inheriting from the `Objective` object as follows. ```python -class MeanSqaureError(ju.Objective): +class MeanSquaredError(ju.Objective): def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: - return jnp.sum((train_data.y - model(train_data.X)) ** 2) + return jnp.mean((train_data.y - model(train_data.X)) ** 2) -loss = MeanSqaureError() +loss = MeanSquaredError() ``` ### (4) Train! We are now ready to train our model. This can simply be done using the `fit` callable. - ```python # Optimisation loop. -model, hist = ju.fit(model, loss, D, ox.sgd(0.0001), 10000) - -# Print parameter values. -print(model.weight, model.bias) +model, hist = ju.fit(model=model, objective=loss, train_data=D, optim=optim, num_iters=1000) ``` - # Dataset ## Overview diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index 81341fd..cd3b268 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,11 +13,11 @@ # limitations under the License. # ============================================================================== -from .module import Module, constrain, param, unconstrain +from .module import Module, constrain, param, unconstrain, stop_gradients from .bijectors import Bijector, Identity, Softplus from .objective import Objective from .dataset import Dataset -from .fit import get_batch +from .fit import fit, get_batch from .progress_bar import progress_bar @@ -41,7 +41,8 @@ "param", "constrain", "unconstrain", - "stop_gradients" "fit", + "stop_gradients", + "fit", "get_batch", "progress_bar", ] diff --git a/jaxutils/fit.py b/jaxutils/fit.py index b3dbf7b..9c61821 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -48,56 +48,38 @@ def fit( ) -> Tuple[Module, Array]: """Train a Module model with respect to a supplied Objective function. Optimisers used here should originate from Optax. - !!! example - ```python - import jax.numpy as jnp - import jaxutils as ju - import optax as ox - - # (1) Create a dataset: - X = jnp.linspace(0.0, 10.0, 100).reshape(-1, 1) - y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape).reshape(-1, 1) - D = ju.Dataset(X, y) - - # (2) Define your model: - class LinearModel(ju.Module): - weight: float = ju.param(transform=ju.Identity, trainable=True) - bias: float = ju.param(transform=ju.Identity, trainable=True) - - def __call__(self, x): - return self.weight * x + self.bias - - model = LinearModel(weight=1.0, bias=1.0) - - # (3) Define your loss function: - class MeanSqaureError(Objective): - def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: - y_pred = model(train_data.X) - return jnp.mean((y_pred - train_data.y) ** 2) - - loss = MeanSqaureError() - - # (4) Define your optimiser: - optim = ox.adam(1e-3) - - # (5) Train your model: - model, history = ju.fit(model=model, objective=loss, train_data=D, optim=optim, num_iters=1000) - - # (6) Plot the training history: - import matplotlib.pyplot as plt - plt.plot(history) - plt.show() - - # (7) Plot the model predictions: - X_test = jnp.linspace(0.0, 10.0, 1000).reshape(-1, 1) - y_test = model(X_test) - plt.plot(X_test, y_test) - plt.scatter(D.X, D.y) - plt.show() - - # (8) Print the final model parameters: - print(model) - ``` + Example: + >>> import jax.numpy as jnp + >>> import jax.random as jr + >>> import optax as ox + >>> import jaxutils as ju + >>> + >>> # (1) Create a dataset: + >>> X = jnp.linspace(0.0, 10.0, 100)[:, None] + >>> y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape) + >>> D = ju.Dataset(X, y) + >>> + >>> # (2) Define your model: + >>> class LinearModel(ju.Module): + ... weight: float = ju.param(ju.Identity) + ... bias: float = ju.param(ju.Identity) + ... + ... def __call__(self, x): + ... return self.weight * x + self.bias + ... + >>> model = LinearModel(weight=1.0, bias=1.0) + >>> + >>> # (3) Define your loss function: + >>> class MeanSqaureError(ju.Objective): + ... def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: + ... return jnp.mean((train_data.y - model(train_data.X)) ** 2) + ... + >>> loss = MeanSqaureError() + >>> + >>> # (4) Train! + >>> trained_model, history = ju.fit( + ... model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=1000 + ... ) Args: model (Module): The model Module to be optimised. diff --git a/jaxutils/module.py b/jaxutils/module.py index 849bf8b..512984d 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,31 +20,90 @@ from jax import lax from dataclasses import fields, field -from typing import Any, Callable, NamedTuple +from typing import Any, Callable, NamedTuple, Tuple from collections import namedtuple import equinox as eqx from .bijectors import Bijector -"""NamedTuple for storing metadata (i.e., trainables and bijectors). """ +"""NamedTuple for storing transformations and trainability status metadata of `jaxutils.Module` PyTree leaves. + +Args: + trainables (Tuple[bool]): Whether the PyTree leaf is trainable. + bijectors (Tuple[Bijector]): The bijector that should be applied to the PyTree leaf. + +Example: + This example shows us creating a module with two parameters, and accessing the metadata of the module. + This is part of the non-public API, and is not intended to be used directly by users. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> # Create a bijector for demonstration purposes. + >>> class Test(ju.Bijector): + >>> def __init__(self): + >>> self.forward = jnp.tanh + >>> self.inverse = jnp.arctanh + >>> + >>> # Create a module with two parameters. + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(Test()) + >>> param_b: float = ju.param(Test()) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + >>> + >>> module = MyModule(param_a=1.0, param_b=1.0) + >>> + >>> # The `__meta__` attribute is a `_Meta` object. + >>> print(module.__meta__) + _Meta(trainables=(True, True), bijectors=(Test(forward=>, inverse=>), Test(forward=>, inverse=>))) + +""" _Meta = namedtuple("_Meta", ["trainables", "bijectors"]) class _cached_static_property: """Decorator to cache result of static immutable properties of a PyTree. - Courtesy of Kernex library. + Example: - !!! note - The decorated property must *NOT* contain any dynamic attributes / PyTree leaves. + This example shows us caching the result of sqauring a static float attribute of a Module. + + >>> import jaxutils as ju + >>> + >>> class MyModule(ju.Module): + >>> static_attribute: float = ju.static() + + >>> @_cached_static_property + >>> def static_property(self): + >>> return self.static_attribute ** 2 + + Note: + The decorated property must *NOT* contain any dynamic attributes / PyTree leaves, + i.e., any attributes referenced in the property must be marked as static. + + For example, the following will break durin tracing since `self.dynamic_attribute` is not static: + + >>> import jaxutils as ju + >>> + >>> class MyModule(ju.Module): + >>> static_attribute: float = ju.static() + >>> dynamic_attribute: float = ju.param(ju.Identity) + >>> + >>> @_cached_static_property + >>> def static_property(self): + >>> return self.static_attribute ** 2 + self.dynamic_attribute """ def __init__(self, static_property: Callable): + """Here we store the name of the property and the function itself.""" self.name = static_property.__name__ self.func = static_property def __get__(self, instance, owner): + """Here we cache the result of the property function, by overwriting the attribute with the result.""" attr = self.func(instance) object.__setattr__(instance, self.name, attr) return attr @@ -53,20 +112,56 @@ def __get__(self, instance, owner): def param(transform: Bijector, trainable: bool = True, **kwargs: Any): """Used for marking default parameter transformations. - !!! example + All PyTree leaves of the `jaxutils.Module` must be marked by this function, `jaxutils.static`, or must be of type `jaxutils.Module`. + + Example: + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + >>> + >>> module = MyModule(param_a=1.0, param_b=1.0) + + We can access the trainability status of the parameters using the `trainables` property. - ```python - class MyModule(jaxutils.Module): - param_a: float = jaxutils.param(jaxutils.Identity) - param_b: float = jaxutils.param(jaxutils.Softplus) - ``` + >>> # Print the trainability status PyTree + >>> print(module.trainables) + LinearModel(weight=True, bias=True) - All PyTree leaves of the Module must be marked. + And we can access the bijectors of the parameters using the `bijectors` property. + + >>> # Print the bijectors of the PyTree + >>> print(module.bijectors) + LinearModel( + weight=Bijector(forward=>, inverse=>), + bias=Bijector(forward=>, inverse=>) + ) + + Under the hood, the `param` function is used to create a `dataclasses.field` object with the `transform` and `trainable` metadata set, + which is then used to initialise the non-public and static `Module.__meta__` attribute. + + >>> # Print the trainability status leaves from the `__meta__` attribute. + >>> print(module.__meta__.trainables) + (True, False) + >>> + >>> # Print the bijectors of the leaves from the `__meta__` attribute. + >>> print(module.__meta__.bijectors) + (Identity(forward=>, inverse=>), Softplus(forward=>, inverse=>)) Args: transform (Bijector): The default bijector that should be should upon Module initialisation. **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) + + Returns: + A `dataclasses.field` object with the `transform` and `trainable` metadata set. """ try: metadata = dict(kwargs["metadata"]) @@ -91,18 +186,39 @@ def static(**kwargs: Any): Used for marking that a field should _not_ be treated as a leaf of the PyTree of a `jaxutils.Module`/ `equinox.Module`. (And is instead treated as part of the structure, i.e. as extra metadata.) - !!! example - ```python - class MyModule(jaxutils.Module): - normal_field: int - static_field: int = equinox.static_field() - mymodule = MyModule("normal", "static") - leaves, treedef = jtu.tree_flatten(mymodule) - assert leaves == ["normal"] - assert "static" in str(treedef) - ``` + + Example: + This example shows us creating a module with a static field, and then flattening the module. + + >>> import jaxutils as ju + >>> + >>> class MyModule(ju.Module): + >>> normal_field: int + >>> static_field: int = ju.static() + >>> + >>> mymodule = MyModule("normal", "static") + >>> leaves, treedef = jax.tree_flatten(mymodule) + >>> print(leaves) + ['normal'] + >>> print(treedef) + PyTreeDef(, {'static_field': *}) + >>> + >>> # The same example using `equinox.static_field` + >>> import equinox as eq + >>> + >>> class MyModule(ju.Module): + >>> normal_field: int + >>> static_field: int = eq.static_field() + >>> + >>> mymodule = MyModule("normal", "static") + >>> leaves, treedef = jax.tree_flatten(mymodule) + >>> print(leaves) + ['normal'] + >>> print(treedef) + PyTreeDef(, {'static_field': *}) + Args: - **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. + **kwargs (Any): If any are passed then they are passed on to `dataclass.field`. (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) """ try: @@ -116,9 +232,34 @@ class MyModule(jaxutils.Module): def constrain(obj: Module) -> Module: - """ - Transform model parameters to the constrained space for corresponding - bijectors. + """Transform model parameters to the constrained space according to their defined bijectors. + + Example: + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + >>> + >>> module = MyModule(param_a=1.0, param_b=1.0) + + We can constrain the parameters using the `constrain` function. + + >>> constrained_module = ju.constrain(module) + >>> print(constrained_module) + MyModule(param_a=1.0, param_b=0.0) + + And we can unconstrain the parameters using the `unconstrain` function. + + >>> unconstrained_module = ju.unconstrain(constrained_module) + >>> print(unconstrained_module) + MyModule(param_a=1.0, param_b=1.0) Args: obj (Module): The PyTree object whoose leaves are to be transformed. @@ -132,9 +273,34 @@ def constrain(obj: Module) -> Module: def unconstrain(obj: Module) -> Module: - """ - Transform model parameters to the unconstrained space for corresponding - bijectors. + """Transform model parameters to the unconstrained space according to their defined bijectors. + + Example: + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + >>> + >>> module = MyModule(param_a=1.0, param_b=1.0) + + We can constrain the parameters using the `constrain` function. + + >>> constrained_module = ju.constrain(module) + >>> print(constrained_module) + MyModule(param_a=1.0, param_b=0.0) + + And we can unconstrain the parameters using the `unconstrain` function. + + >>> unconstrained_module = ju.unconstrain(constrained_module) + >>> print(unconstrained_module) + MyModule(param_a=1.0, param_b=1.0) Args: obj (Module): The PyTree object whoose leaves are to be transformed. @@ -150,7 +316,33 @@ def unconstrain(obj: Module) -> Module: def stop_gradients(obj: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is - False. + False. This is useful for stopping parameters from being updated during training. + + Example: + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + + We now create a dummy objective function and check the gradients of the parameters. + + >>> module = MyModule(param_a=5.0, param_b=7.0) + >>> def dummy_objective(module, x): + ... module = ju.stop_gradients(module) # Stop gradients flowing through `param_b` + ... return jnp.sum(module(x)) + >>> g = jax.grad(dummy_objective)(module, 1.0) + + We can see that the gradient of `param_a` is 1.0, but the gradient of `param_b` is 0.0, as expected. + + >>> print(g.param_a, g.param_b) + 1.0 0.0 Args: obj (Module): PyTree object to stop gradients for. @@ -160,13 +352,41 @@ def stop_gradients(obj: Module) -> Module: """ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: + """Stop gradients flowing through a given leaf if it is not trainable.""" return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) def _unpack_meta(obj: Module) -> NamedTuple: - """Unpack metadata (i.e., trainables and bijectors) defined by the `param` field. + """Unpack trainable and tranformation metadata defined by the `jaxutils.param` field of a `jaxutils.Module`. + + This is used to build the leaves of the `trainables` and `bijectors` attributes defined in the `__meta__` attribute of a `jaxutils.Module`, during class instantiation. + + Example: + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + >>> + >>> module = MyModule(param_a=1.0, param_b=1.0) + + We unpack the metadata from the `param` fields using the `_unpack_meta` function. + + >>> meta_named_tuple = _unpack_meta(module) + >>> print(meta_named_tuple) + _Meta(trainables=(True, False), bijectors=(Bijector(forward=>, inverse=>), Bijector(forward=>, inverse=>))) + + We can see this is equivalent to the `__meta__` attribute of the module. + >>> assert meta_named_tuple == module.__meta__ + True Args: obj (Module): The PyTree object whoose leaves are to be transformed. @@ -199,7 +419,7 @@ def _unpack_meta(obj: Module) -> NamedTuple: f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." ) - return _Meta(trainables, bijectors) + return _Meta(tuple(trainables), tuple(bijectors)) class Module(eqx.Module): @@ -208,14 +428,24 @@ class Module(eqx.Module): This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), with modifications to handle bijector transformations and trainability statuses. - !!! example - ```python - class MyModule(jaxutils.Module): - param_a: float = jaxutils.param(jaxutils.Identity) - param_b: float = jaxutils.param(jaxutils.Softplus) - ``` + Example: + + TODO: More thorough example. - All PyTree leaves of the Module must be marked with the `param` field. + This example shows us creating a module with two parameters, with differing transformations and trainability statuses. + + >>> import jaxutils as ju + >>> import jax.numpy as jnp + >>> + >>> class MyModule(ju.Module): + >>> param_a: float = ju.param(ju.Identity, trainable=True) + >>> param_b: float = ju.param(ju.Softplus, trainable=False) + >>> + >>> def __call__(self, x): + >>> return self.param_a * x + self.param_b + + Note: + All attributes of the Module must be marked with either a `param` or `static` field or the attributes type needs to be subclass of `jaxutils.Module`. """ def __new__( @@ -227,12 +457,12 @@ def __new__( """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). Args: - __meta__ (_Meta.) Metadata that define the models' trainables and bijectors PyTree leaves. - *args (Any). Arguments. - **kwargs (Any). Keyword arguments. + __meta__ (_Meta): Metadata that defines the Module's trainables and bijectors PyTree leaves. + *args (Any): Arguments. + **kwargs (Any): Keyword arguments. Returns: - Module. An instance of the JaxUtils Module class. + Module. An instance of the `jaxutils.Module`. """ obj = super().__new__(cls) if __meta__ is None: @@ -261,6 +491,9 @@ def bijectors(self) -> Module: def set_trainables(self, tree: Module) -> Module: """Set parameter trainability status for the Module. + Example: + TODO! + Args: tree (Module): The boolean tree of trainability status comprising the same tree structure as the underlying Module. @@ -281,6 +514,9 @@ def set_trainables(self, tree: Module) -> Module: def set_bijectors(self, tree: Module) -> Module: """Set parameter transformations for the Module. + Example: + TODO! + Args: tree (Module): The bijector tree of parameter transformations comprising the same tree structure as the underlying Module. @@ -303,8 +539,19 @@ def set_bijectors(self, tree: Module) -> Module: trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree) ) - def __update_meta__(self, trainables, bijectors) -> Module: - """Update Module meta through a new instance.""" + def __update_meta__(self, trainables: Tuple, bijectors: Tuple) -> Module: + """Update Module meta through a new instance. + + Example: + TODO! + + Args: + trainables (Tuple): The new leaves of the trainables PyTree. + bijectors (Tuple): The new leaves of the bijectors PyTree. + + Returns: + Module: A new instance of the Module with updated meta. + """ new = self.__class__.__new__( cls=self.__class__, __meta__=_Meta(trainables, bijectors) ) @@ -314,8 +561,12 @@ def __update_meta__(self, trainables, bijectors) -> Module: return new - def tree_flatten(self): - """Identical to that of Equinox, except for the addition of the `meta` component.""" + def tree_flatten(self) -> Tuple[Tuple, Tuple]: + """Identical to that of Equinox, except for the addition of a meta component. + + Returns: + Tuple: A tuple of the Module's dynamic and static fields. + """ dynamic_field_names = [] dynamic_field_values = [] static_field_names = [] @@ -343,9 +594,16 @@ def tree_flatten(self): ) @classmethod - def tree_unflatten(cls, aux, dynamic_field_values): - """Identical to that of Equinox, except for the addition of the `meta` component.""" + def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: + """Identical to that of Equinox, except for the addition of a meta component. + + Args: + aux (Tuple): Auxiliary data. + dynamic_field_values (Tuple): Dynamic field values. + Returns: + Module: An instance of the `jaxutils.Module` class. + """ dynamic_field_names, static_field_names, static_field_values, meta = aux self = cls.__new__(cls=cls, __meta__=_Meta(*meta)) @@ -353,7 +611,6 @@ def tree_unflatten(cls, aux, dynamic_field_values): object.__setattr__(self, name, value) for name, value in zip(static_field_names, static_field_values): object.__setattr__(self, name, value) - return self From c2cf3c2f9832b70aecc4f90a07876923b98b0f0f Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Fri, 17 Feb 2023 01:51:05 +0000 Subject: [PATCH 45/81] Bugfix. --- jaxutils/module.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 512984d..5bcb9c0 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -450,8 +450,8 @@ class Module(eqx.Module): def __new__( cls, - __meta__: _Meta = None, *args: Any, + __meta__: _Meta = None, **kwargs: Any, ) -> Module: """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). From fcdd52e2dbeab6ecbb320af86d4b09092f15d13e Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 19 Feb 2023 06:26:56 +0000 Subject: [PATCH 46/81] Update. --- README.md | 10 +- jaxutils/__init__.py | 7 +- jaxutils/_pytree.py | 91 ++++++++++++++++ jaxutils/fit.py | 18 ++-- jaxutils/scan.py | 161 ++++++++++++++++++++++++++++ jaxutils/verbose_scan.py | 96 ----------------- tests/test_module.py | 226 +++++++++++++++++++++++++++++++++++++++ tests/test_vscan.py | 30 ++++++ 8 files changed, 526 insertions(+), 113 deletions(-) create mode 100644 jaxutils/_pytree.py create mode 100644 jaxutils/scan.py delete mode 100644 jaxutils/verbose_scan.py create mode 100644 tests/test_vscan.py diff --git a/README.md b/README.md index 17f9bee..d22e170 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,17 @@ # Contents - [Overview](#overview) -- [Module] (#) +- [Module] (#module) +- [Objective] (#objective) +- [Vscan] (#vscan) +- [Fit] (#fit) +- [Bijectors](#bijectors) - [Dataset](#dataset) # Overview +## Linear Model example. + `JaxUtils` is designed.... @@ -79,7 +85,7 @@ model, hist = ju.fit(model=model, objective=loss, train_data=D, optim=optim, num ## Overview -`jaxutils.Dataset` is a datset abstraction. In future, we wish to extend this to a heterotopic and isotopic data abstraction. +`jaxutils.Dataset` is a dataset abstraction. ## Example diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index cd3b268..2f643da 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,12 +13,12 @@ # limitations under the License. # ============================================================================== -from .module import Module, constrain, param, unconstrain, stop_gradients +from .module import Module, constrain, param, static, unconstrain, stop_gradients from .bijectors import Bijector, Identity, Softplus from .objective import Objective from .dataset import Dataset from .fit import fit, get_batch -from .progress_bar import progress_bar +from .scan import vscan __authors__ = "Thomas Pinder, Daniel Dodd" @@ -39,12 +39,13 @@ "Dataset", "Module", "param", + "static", "constrain", "unconstrain", "stop_gradients", "fit", "get_batch", - "progress_bar", + "vscan", ] from . import _version diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py new file mode 100644 index 0000000..65b9974 --- /dev/null +++ b/jaxutils/_pytree.py @@ -0,0 +1,91 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" + +from __future__ import annotations +from typing import Any, Sequence, Callable, Union +from jaxtyping import PyTree +from equinox import tree_at + + +class _PyTreeUpdateRef: + + __slots__ = ("pytree", "where") + + def __init__(self, pytree: PyTree, where: Union[Callable, Sequence[str]]) -> None: + self.pytree = pytree + self.where = where + + def __repr__(self) -> str: + return f"_IndexUpdateRef({repr(self.pytree)}, {repr(self.where)})" + + def get(self) -> PyTree: + return self.where(self.pytree) + + def set(self, values: Any) -> PyTree: + return tree_at(where=self.where, pytree=self.pytree, replace=values) + + def apply(self, func: Callable) -> PyTree: + return tree_at(where=self.where, pytree=self.pytree, replace_fn=func) + + # def add(self, values): + # ... + + # def multiply(self, values): + # ... + + # def divide(self, values): + # ... + + # def power(self, values): + # ... + + # def min(self, values): + # ... + + # def max(self, values): + # ... + + +class _PyTreeUpdateHelper: + """Helper class for updating a PyTree.""" + + __slots__ = ("pytree",) + + def __init__(self, pytree: PyTree): + self.pytree = pytree + + def __getitem__(self, where: Union[Callable, Sequence[str], Ellipsis]): + + if isinstance(where, list) | isinstance(where, str): + + def _to_path(lst: list): + return "".join( + [ + str(elem) if not isinstance(elem, str) else "." + elem + for elem in lst + ] + ) + + where = eval("lambda x: x" + _to_path(where)) + + if isinstance(where, type(Ellipsis)): + where = lambda x: x + + return _PyTreeUpdateRef(self.pytree, where) + + def __repr__(self): + return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 9c61821..56dd786 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -16,7 +16,6 @@ from typing import Optional, Tuple import jax -import jax.numpy as jnp import jax.random as jr import optax as ox @@ -30,7 +29,7 @@ from .dataset import Dataset from .bijectors import Bijector from .objective import Objective -from .progress_bar import progress_bar +from .scan import vscan def fit( @@ -120,13 +119,11 @@ def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: # Initialise optimiser state. state = optim.init(model) - # Mini-batch random keys and iteration loop numbers to scan over. + # Mini-batch random keys to scan over. iter_keys = jr.split(key, num_iters) - iter_nums = jnp.arange(num_iters) # Optimisation step. - def step(carry, iter_num__and__key): - _, key = iter_num__and__key + def step(carry, key): model, opt_state = carry if batch_size != -1: @@ -141,14 +138,11 @@ def step(carry, iter_num__and__key): carry = model, opt_state return carry, loss_val - # Progress bar, if verbose True. - if verbose: - step = progress_bar(num_iters, log_rate)(step) + # Optimisation scan. + scan = vscan if verbose else jax.lax.scan # Optimisation loop. - (model, _), history = jax.lax.scan( - step, (model, state), (iter_nums, iter_keys), unroll=unroll - ) + (model, _), history = scan(step, (model, state), (iter_keys), unroll=unroll) # Constrained space. model = constrain(model) diff --git a/jaxutils/scan.py b/jaxutils/scan.py new file mode 100644 index 0000000..f55e32d --- /dev/null +++ b/jaxutils/scan.py @@ -0,0 +1,161 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from typing import Callable, List, Optional, Tuple, TypeVar, Any +from jax import lax +from jax.experimental import host_callback as hcb +from tqdm.auto import trange + +import jax.tree_util as jtu + +Carry = TypeVar("Carry") +X = TypeVar("X") +Y = TypeVar("Y") + +import jax +import jax.numpy as jnp + + +def _callback(cond: bool, func: Callable, *args: Any) -> None: + """Callback a function for a given argument if a condition is true. + + Args: + cond (bool): The condition. + func (Callable): The function to call. + *args (Any): The arguments to pass to the function. + """ + + # lax.cond requires a result, so we use a dummy result. + _dummy_result = 0 + + def _do_callback(_) -> int: + """Perform the callback.""" + return hcb.id_tap(func, *args, result=_dummy_result) + + def _not_callback(_) -> int: + """Do nothing.""" + return _dummy_result + + _ = lax.cond(cond, _do_callback, _not_callback, operand=None) + + +def vscan( + f: Callable[[Carry, X], Tuple[Carry, Y]], + init: Carry, + xs: X, + length: Optional[int] = None, + reverse: Optional[bool] = False, + unroll: Optional[int] = 1, + log_rate: Optional[int] = 10, + log_value: Optional[bool] = True, +) -> Tuple[Carry, List[Y]]: + """Scan with verbose output. + + This is based on code from the excellent blog post: + https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/. + + Example: + >>> def f(carry, x): + ... return carry + x, carry + x + >>> init = 0 + >>> xs = jnp.arange(10) + >>> vscan(f, init, xs) + (45, DeviceArray([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45], dtype=int32)) + + Args: + f (Callable[[Carry, X], Tuple[Carry, Y]]): A function that takes in a carry and an input and returns a tuple of a new carry and an output. + init (Carry): The initial carry. + xs (X): The inputs. + length (Optional[int]): The length of the inputs. If None, then the length of the inputs is inferred. + reverse (bool): Whether to scan in reverse. + unroll (int): The number of iterations to unroll. + log_rate (int): The rate at which to log the progress bar. + log_value (bool): Whether to log the value of the objective function. + + Returns: + Tuple[Carry, List[Y]]: A tuple of the final carry and the outputs. + """ + + # TODO: Scope out lower level API for jax.lax.scan, to avoid the need for finding the length of the inputs / check inputs. + # TODO: Scope out lower level API for tqdm, for more control over the progress bar. Need to check this. + _xs_flat = jtu.tree_leaves(xs) + _length = length if length is not None else len(_xs_flat[0]) + _iter_nums = jnp.arange(_length) + _remainder = _length % log_rate + + _progress_bar = trange(_length) + _progress_bar.set_description("Compiling...", refresh=True) + + def _set_running(args: Any, transform: Any) -> None: + """Set the tqdm progress bar to running.""" + _progress_bar.set_description("Running", refresh=False) + + def _update_tqdm(args: Any, transform: Any) -> None: + """Update the tqdm progress bar with the latest objective value.""" + _value, _iter_num = args + _progress_bar.update(_iter_num) + + if log_value and _value is not None: + _progress_bar.set_postfix({"Value": f"{_value: .2f}"}) + + def _close_tqdm(args: Any, transform: Any) -> None: + """Close the tqdm progress bar.""" + _progress_bar.close() + + def _body_fun(carry: Carry, iter_num_and_x: Tuple[int, X]) -> Tuple[Carry, Y]: + + # Unpack iter_num and x. + iter_num, x = iter_num_and_x + + # Compute body function. + carry, y = f(carry, x) + + # Conditions for iteration number. + _is_first: bool = iter_num == 0 + _is_multiple: bool = (iter_num % log_rate == 0) & ( + iter_num != _length - _remainder + ) + _is_remainder: bool = iter_num == _length - _remainder + _is_last: bool = iter_num == _length - 1 + + # Update progress bar, if first of log_rate. + _callback(_is_first, _set_running, (y, log_rate)) + + # Update progress bar, if multiple of log_rate. + _callback(_is_multiple, _update_tqdm, (y, log_rate)) + + # Update progress bar, if remainder. + _callback(_is_remainder, _update_tqdm, (y, _remainder)) + + # Close progress bar, if last iteration. + _callback(_is_last, _close_tqdm, (y, None)) + + return carry, y + + carry, ys = jax.lax.scan( + _body_fun, + init, + (_iter_nums, xs), + length=length, + reverse=reverse, + unroll=unroll, + ) + + return carry, ys + + +__all__ = [ + "vscan", +] diff --git a/jaxutils/verbose_scan.py b/jaxutils/verbose_scan.py deleted file mode 100644 index b996a62..0000000 --- a/jaxutils/verbose_scan.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from typing import Callable, List, Optional, Tuple, TypeVar - -Carry = TypeVar("Carry") -X = TypeVar("X") -Y = TypeVar("Y") - -from jaxutils import progress_bar -import jax -import jax.numpy as jnp - -# TODO: Either remove Value printing altogether or make it an optional argument. - - -def verbose_scan( - f: Callable[[Carry, X], Tuple[Carry, Y]], - init: Carry, - xs: X, - length: Optional[int] = None, - reverse: bool = False, - unroll: int = 1, - log_rate: int = 10, -) -> Tuple[Carry, List[Y]]: - """Scan with verbose output. - - !!! example - ```python - import jax.numpy as jnp - import jaxutils as ju - - def f(carry, x): - return carry + x, carry + x - - init = 0 - xs = jnp.arange(10) - carry, ys = ju.verbose_scan(f, init, xs) - print(carry, ys) - - # 45 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] - - # The above is equivalent to: - carry, ys = jax.lax.scan(f, init, xs) - print(carry, ys) - - # 45 [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] - ``` - - Args: - f (Callable[[Carry, X], Tuple[Carry, Y]]): A function that takes in a carry and an input and returns a tuple of a new carry and an output. - init (Carry): The initial carry. - xs (X): The inputs. - length (Optional[int]): The length of the inputs. If None, then the length of the inputs is inferred. - reverse (bool): Whether to scan in reverse. - unroll (int): The number of iterations to unroll. - log_rate (int): The rate at which to log the progress bar. - - Returns: - Tuple[Carry, List[Y]]: A tuple of the final carry and the outputs. - """ - - length = len(xs) - - @progress_bar(num_iters=length, log_rate=log_rate) - def body_fun(carry: Carry, iter_num_and_xs: Tuple[int, X]) -> Tuple[Carry, Y]: - iter_num, x = iter_num_and_xs - carry, y = f(carry, x) - return carry, y - - carry, ys = jax.lax.scan( - body_fun, - init, - (jnp.arange(length), xs), - length=length, - reverse=reverse, - unroll=unroll, - ) - return carry, ys - - -__all__ = [ - "verbose_scan", -] diff --git a/tests/test_module.py b/tests/test_module.py index 269d88e..d566822 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -19,6 +19,12 @@ import jax.tree_util as jtu import jax +from typing import Any + +import jax.tree_util as jtu +import pytest +import equinox as eqx + def test_module(): @@ -39,6 +45,13 @@ class Tree(Module): param_b=5.0, ) + assert isinstance(tree, Module) + assert isinstance(tree.trainables, Module) + assert isinstance(tree.bijectors, Module) + assert isinstance(tree, eqx.Module) + assert isinstance(tree.trainables, eqx.Module) + assert isinstance(tree.bijectors, eqx.Module) + assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 assert tree.sub_tree.param_d == 3.0 @@ -104,3 +117,216 @@ def loss(tree): assert g.sub_tree.param_d == 6.0 assert g.sub_tree.param_e == 0.0 assert g.param_b == 0.0 + + +def test_module_incorrect_typing(): + class NotAModule: + pass + + class SubTree(Module): + param_c: float = param(Identity) + param_d: float = param(Softplus) + param_e: float = param(Softplus) + + class Tree(Module): + param_a: float = param(Identity) + sub_tree: NotAModule + param_b: float = param(Softplus) + + with pytest.raises(ValueError): + Tree( + param_a=1.0, + sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), + param_b=5.0, + ) + + +def test_module_unmarked_param(): + class SubTree(Module): + param_c: float + param_d: float = param(Softplus) + param_e: float = param(Softplus) + + class Tree(Module): + param_a: float = param(Identity) + sub_tree: SubTree + param_b: float = param(Softplus) + + with pytest.raises(ValueError): + Tree( + param_a=1.0, + sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), + param_b=5.0, + ) + + +def test_module_not_enough_attributes(): + class MyModule1(Module): + weight: Any = param(Identity) + + with pytest.raises(TypeError): + MyModule1() + + class MyModule2(Module): + weight: Any = param(Identity) + + def __init__(self): + pass + + with pytest.raises(ValueError): + MyModule2() + with pytest.raises(TypeError): + MyModule2(1) + + +def test_module_too_many_attributes(): + class MyModule1(Module): + weight: Any = param(Identity) + + with pytest.raises(TypeError): + MyModule1(1, 2) + + class MyModule2(Module): + weight: Any = param(Identity) + + def __init__(self, weight): + self.weight = weight + self.something_else = True + + with pytest.raises(AttributeError): + MyModule2(1) + + +def test_module_setattr_after_init(): + class MyModule(Module): + weight: Any = param(Identity) + + m = MyModule(1) + with pytest.raises(AttributeError): + m.asdf = True + + +def test_wrong_attribute(): + class MyModule(Module): + weight: Any = param(Identity) + + def __init__(self, value): + self.not_weight = value + + with pytest.raises(AttributeError): + MyModule(1) + + +# The main part of this test is to check that __init__ works correctly. +def test_inheritance(): + # no custom init / no custom init + + class MyModule(Module): + weight: Any = param(Identity) + + class MyModule2(MyModule): + weight2: Any = param(Identity) + + m = MyModule2(1, 2) + assert m.weight == 1 + assert m.weight2 == 2 + m = MyModule2(1, weight2=2) + assert m.weight == 1 + assert m.weight2 == 2 + m = MyModule2(weight=1, weight2=2) + assert m.weight == 1 + assert m.weight2 == 2 + with pytest.raises(TypeError): + m = MyModule2(2, weight=2) + + # not custom init / custom init + + class MyModule3(MyModule): + weight3: Any = param(Identity) + + def __init__(self, *, weight3, **kwargs): + self.weight3 = weight3 + super().__init__(**kwargs) + + m = MyModule3(weight=1, weight3=3) + assert m.weight == 1 + assert m.weight3 == 3 + + # custom init / no custom init + + class MyModule4(Module): + weight4: Any = param(Identity) + + def __init__(self, value4, **kwargs): + self.weight4 = value4 + super().__init__(**kwargs) + + class MyModule5(MyModule4): + weight5: Any = param(Identity) + + with pytest.raises(TypeError): + m = MyModule5(value4=1, weight5=2) + + class MyModule6(MyModule4): + pass + + m = MyModule6(value4=1) + assert m.weight4 == 1 + + # custom init / custom init + + class MyModule7(MyModule4): + weight7: Any = param(Identity) + + def __init__(self, value7, **kwargs): + self.weight7 = value7 + super().__init__(**kwargs) + + m = MyModule7(value4=1, value7=2) + assert m.weight4 == 1 + assert m.weight7 == 2 + + +def test_static_field(): + class MyModule(Module): + field1: int = param(Identity) + field2: int = eqx.static_field() + field3: int = eqx.static_field(default=3) + + m = MyModule(1, 2) + flat, treedef = jtu.tree_flatten(m) + assert len(flat) == 1 + assert flat[0] == 1 + rm = jtu.tree_unflatten(treedef, flat) + assert rm.field1 == 1 + assert rm.field2 == 2 + assert rm.field3 == 3 + + +def test_wrap_method(): + class MyModule(Module): + a: int = param(Identity) + + def f(self, b): + return self.a + b + + m = MyModule(13) + assert isinstance(m.f, jtu.Partial) + flat, treedef = jtu.tree_flatten(m.f) + assert len(flat) == 1 + assert flat[0] == 13 + assert jtu.tree_unflatten(treedef, flat)(2) == 15 + + +def test_init_subclass(): + ran = [] + + class MyModule(Module): + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + ran.append(True) + + class AnotherModule(MyModule): + pass + + assert ran == [True] diff --git a/tests/test_vscan.py b/tests/test_vscan.py new file mode 100644 index 0000000..cf1a9a2 --- /dev/null +++ b/tests/test_vscan.py @@ -0,0 +1,30 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from jaxutils.scan import vscan + +import jax.numpy as jnp + +# TODO: Thorough checks on vscan. +def test_vscan(): + def body(c, x): + a, b = x + return c, a + b + + xs = (jnp.arange(10), jnp.arange(10)) + c, ys = vscan(body, 0, xs) + + assert c == 0 + assert jnp.all(ys == jnp.arange(10) * 2) From 69719428276792d8f7fe59b600f3f15e446f13af Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 19 Feb 2023 06:29:02 +0000 Subject: [PATCH 47/81] Update module.py --- jaxutils/module.py | 169 +++++++++++++++++++++++++-------------------- 1 file changed, 93 insertions(+), 76 deletions(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 5bcb9c0..5f7169b 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -20,13 +20,16 @@ from jax import lax from dataclasses import fields, field -from typing import Any, Callable, NamedTuple, Tuple +from typing import Any, Callable, Tuple from collections import namedtuple -import equinox as eqx +from ._pytree import _PyTreeUpdateHelper +import equinox from .bijectors import Bijector +Distribution = Any + """NamedTuple for storing transformations and trainability status metadata of `jaxutils.Module` PyTree leaves. Args: @@ -109,7 +112,12 @@ def __get__(self, instance, owner): return attr -def param(transform: Bijector, trainable: bool = True, **kwargs: Any): +def param( + transform: Bijector, + trainable: bool = True, + prior: Distribution = None, + **kwargs: Any, +): """Used for marking default parameter transformations. All PyTree leaves of the `jaxutils.Module` must be marked by this function, `jaxutils.static`, or must be of type `jaxutils.Module`. @@ -163,6 +171,9 @@ def param(transform: Bijector, trainable: bool = True, **kwargs: Any): Returns: A `dataclasses.field` object with the `transform` and `trainable` metadata set. """ + + # TODO: Type check. + try: metadata = dict(kwargs["metadata"]) except KeyError: @@ -173,6 +184,9 @@ def param(transform: Bijector, trainable: bool = True, **kwargs: Any): if "trainable" in metadata: raise ValueError("Cannot use metadata with `trainable` already set.") metadata["trainable"] = trainable + if "prior" in metadata: + raise ValueError("Cannot use metadata with `prior` already set.") + metadata["prior"] = prior if "param" in metadata: raise ValueError("Cannot use metadata with `param` already set.") metadata["param"] = True @@ -358,50 +372,26 @@ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) -def _unpack_meta(obj: Module) -> NamedTuple: - """Unpack trainable and tranformation metadata defined by the `jaxutils.param` field of a `jaxutils.Module`. - - This is used to build the leaves of the `trainables` and `bijectors` attributes defined in the `__meta__` attribute of a `jaxutils.Module`, during class instantiation. - - Example: - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - >>> - >>> module = MyModule(param_a=1.0, param_b=1.0) - - We unpack the metadata from the `param` fields using the `_unpack_meta` function. - - >>> meta_named_tuple = _unpack_meta(module) - >>> print(meta_named_tuple) - _Meta(trainables=(True, False), bijectors=(Bijector(forward=>, inverse=>), Bijector(forward=>, inverse=>))) - - We can see this is equivalent to the `__meta__` attribute of the module. - >>> assert meta_named_tuple == module.__meta__ - True - - Args: - obj (Module): The PyTree object whoose leaves are to be transformed. - - Returns: - NamedTuple: A namedtuple with fields `trainables` and `bijectors`. - - Raises: - ValueError: If a leaf is not marked as a parameter and its type is not a subclass of `Module`. - """ +def _default_meta_func(obj: Module): trainables, bijectors = [], [] - for field_ in fields(obj): + for field_, node_ in ( + [f, getattr(obj, f.name)] + for f in obj.__dataclass_fields__.values() + if not f.metadata.get("static", False) + ): - if field_.metadata.get("static", False): + if isinstance(node_, Module): + for trainable, bijector in zip(*_default_meta_func(field_.type)): + trainables.append(trainable) + bijectors.append(bijector) + continue + + if isinstance(node_, list) or isinstance(node_, tuple): + for item in node_: + for trainable, bijector in zip(*_default_meta_func(item)): + trainables.append(trainable) + bijectors.append(bijector) continue if field_.metadata.get("param", False): @@ -409,20 +399,14 @@ def _unpack_meta(obj: Module) -> NamedTuple: bijectors.append(field_.metadata["transform"]) continue - if issubclass(field_.type, Module): - for trainable, bijector in zip(*_unpack_meta(field_.type)): - trainables.append(trainable) - bijectors.append(bijector) - continue - raise ValueError( f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." ) - return _Meta(tuple(trainables), tuple(bijectors)) + return tuple(trainables), tuple(bijectors) -class Module(eqx.Module): +class Module(equinox.Module): """Base Module object. This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), @@ -451,7 +435,7 @@ class Module(eqx.Module): def __new__( cls, *args: Any, - __meta__: _Meta = None, + __meta_func__=None, **kwargs: Any, ) -> Module: """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). @@ -465,11 +449,22 @@ def __new__( Module. An instance of the `jaxutils.Module`. """ obj = super().__new__(cls) - if __meta__ is None: - __meta__ = _unpack_meta(obj) - object.__setattr__(obj, "__meta__", __meta__) + + if __meta_func__ is None: + __meta_func__ = _default_meta_func + + object.__setattr__(obj, "__meta_func__", __meta_func__) return obj + @_cached_static_property + def __meta__(self) -> _Meta: + """Return the metadata for the Module. + + Returns: + _Meta: The metadata for the Module. + """ + return _Meta(*self.__meta_func__(self)) + @_cached_static_property # Caching fine here since `trainables` are static and `Module` is frozen/inmutable. def trainables(self) -> Module: """Return boolean Module comprising trainability statuses for the Module. @@ -507,8 +502,8 @@ def set_trainables(self, tree: Module) -> Module: if not jtu.tree_structure(tree) == jtu.tree_structure(self): raise ValueError("Tree must have the same structure as the Module.") - return self.__update_meta__( - trainables=jtu.tree_leaves(tree), bijectors=self.__meta__.bijectors + return self.__set_meta__( + _Meta(trainables=jtu.tree_leaves(tree), bijectors=self.__meta__.bijectors) ) def set_bijectors(self, tree: Module) -> Module: @@ -535,12 +530,23 @@ def set_bijectors(self, tree: Module) -> Module: "bijectors tree must have the same structure as the Module." ) - return self.__update_meta__( - trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree) + return self.__set_meta__( + _Meta(trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree)) ) - def __update_meta__(self, trainables: Tuple, bijectors: Tuple) -> Module: - """Update Module meta through a new instance. + def __set_meta__(self, __meta__: _Meta) -> Module: + """Set the Module's meta. + + Args: + __meta__ (_Meta): The new meta for the Module. + + Returns: + Module: A new instance of the Module with updated meta. + """ + return self.__set_meta_func__(lambda _: __meta__) + + def __set_meta_func__(self, __meta_func__: _Meta) -> Module: + """Set function that generates parameter meta through a new Module instance. Example: TODO! @@ -552,8 +558,11 @@ def __update_meta__(self, trainables: Tuple, bijectors: Tuple) -> Module: Returns: Module: A new instance of the Module with updated meta. """ - new = self.__class__.__new__( - cls=self.__class__, __meta__=_Meta(trainables, bijectors) + cls = self.__class__ + + new = cls.__new__( + cls=cls, + __meta_func__=__meta_func__, ) for field_ in fields(self): @@ -571,7 +580,6 @@ def tree_flatten(self) -> Tuple[Tuple, Tuple]: dynamic_field_values = [] static_field_names = [] static_field_values = [] - meta = [self.__meta__.trainables, self.__meta__.bijectors] for field_ in fields(self): name = field_.name @@ -590,7 +598,7 @@ def tree_flatten(self) -> Tuple[Tuple, Tuple]: tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(meta), + self.__meta__, ) @classmethod @@ -604,21 +612,30 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: Returns: Module: An instance of the `jaxutils.Module` class. """ - dynamic_field_names, static_field_names, static_field_values, meta = aux + dynamic_field_names, static_field_names, static_field_values, __meta__ = aux + + self = cls.__new__( + cls=cls, + __meta_func__=lambda _: __meta__, + ) - self = cls.__new__(cls=cls, __meta__=_Meta(*meta)) for name, value in zip(dynamic_field_names, dynamic_field_values): object.__setattr__(self, name, value) for name, value in zip(static_field_names, static_field_values): object.__setattr__(self, name, value) + return self + @property + def at(self): + return _PyTreeUpdateHelper(pytree=self) + -__all__ = [ - "Module", - "param", - "static", - "constrain", - "unconstrain", - "stop_gradients", -] +# __all__ = [ +# "Module", +# "param", +# "static", +# "constrain", +# "unconstrain", +# "stop_gradients", +# ] From 37676849af8f3a7c55d122525ccfcf0d4322f3c2 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Sun, 19 Feb 2023 17:10:43 +0000 Subject: [PATCH 48/81] Fix list tuple breakages (SEE NOTE). TODO: - PEFORMANCE: Refactor metadata to make it easier to set, modify, access. `module.at[...].set_meta(**kwargs), could raise error / do some type checking if keyword is e.g., not in metadata, but maybe this might add greater flexibility. It would be better to access trainables, bijectors, etc direcly from a metadata collection. BUG: Need to reintroduce checks / create a policy if a field is not marked with jaxutils.param, to determine whether a field is a node or not. --- jaxutils/_pytree.py | 4 +- jaxutils/module.py | 15 ++++- tests/test_module.py | 137 +++++++++++++++++++++++++++++++++---------- 3 files changed, 120 insertions(+), 36 deletions(-) diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py index 65b9974..2aa9e1d 100644 --- a/jaxutils/_pytree.py +++ b/jaxutils/_pytree.py @@ -16,7 +16,7 @@ """This non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" from __future__ import annotations -from typing import Any, Sequence, Callable, Union +from typing import Any, Sequence, Callable, Union, Iterable from jaxtyping import PyTree from equinox import tree_at @@ -70,7 +70,7 @@ def __init__(self, pytree: PyTree): def __getitem__(self, where: Union[Callable, Sequence[str], Ellipsis]): - if isinstance(where, list) | isinstance(where, str): + if isinstance(where, Iterable) | isinstance(where, str): def _to_path(lst: list): return "".join( diff --git a/jaxutils/module.py b/jaxutils/module.py index 5f7169b..93e9b56 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -382,12 +382,12 @@ def _default_meta_func(obj: Module): ): if isinstance(node_, Module): - for trainable, bijector in zip(*_default_meta_func(field_.type)): + for trainable, bijector in zip(*_default_meta_func(node_)): trainables.append(trainable) bijectors.append(bijector) continue - if isinstance(node_, list) or isinstance(node_, tuple): + if isinstance(node_, list) | isinstance(node_, tuple): for item in node_: for trainable, bijector in zip(*_default_meta_func(item)): trainables.append(trainable) @@ -598,7 +598,7 @@ def tree_flatten(self) -> Tuple[Tuple, Tuple]: tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - self.__meta__, + tuple(self.__meta__), ) @classmethod @@ -630,6 +630,15 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: def at(self): return _PyTreeUpdateHelper(pytree=self) + def constrain(self): + return constrain(self) + + def unconstrain(self): + return unconstrain(self) + + def stop_gradients(self): + return stop_gradients(self) + # __all__ = [ # "Module", diff --git a/tests/test_module.py b/tests/test_module.py index d566822..ef0307c 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,7 +14,7 @@ # ============================================================================== import jax.numpy as jnp -from jaxutils.module import Module, param, constrain, unconstrain, stop_gradients +from jaxutils.module import Module, constrain, param, stop_gradients, unconstrain from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax @@ -119,45 +119,120 @@ def loss(tree): assert g.param_b == 0.0 -def test_module_incorrect_typing(): - class NotAModule: - pass +# TODO: Fix these tests. +# def test_module_incorrect_typing(): +# class NotAModule: +# pass - class SubTree(Module): - param_c: float = param(Identity) - param_d: float = param(Softplus) - param_e: float = param(Softplus) +# class SubTree(Module): +# param_c: float = param(Identity) +# param_d: float = param(Softplus) +# param_e: float = param(Softplus) - class Tree(Module): - param_a: float = param(Identity) - sub_tree: NotAModule - param_b: float = param(Softplus) +# class Tree(Module): +# param_a: float = param(Identity) +# sub_tree: NotAModule +# param_b: float = param(Softplus) - with pytest.raises(ValueError): - Tree( - param_a=1.0, - sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), - param_b=5.0, - ) +# with pytest.raises(ValueError): +# Tree( +# param_a=1.0, +# sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), +# param_b=5.0, +# ) + + +# def test_module_unmarked_param(): +# class SubTree(Module): +# param_c: float +# param_d: float = param(Softplus) +# param_e: float = param(Softplus) +# class Tree(Module): +# param_a: float = param(Identity) +# sub_tree: SubTree +# param_b: float = param(Softplus) -def test_module_unmarked_param(): +# with pytest.raises(ValueError): +# Tree( +# param_a=1.0, +# sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), +# param_b=5.0, +# ) + + +def test_tuple_attribute(): class SubTree(Module): - param_c: float - param_d: float = param(Softplus) - param_e: float = param(Softplus) + param_a: int = param(transform=Identity, default=1) + param_b: int = param(transform=Softplus, default=2) + param_c: int = param(transform=Identity, default=3, trainable=False) class Tree(Module): - param_a: float = param(Identity) - sub_tree: SubTree - param_b: float = param(Softplus) + trees: tuple + + tree = Tree((SubTree(), SubTree(), SubTree())) + + assert len(tree.__meta__.trainables) == 9 + assert len(tree.__meta__.bijectors) == 9 + assert tree.__meta__.trainables == ( + True, + True, + False, + True, + True, + False, + True, + True, + False, + ) + assert tree.__meta__.bijectors == ( + Identity, + Softplus, + Identity, + Identity, + Softplus, + Identity, + Identity, + Softplus, + Identity, + ) - with pytest.raises(ValueError): - Tree( - param_a=1.0, - sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), - param_b=5.0, - ) + +def test_list_attribute(): + class SubTree(Module): + param_a: int = param(transform=Identity, default=1) + param_b: int = param(transform=Softplus, default=2) + param_c: int = param(transform=Identity, default=3, trainable=False) + + class Tree(Module): + trees: list + + tree = Tree([SubTree(), SubTree(), SubTree()]) + + assert len(tree.__meta__.trainables) == 9 + assert len(tree.__meta__.bijectors) == 9 + assert tree.__meta__.trainables == ( + True, + True, + False, + True, + True, + False, + True, + True, + False, + ) + assert tree.__meta__.bijectors == ( + Identity, + Softplus, + Identity, + Identity, + Softplus, + Identity, + Identity, + Softplus, + Identity, + ) def test_module_not_enough_attributes(): From f7537343d9696b851caaf5d128eae86ea20857ff Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Mon, 20 Feb 2023 21:58:59 +0000 Subject: [PATCH 49/81] Minimal functionality for accessing and setting trainables, transforms and priors. --- jaxutils/_pytree.py | 42 +++----- jaxutils/fit.py | 13 --- jaxutils/module.py | 249 +++++++++++++++++++++++++------------------ tests/test_module.py | 14 +-- 4 files changed, 168 insertions(+), 150 deletions(-) diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py index 2aa9e1d..6424a02 100644 --- a/jaxutils/_pytree.py +++ b/jaxutils/_pytree.py @@ -23,14 +23,17 @@ class _PyTreeUpdateRef: - __slots__ = ("pytree", "where") + __slots__ = ( + "pytree", + "where", + ) def __init__(self, pytree: PyTree, where: Union[Callable, Sequence[str]]) -> None: self.pytree = pytree self.where = where def __repr__(self) -> str: - return f"_IndexUpdateRef({repr(self.pytree)}, {repr(self.where)})" + return f"_PyTreeUpdateRef({repr(self.pytree)}, {repr(self.where)})" def get(self) -> PyTree: return self.where(self.pytree) @@ -41,42 +44,29 @@ def set(self, values: Any) -> PyTree: def apply(self, func: Callable) -> PyTree: return tree_at(where=self.where, pytree=self.pytree, replace_fn=func) - # def add(self, values): - # ... - - # def multiply(self, values): - # ... - - # def divide(self, values): - # ... - - # def power(self, values): - # ... - - # def min(self, values): - # ... - - # def max(self, values): - # ... - class _PyTreeUpdateHelper: """Helper class for updating a PyTree.""" __slots__ = ("pytree",) - def __init__(self, pytree: PyTree): + def __init__(self, pytree: PyTree) -> None: self.pytree = pytree - def __getitem__(self, where: Union[Callable, Sequence[str], Ellipsis]): + def __getitem__( + self, where: Union[Callable, Sequence[str], Ellipsis] + ) -> _PyTreeUpdateRef: - if isinstance(where, Iterable) | isinstance(where, str): + if isinstance(where, str): + where = eval("lambda x: x." + where) - def _to_path(lst: list): + if isinstance(where, Iterable): + + def _to_path(it: Iterable): return "".join( [ str(elem) if not isinstance(elem, str) else "." + elem - for elem in lst + for elem in it ] ) @@ -87,5 +77,5 @@ def _to_path(lst: list): return _PyTreeUpdateRef(self.pytree, where) - def __repr__(self): + def __repr__(self) -> str: return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 56dd786..f9eb0f5 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -19,7 +19,6 @@ import jax.random as jr import optax as ox -import jax.tree_util as jtu from jax.random import KeyArray from jax._src.random import _check_prng_key from jaxtyping import Array, Float @@ -27,7 +26,6 @@ from .module import Module, constrain, unconstrain, stop_gradients from .dataset import Dataset -from .bijectors import Bijector from .objective import Objective from .scan import vscan @@ -174,17 +172,6 @@ def _check_model(model: Any) -> None: if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") - if not jtu.tree_structure(model) == jtu.tree_structure(model.trainables): - raise TypeError("trainables should have same tree structure as model") - - def _is_bij(x): - return isinstance(x, Bijector) - - if not jtu.tree_structure( - jtu.tree_map(lambda _: True, model.bijectors, is_leaf=_is_bij) - ) == jtu.tree_structure(model): - raise ValueError("bijectors tree must have the same structure as the Module.") - def _check_objective(objective: Any) -> None: """Check that the objective is of type Objective.""" diff --git a/jaxutils/module.py b/jaxutils/module.py index 93e9b56..c4896e2 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -64,7 +64,7 @@ _Meta(trainables=(True, True), bijectors=(Test(forward=>, inverse=>), Test(forward=>, inverse=>))) """ -_Meta = namedtuple("_Meta", ["trainables", "bijectors"]) +_Meta = namedtuple("_Meta", ["trainables", "bijectors", "priors"]) class _cached_static_property: @@ -281,9 +281,10 @@ def constrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the constrained space. """ - return jtu.tree_map( - lambda leaf, transform: transform.forward(leaf), obj, obj.bijectors - ) + + bijectors = obj.bijectors[...].get() + + return jtu.tree_map(lambda leaf, transform: transform.forward(leaf), obj, bijectors) def unconstrain(obj: Module) -> Module: @@ -322,9 +323,13 @@ def unconstrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the unconstrained space. """ - return jtu.tree_map( - lambda leaf, transform: transform.inverse(leaf), obj, obj.bijectors - ) + + # TODO: Remove the tree_map and work with the leaves directly. + # This is since object metadata already comprises flattened leaves. + + bijectors = obj.bijectors[...].get() + + return jtu.tree_map(lambda leaf, transform: transform.inverse(leaf), obj, bijectors) def stop_gradients(obj: Module) -> Module: @@ -364,16 +369,20 @@ def stop_gradients(obj: Module) -> Module: Returns: Module: PyTree with gradients stopped. """ + # TODO: Remove the tree_map and work with the leaves directly. + # This is since object metadata already comprises flattened leaves. + + trainables = obj.trainables[...].get() def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: """Stop gradients flowing through a given leaf if it is not trainable.""" return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) + return jtu.tree_map(lambda *_: _stop_grad(*_), obj, trainables) -def _default_meta_func(obj: Module): - trainables, bijectors = [], [] +def _default_meta(obj: Module) -> _Meta: + trainables, bijectors, priors = [], [], [] for field_, node_ in ( [f, getattr(obj, f.name)] @@ -382,28 +391,28 @@ def _default_meta_func(obj: Module): ): if isinstance(node_, Module): - for trainable, bijector in zip(*_default_meta_func(node_)): + for trainable, bijector, prior in zip(*_default_meta(node_)): trainables.append(trainable) bijectors.append(bijector) - continue + priors.append(prior) - if isinstance(node_, list) | isinstance(node_, tuple): + elif isinstance(node_, list) | isinstance(node_, tuple): for item in node_: - for trainable, bijector in zip(*_default_meta_func(item)): + for trainable, bijector, prior in zip(*_default_meta(item)): trainables.append(trainable) bijectors.append(bijector) - continue + priors.append(prior) - if field_.metadata.get("param", False): - trainables.append(field_.metadata["trainable"]) - bijectors.append(field_.metadata["transform"]) - continue - - raise ValueError( - f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." - ) + else: + trainables.append(field_.metadata.get("trainable", True)) + bijectors.append(field_.metadata.get("transform", None)) + priors.append(field_.metadata.get("prior", None)) - return tuple(trainables), tuple(bijectors) + return _Meta( + trainables=tuple(trainables), + bijectors=tuple(bijectors), + priors=tuple(priors), + ) class Module(equinox.Module): @@ -435,7 +444,7 @@ class Module(equinox.Module): def __new__( cls, *args: Any, - __meta_func__=None, + __meta_func__: Callable[[Module], _Meta] = _default_meta, **kwargs: Any, ) -> Module: """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). @@ -449,101 +458,46 @@ def __new__( Module. An instance of the `jaxutils.Module`. """ obj = super().__new__(cls) - - if __meta_func__ is None: - __meta_func__ = _default_meta_func - object.__setattr__(obj, "__meta_func__", __meta_func__) return obj @_cached_static_property def __meta__(self) -> _Meta: - """Return the metadata for the Module. + """Return the Module's meta. Returns: - _Meta: The metadata for the Module. + _Meta: The Module's meta. """ - return _Meta(*self.__meta_func__(self)) + return self.__meta_func__(self) - @_cached_static_property # Caching fine here since `trainables` are static and `Module` is frozen/inmutable. + @property def trainables(self) -> Module: """Return boolean Module comprising trainability statuses for the Module. Returns: Module: Boolean Module comprising trainability statuses for the Module. """ - return jtu.tree_structure(self).unflatten(self.__meta__.trainables) + return _MetaUpdateHelper(self, "trainables") - @_cached_static_property # Caching fine here since bijectors are static and `Module` is frozen/inmutable. + @property def bijectors(self) -> Module: """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. Returns: Module: The Bijector Module of parameter transformations for the Module. """ - return jtu.tree_structure(self).unflatten(self.__meta__.bijectors) - - def set_trainables(self, tree: Module) -> Module: - """Set parameter trainability status for the Module. - - Example: - TODO! - - Args: - tree (Module): The boolean tree of trainability status comprising the same tree structure as the underlying Module. - - Returns: - Module: A new instance with the updated trainablility status tree. - """ - if not isinstance(tree, Module): - raise TypeError("Tree must be a JaxUtils Module.") + return _MetaUpdateHelper(self, "bijectors") - if not jtu.tree_structure(tree) == jtu.tree_structure(self): - raise ValueError("Tree must have the same structure as the Module.") - - return self.__set_meta__( - _Meta(trainables=jtu.tree_leaves(tree), bijectors=self.__meta__.bijectors) - ) - - def set_bijectors(self, tree: Module) -> Module: - """Set parameter transformations for the Module. - - Example: - TODO! - - Args: - tree (Module): The bijector tree of parameter transformations comprising the same tree structure as the underlying Module. + @property + def priors(self) -> Module: + """Return the Prior Module comprising priors for parameters. Returns: - Module: A new instance with the updated trainablility status tree. + Module: The Prior Module of parameter priors for the Module. """ - if not isinstance(tree, Module): - raise TypeError("tree must be a JaxUtils Module.") - - if not jtu.tree_structure( - jtu.tree_map( - lambda _: True, tree, is_leaf=lambda x: isinstance(x, Bijector) - ) - ) == jtu.tree_structure(self): - raise ValueError( - "bijectors tree must have the same structure as the Module." - ) - - return self.__set_meta__( - _Meta(trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree)) - ) - def __set_meta__(self, __meta__: _Meta) -> Module: - """Set the Module's meta. - - Args: - __meta__ (_Meta): The new meta for the Module. - - Returns: - Module: A new instance of the Module with updated meta. - """ - return self.__set_meta_func__(lambda _: __meta__) + return _MetaUpdateHelper(self, "priors") def __set_meta_func__(self, __meta_func__: _Meta) -> Module: """Set function that generates parameter meta through a new Module instance. @@ -598,7 +552,13 @@ def tree_flatten(self) -> Tuple[Tuple, Tuple]: tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(self.__meta__), + tuple( + [ + self.__meta__.trainables, + self.__meta__.bijectors, + self.__meta__.priors, + ] + ), ) @classmethod @@ -612,11 +572,11 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: Returns: Module: An instance of the `jaxutils.Module` class. """ - dynamic_field_names, static_field_names, static_field_values, __meta__ = aux + dynamic_field_names, static_field_names, static_field_values, meta = aux self = cls.__new__( cls=cls, - __meta_func__=lambda _: __meta__, + __meta_func__=lambda _: _Meta(*meta), ) for name, value in zip(dynamic_field_names, dynamic_field_values): @@ -628,7 +588,7 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: @property def at(self): - return _PyTreeUpdateHelper(pytree=self) + return _PyTreeUpdateHelper(self) def constrain(self): return constrain(self) @@ -640,11 +600,92 @@ def stop_gradients(self): return stop_gradients(self) -# __all__ = [ -# "Module", -# "param", -# "static", -# "constrain", -# "unconstrain", -# "stop_gradients", -# ] +from typing import Any, Sequence, Callable, Union, Iterable +from jaxtyping import PyTree +from equinox import tree_at + + +def _to_callable(where: Union[Callable, Sequence[str], Ellipsis]) -> Callable: + + if isinstance(where, str): + where = eval("lambda x: x." + where) + + if isinstance(where, Iterable): + + def _to_path(it: Iterable): + return "".join( + [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] + ) + + where = eval("lambda x: x" + _to_path(where)) + + if isinstance(where, type(Ellipsis)): + where = lambda x: x + + return where + + +class _MetaUpdateRef: + + __slots__ = ( + "pytree", + "where", + "meta_attr", + "meta_pytree", + ) + + def __init__( + self, pytree: PyTree, where: Union[Callable, Sequence[str]], meta_attr: str + ) -> None: + + leaves = pytree.__meta__.__getattribute__(meta_attr) + + self.pytree = pytree + self.where = where + self.meta_attr = meta_attr + self.meta_pytree = jtu.tree_structure(pytree).unflatten(leaves) + + def __repr__(self) -> str: + return f"_MetaUpdateRef({repr(self.pytree)}, {repr(self.where)})" + + def get(self) -> PyTree: + return self.where(self.meta_pytree) + + def set(self, values: Any) -> PyTree: + new_meta_pytree = tree_at( + where=self.where, pytree=self.meta_pytree, replace=values + ) + new_meta = self.pytree.__meta__._replace( + **{self.meta_attr: jtu.tree_leaves(new_meta_pytree)} + ) + return self.pytree.__set_meta_func__(lambda _: new_meta) + + def apply(self, func: Callable) -> PyTree: + new_meta_pytree = tree_at( + where=self.where, pytree=self.meta_pytree, replace_fn=func + ) + new_meta = self.pytree.__meta__._replace( + **{self.meta_attr: jtu.tree_leaves(new_meta_pytree)} + ) + return self.pytree.__set_meta_func__(lambda _: new_meta) + + +class _MetaUpdateHelper: + """Helper class for updating a PyTree.""" + + __slots__ = ( + "pytree", + "meta_attr", + ) + + def __init__(self, pytree: PyTree, meta_attr: str) -> None: + self.pytree = pytree + self.meta_attr = meta_attr + + def __getitem__( + self, where: Union[Callable, Sequence[str], Ellipsis] + ) -> _MetaUpdateRef: + return _MetaUpdateRef(self.pytree, _to_callable(where), self.meta_attr) + + def __repr__(self) -> str: + return f"_MetaUpdateHelper({repr(self.pytree)}, meta_attr={self.meta_attr})" diff --git a/tests/test_module.py b/tests/test_module.py index ef0307c..0026811 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -46,11 +46,11 @@ class Tree(Module): ) assert isinstance(tree, Module) - assert isinstance(tree.trainables, Module) - assert isinstance(tree.bijectors, Module) + assert isinstance(tree.trainables[...].get(), Module) + assert isinstance(tree.bijectors[...].get(), Module) assert isinstance(tree, eqx.Module) - assert isinstance(tree.trainables, eqx.Module) - assert isinstance(tree.bijectors, eqx.Module) + assert isinstance(tree.trainables[...].get(), eqx.Module) + assert isinstance(tree.bijectors[...].get(), eqx.Module) assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 @@ -59,7 +59,7 @@ class Tree(Module): assert tree.param_b == 5.0 # Test default bijectors - bijectors = tree.bijectors + bijectors = tree.bijectors[...].get() bijector_list = jtu.tree_leaves(bijectors) for b1, b2 in zip( @@ -68,7 +68,7 @@ class Tree(Module): assert b1 == b2 # Test default trainables - trainables = tree.trainables + trainables = tree.trainables[...].get() trainable_list = jtu.tree_leaves(trainables) for t1, t2 in zip(trainable_list, [True, True, True, True, True]): @@ -97,7 +97,7 @@ class Tree(Module): _, tree_def = jtu.tree_flatten(tree) trainables = tree_def.unflatten([True, False, True, False, False]) - new_tree = tree.set_trainables(trainables) + new_tree = tree.trainables[...].set(trainables) # Test stop gradients def loss(tree): From 999780587db8a0349a06a211042c6333467ef1cb Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 22 Feb 2023 10:16:50 +0000 Subject: [PATCH 50/81] Push minimal meta functionality. --- jaxutils/_cached.py | 63 ++++++++ jaxutils/_meta.py | 276 +++++++++++++++++++++++++++++++++++ jaxutils/_pytree.py | 42 ++---- jaxutils/distributions.py | 25 ++++ jaxutils/fit.py | 13 -- jaxutils/module.py | 299 ++++++++++---------------------------- tests/test_module.py | 61 ++++---- 7 files changed, 485 insertions(+), 294 deletions(-) create mode 100644 jaxutils/_cached.py create mode 100644 jaxutils/_meta.py create mode 100644 jaxutils/distributions.py diff --git a/jaxutils/_cached.py b/jaxutils/_cached.py new file mode 100644 index 0000000..f8ebd85 --- /dev/null +++ b/jaxutils/_cached.py @@ -0,0 +1,63 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 non-public module defines the caching utilities for the Module class's static properties.""" + +from __future__ import annotations +from typing import Callable + + +class _cached_static_property: + """Decorator to cache result of static immutable properties of a PyTree. + + Example: + + This example shows us caching the result of sqauring a static float attribute of a Module. + + >>> import jaxutils as ju + >>> + >>> class MyModule(ju.Module): + >>> static_attribute: float = ju.static() + + >>> @_cached_static_property + >>> def static_property(self): + >>> return self.static_attribute ** 2 + + Note: + The decorated property must *NOT* contain any dynamic attributes / PyTree leaves, + i.e., any attributes referenced in the property must be marked as static. + + For example, the following will break durin tracing since `self.dynamic_attribute` is not static: + + >>> import jaxutils as ju + >>> + >>> class MyModule(ju.Module): + >>> static_attribute: float = ju.static() + >>> dynamic_attribute: float = ju.param(ju.Identity) + >>> + >>> @_cached_static_property + >>> def static_property(self): + >>> return self.static_attribute ** 2 + self.dynamic_attribute + """ + + def __init__(self, static_property: Callable): + """Here we store the name of the property and the function itself.""" + self.name = static_property.__name__ + self.func = static_property + + def __get__(self, instance, owner): + """Here we cache the result of the property function, by overwriting the attribute with the result.""" + attr = self.func(instance) + object.__setattr__(instance, self.name, attr) + return attr diff --git a/jaxutils/_meta.py b/jaxutils/_meta.py new file mode 100644 index 0000000..06a98cd --- /dev/null +++ b/jaxutils/_meta.py @@ -0,0 +1,276 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` metadata via the `jax.numpy` e.g. `.at` and `.set` syntax. + +The following classes mimic what is done in lax.numpy. +""" + +from __future__ import annotations +from typing import Callable, Any, Union, Sequence, Iterable +from jaxtyping import PyTree +import jax.tree_util as jtu + + +class _MetaUpdateRef: + + __slots__ = ( + "pytree", + "where", + ) + + def __init__(self, pytree: PyTree, where: Callable[[PyTree], PyTree]) -> None: + self.pytree = pytree + self.where = where + + def __repr__(self) -> str: + return f"_MetaUpdateRef({repr(self.pytree)}, {repr(self.where)})" + + def get(self, name: str = None, value: Any = None) -> PyTree: + if name is None: + return self.where( + jtu.tree_structure(self.pytree).unflatten(self.pytree.__meta__) + ) + + else: + return self.where( + jtu.tree_structure(self.pytree).unflatten( + [meta_.get(name, value) for meta_ in self.pytree.__meta__] + ) + ) + + def set(self, **kwargs) -> PyTree: + return _meta_at(where=self.where, pytree=self.pytree, replace=kwargs) + + def apply(self, func: Callable) -> PyTree: + return _meta_at(where=self.where, pytree=self.pytree, replace_fn=func) + + +class _MetaUpdateHelper: + """Helper class for updating a PyTree.""" + + __slots__ = ("pytree",) + + def __init__(self, pytree: PyTree) -> None: + self.pytree = pytree + + def __getitem__(self, where: Callable[[PyTree], PyTree]) -> _MetaUpdateRef: + return _MetaUpdateRef(self.pytree, _to_callable(where)) + + def __repr__(self) -> str: + return f"_MetaUpdateHelper({repr(self.pytree)})" + + +def _to_callable(where: Union[Callable, Sequence[str], Ellipsis]) -> Callable: + + if isinstance(where, str): + where = eval("lambda x: x." + where) + + if isinstance(where, Iterable): + + def _to_path(it: Iterable): + return "".join( + [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] + ) + + where = eval("lambda x: x" + _to_path(where)) + + if isinstance(where, type(Ellipsis)): + where = lambda x: x + + return where + + +from typing import Any +import jax.tree_util as jtu + +_Node = Any + + +class _LeafWrapper: + __slots__ = ("value",) + + def __init__(self, value: Any): + self.value = value + + +def _remove_leaf_wrapper(x: _LeafWrapper) -> Any: + assert type(x) is _LeafWrapper + return x.value + + +class _CountedIdDict: + + __slots__ = ("_dict",) + + def __init__(self, keys, values): + assert len(keys) == len(values) + self._dict = {id(k): (0, v) for k, v in zip(keys, values)} + + def __contains__(self, item): + return id(item) in self._dict + + def __getitem__(self, item): + c, v = self._dict[id(item)] + self._dict[id(item)] = (c + 1, v) + return v + + def get(self, item, default): + try: + return self[item] + except KeyError: + return default + + def count(self, item): + return self._dict[id(item)][0] + + +def _meta_map(f: Callable[..., Any], tree: PyTree) -> PyTree: + """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves.""" + leaves, treedef = jtu.tree_flatten(tree) + meta_leaves = tree.__meta__ + all_leaves = [leaves] + [meta_leaves] + return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) + + +# TODO: Rerwite this function to exploit flattened meta pytree structure -> This would be faster than the current implementation that has to unflatten the meta pytree for each leaf. +def _meta_at( + where, + pytree, + replace=None, + replace_fn=None, + is_leaf=lambda x: isinstance(x, dict), +): + """Adapted from Equinox's `tree_at`.""" + + # We need to specify a particular node in a PyTree. + # This is surprisingly difficult to do! As far as I can see, pretty much the only + # way of doing this is to specify e.g. `x.foo[0].bar` via `is`, and then pulling + # a few tricks to try and ensure that the same object doesn't appear multiple + # times in the same PyTree. + # + # So this first `tree_map` serves a dual purpose. + # 1) Makes a copy of the composite nodes in the PyTree, to avoid aliasing via + # e.g. `pytree=[(1,)] * 5`. This has the tuple `(1,)` appear multiple times. + # 2) It makes each leaf be a unique Python object, as it's wrapped in + # `_LeafWrapper`. This is needed because Python caches a few builtin objects: + # `assert 0 + 1 is 1`. I think only a few leaf types are subject to this. + # So point 1) should ensure that all composite nodes are unique Python objects, + # and point 2) should ensure that all leaves are unique Python objects. + # Between them, all nodes of `pytree` are handled. + # + # I think pretty much the only way this can fail is when using a custom node with + # singleton-like flatten+unflatten behaviour, which is pretty edge case. And we've + # added a check for it at the bottom of this function, just to be sure. + # + # Whilst we're here: we also double-check that `where` is well-formed and doesn't + # use leaf information. (As else `node_or_nodes` will be wrong.) + pytree_old = pytree + pytree = jtu.tree_structure(pytree).unflatten(pytree.__meta__) + + node_or_nodes_nowrapper = where(pytree) + pytree = jtu.tree_map(_LeafWrapper, pytree, is_leaf=is_leaf) + node_or_nodes = where(pytree) + leaves1, structure1 = jtu.tree_flatten(node_or_nodes_nowrapper, is_leaf=is_leaf) + leaves2, structure2 = jtu.tree_flatten(node_or_nodes) + leaves2 = [_remove_leaf_wrapper(x) for x in leaves2] + if ( + structure1 != structure2 + or len(leaves1) != len(leaves2) + or any(l1 is not l2 for l1, l2 in zip(leaves1, leaves2)) + ): + raise ValueError( + "`where` must use just the PyTree structure of `pytree`. `where` must not " + "depend on the leaves in `pytree`." + ) + del node_or_nodes_nowrapper, leaves1, structure1, leaves2, structure2 + + # Normalise whether we were passed a single node or a sequence of nodes. + in_pytree = False + + def _in_pytree(x): + nonlocal in_pytree + if x is node_or_nodes: # noqa: F821 + in_pytree = True + return x # needed for jax.tree_util.Partial, which has a dodgy constructor + + jtu.tree_map(_in_pytree, pytree, is_leaf=lambda x: x is node_or_nodes) # noqa: F821 + + if in_pytree: + nodes = (node_or_nodes,) + if replace is not None: + replace = (replace,) + else: + nodes = node_or_nodes + del in_pytree, node_or_nodes + + # Normalise replace vs replace_fn + if replace is None: + if replace_fn is None: + raise ValueError( + "Precisely one of `replace` and `replace_fn` must be specified." + ) + else: + + def _replace_fn(x): + x = jtu.tree_map(_remove_leaf_wrapper, x) + return replace_fn(x) + + replace_fns = [_replace_fn] * len(nodes) + else: + if replace_fn is None: + + # TODO: Need to fix this. + def _replace_fn(x, i): + x = jtu.tree_map(_remove_leaf_wrapper, x) + + for k, v in replace.items(): + + # if len(nodes) != len(v): + # raise ValueError( + # "`where` must return a sequence of leaves of the same length as " + # "`replace`." + # ) + + try: + value = v[i] + except: + TypeError + value = v + + x.update({k: value}) + + return x + + replace_fns = [lambda x, i=i: _replace_fn(x, i) for i in range(len(nodes))] + else: + raise ValueError( + "Precisely one of `replace` and `replace_fn` must be specified." + ) + node_replace_fns = _CountedIdDict(nodes, replace_fns) + + # Actually do the replacement + def _make_replacement(x: _Node) -> Any: + return node_replace_fns.get(x, _remove_leaf_wrapper)(x) + + out = jtu.tree_map( + _make_replacement, pytree, is_leaf=lambda x: x in node_replace_fns + ) + + print(out) + + new = pytree_old.__set_meta_func__(lambda _: jtu.tree_leaves(out, is_leaf=is_leaf)) + + return new diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py index 2aa9e1d..6424a02 100644 --- a/jaxutils/_pytree.py +++ b/jaxutils/_pytree.py @@ -23,14 +23,17 @@ class _PyTreeUpdateRef: - __slots__ = ("pytree", "where") + __slots__ = ( + "pytree", + "where", + ) def __init__(self, pytree: PyTree, where: Union[Callable, Sequence[str]]) -> None: self.pytree = pytree self.where = where def __repr__(self) -> str: - return f"_IndexUpdateRef({repr(self.pytree)}, {repr(self.where)})" + return f"_PyTreeUpdateRef({repr(self.pytree)}, {repr(self.where)})" def get(self) -> PyTree: return self.where(self.pytree) @@ -41,42 +44,29 @@ def set(self, values: Any) -> PyTree: def apply(self, func: Callable) -> PyTree: return tree_at(where=self.where, pytree=self.pytree, replace_fn=func) - # def add(self, values): - # ... - - # def multiply(self, values): - # ... - - # def divide(self, values): - # ... - - # def power(self, values): - # ... - - # def min(self, values): - # ... - - # def max(self, values): - # ... - class _PyTreeUpdateHelper: """Helper class for updating a PyTree.""" __slots__ = ("pytree",) - def __init__(self, pytree: PyTree): + def __init__(self, pytree: PyTree) -> None: self.pytree = pytree - def __getitem__(self, where: Union[Callable, Sequence[str], Ellipsis]): + def __getitem__( + self, where: Union[Callable, Sequence[str], Ellipsis] + ) -> _PyTreeUpdateRef: - if isinstance(where, Iterable) | isinstance(where, str): + if isinstance(where, str): + where = eval("lambda x: x." + where) - def _to_path(lst: list): + if isinstance(where, Iterable): + + def _to_path(it: Iterable): return "".join( [ str(elem) if not isinstance(elem, str) else "." + elem - for elem in lst + for elem in it ] ) @@ -87,5 +77,5 @@ def _to_path(lst: list): return _PyTreeUpdateRef(self.pytree, where) - def __repr__(self): + def __repr__(self) -> str: return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/distributions.py b/jaxutils/distributions.py new file mode 100644 index 0000000..6999938 --- /dev/null +++ b/jaxutils/distributions.py @@ -0,0 +1,25 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 equinox as eqx + + +class Distribution(eqx.Module): + """Base class for distributions.""" + + +__all__ = [ + "Distribution", +] diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 56dd786..f9eb0f5 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -19,7 +19,6 @@ import jax.random as jr import optax as ox -import jax.tree_util as jtu from jax.random import KeyArray from jax._src.random import _check_prng_key from jaxtyping import Array, Float @@ -27,7 +26,6 @@ from .module import Module, constrain, unconstrain, stop_gradients from .dataset import Dataset -from .bijectors import Bijector from .objective import Objective from .scan import vscan @@ -174,17 +172,6 @@ def _check_model(model: Any) -> None: if not isinstance(model, Module): raise TypeError("model must be of type jaxutils.Module") - if not jtu.tree_structure(model) == jtu.tree_structure(model.trainables): - raise TypeError("trainables should have same tree structure as model") - - def _is_bij(x): - return isinstance(x, Bijector) - - if not jtu.tree_structure( - jtu.tree_map(lambda _: True, model.bijectors, is_leaf=_is_bij) - ) == jtu.tree_structure(model): - raise ValueError("bijectors tree must have the same structure as the Module.") - def _check_objective(objective: Any) -> None: """Check that the objective is of type Objective.""" diff --git a/jaxutils/module.py b/jaxutils/module.py index 93e9b56..ec220dc 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -15,101 +15,17 @@ from __future__ import annotations -import jax.tree_util as jtu import jax -from jax import lax +import equinox +from jax import lax from dataclasses import fields, field -from typing import Any, Callable, Tuple -from collections import namedtuple +from typing import Any, Callable, Tuple, List, Dict +from .bijectors import Bijector, Identity +from .distributions import Distribution from ._pytree import _PyTreeUpdateHelper -import equinox - -from .bijectors import Bijector - -Distribution = Any - -"""NamedTuple for storing transformations and trainability status metadata of `jaxutils.Module` PyTree leaves. - -Args: - trainables (Tuple[bool]): Whether the PyTree leaf is trainable. - bijectors (Tuple[Bijector]): The bijector that should be applied to the PyTree leaf. - -Example: - This example shows us creating a module with two parameters, and accessing the metadata of the module. - This is part of the non-public API, and is not intended to be used directly by users. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> # Create a bijector for demonstration purposes. - >>> class Test(ju.Bijector): - >>> def __init__(self): - >>> self.forward = jnp.tanh - >>> self.inverse = jnp.arctanh - >>> - >>> # Create a module with two parameters. - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(Test()) - >>> param_b: float = ju.param(Test()) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - >>> - >>> module = MyModule(param_a=1.0, param_b=1.0) - >>> - >>> # The `__meta__` attribute is a `_Meta` object. - >>> print(module.__meta__) - _Meta(trainables=(True, True), bijectors=(Test(forward=>, inverse=>), Test(forward=>, inverse=>))) - -""" -_Meta = namedtuple("_Meta", ["trainables", "bijectors"]) - - -class _cached_static_property: - """Decorator to cache result of static immutable properties of a PyTree. - - Example: - - This example shows us caching the result of sqauring a static float attribute of a Module. - - >>> import jaxutils as ju - >>> - >>> class MyModule(ju.Module): - >>> static_attribute: float = ju.static() - - >>> @_cached_static_property - >>> def static_property(self): - >>> return self.static_attribute ** 2 - - Note: - The decorated property must *NOT* contain any dynamic attributes / PyTree leaves, - i.e., any attributes referenced in the property must be marked as static. - - For example, the following will break durin tracing since `self.dynamic_attribute` is not static: - - >>> import jaxutils as ju - >>> - >>> class MyModule(ju.Module): - >>> static_attribute: float = ju.static() - >>> dynamic_attribute: float = ju.param(ju.Identity) - >>> - >>> @_cached_static_property - >>> def static_property(self): - >>> return self.static_attribute ** 2 + self.dynamic_attribute - """ - - def __init__(self, static_property: Callable): - """Here we store the name of the property and the function itself.""" - self.name = static_property.__name__ - self.func = static_property - - def __get__(self, instance, owner): - """Here we cache the result of the property function, by overwriting the attribute with the result.""" - attr = self.func(instance) - object.__setattr__(instance, self.name, attr) - return attr +from ._meta import _MetaUpdateHelper, _meta_map def param( @@ -281,8 +197,8 @@ def constrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the constrained space. """ - return jtu.tree_map( - lambda leaf, transform: transform.forward(leaf), obj, obj.bijectors + return _meta_map( + lambda leaf, meta: meta.get("transform", Identity).forward(leaf), obj ) @@ -322,8 +238,8 @@ def unconstrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the unconstrained space. """ - return jtu.tree_map( - lambda leaf, transform: transform.inverse(leaf), obj, obj.bijectors + return _meta_map( + lambda leaf, meta: meta.get("transform", Identity).inverse(leaf), obj ) @@ -369,11 +285,14 @@ def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: """Stop gradients flowing through a given leaf if it is not trainable.""" return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - return jtu.tree_map(lambda *_: _stop_grad(*_), obj, obj.trainables) + return _meta_map( + lambda leaf, meta: _stop_grad(leaf, meta.get("trainable", True)), obj + ) -def _default_meta_func(obj: Module): - trainables, bijectors = [], [] +# TODO: Rewrite this as a generator. +def _default_meta(obj: Module) -> tuple[Dict]: + meta = [] for field_, node_ in ( [f, getattr(obj, f.name)] @@ -382,28 +301,19 @@ def _default_meta_func(obj: Module): ): if isinstance(node_, Module): - for trainable, bijector in zip(*_default_meta_func(node_)): - trainables.append(trainable) - bijectors.append(bijector) - continue + for meta_ in _default_meta(node_): + meta.append(meta_) - if isinstance(node_, list) | isinstance(node_, tuple): + elif isinstance(node_, list | tuple): for item in node_: - for trainable, bijector in zip(*_default_meta_func(item)): - trainables.append(trainable) - bijectors.append(bijector) - continue - - if field_.metadata.get("param", False): - trainables.append(field_.metadata["trainable"]) - bijectors.append(field_.metadata["transform"]) - continue - - raise ValueError( - f"Field `{field_.name}` must either be: \n- marked as a parameter via by the `param` field\n- marked as static via the `static` field metadata\n- a jaxutils.Module." - ) + for meta_ in _default_meta(item): + meta.append(meta_) + else: + meta.append( + {**field_.metadata} + ) # Have to do this otherwise can't pickle the Module. - return tuple(trainables), tuple(bijectors) + return meta class Module(equinox.Module): @@ -435,125 +345,43 @@ class Module(equinox.Module): def __new__( cls, *args: Any, - __meta_func__=None, + __meta_func__: Callable[[Module], List[Dict]] = _default_meta, **kwargs: Any, ) -> Module: """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). Args: - __meta__ (_Meta): Metadata that defines the Module's trainables and bijectors PyTree leaves. *args (Any): Arguments. + __meta_func__ (Callable[[Module], List[Dict]], optional): Function to generate the Module's meta. Defaults to _default_meta. **kwargs (Any): Keyword arguments. Returns: Module. An instance of the `jaxutils.Module`. """ obj = super().__new__(cls) - - if __meta_func__ is None: - __meta_func__ = _default_meta_func - object.__setattr__(obj, "__meta_func__", __meta_func__) return obj - @_cached_static_property - def __meta__(self) -> _Meta: - """Return the metadata for the Module. - - Returns: - _Meta: The metadata for the Module. - """ - return _Meta(*self.__meta_func__(self)) - - @_cached_static_property # Caching fine here since `trainables` are static and `Module` is frozen/inmutable. - def trainables(self) -> Module: - """Return boolean Module comprising trainability statuses for the Module. - - Returns: - Module: Boolean Module comprising trainability statuses for the Module. - """ - return jtu.tree_structure(self).unflatten(self.__meta__.trainables) - - @_cached_static_property # Caching fine here since bijectors are static and `Module` is frozen/inmutable. - def bijectors(self) -> Module: - """Return the Bijector Module comprising transformations for parameters to and from the constrained and unconstrained spaces. - - Returns: - Module: The Bijector Module of parameter transformations for the Module. - """ - return jtu.tree_structure(self).unflatten(self.__meta__.bijectors) - - def set_trainables(self, tree: Module) -> Module: - """Set parameter trainability status for the Module. - - Example: - TODO! - - Args: - tree (Module): The boolean tree of trainability status comprising the same tree structure as the underlying Module. - - Returns: - Module: A new instance with the updated trainablility status tree. - """ - - if not isinstance(tree, Module): - raise TypeError("Tree must be a JaxUtils Module.") - - if not jtu.tree_structure(tree) == jtu.tree_structure(self): - raise ValueError("Tree must have the same structure as the Module.") - - return self.__set_meta__( - _Meta(trainables=jtu.tree_leaves(tree), bijectors=self.__meta__.bijectors) - ) - - def set_bijectors(self, tree: Module) -> Module: - """Set parameter transformations for the Module. - - Example: - TODO! - - Args: - tree (Module): The bijector tree of parameter transformations comprising the same tree structure as the underlying Module. - - Returns: - Module: A new instance with the updated trainablility status tree. - """ - if not isinstance(tree, Module): - raise TypeError("tree must be a JaxUtils Module.") - - if not jtu.tree_structure( - jtu.tree_map( - lambda _: True, tree, is_leaf=lambda x: isinstance(x, Bijector) - ) - ) == jtu.tree_structure(self): - raise ValueError( - "bijectors tree must have the same structure as the Module." - ) - - return self.__set_meta__( - _Meta(trainables=self.__meta__.trainables, bijectors=jtu.tree_leaves(tree)) - ) - - def __set_meta__(self, __meta__: _Meta) -> Module: - """Set the Module's meta. - - Args: - __meta__ (_Meta): The new meta for the Module. + # @_cached_static_property + @property + def __meta__(self) -> List[Dict]: + """Return the Module's meta. Returns: - Module: A new instance of the Module with updated meta. + _Meta: The Module's meta. """ - return self.__set_meta_func__(lambda _: __meta__) + return self.__meta_func__(self) - def __set_meta_func__(self, __meta_func__: _Meta) -> Module: + def __set_meta_func__( + self, __meta_func__: Callable[[Module], List[Dict]] + ) -> Module: """Set function that generates parameter meta through a new Module instance. Example: TODO! Args: - trainables (Tuple): The new leaves of the trainables PyTree. - bijectors (Tuple): The new leaves of the bijectors PyTree. + __meta_func__ (Callable[[Module], List[Dict]]): Function to generate the Module's meta. Returns: Module: A new instance of the Module with updated meta. @@ -598,7 +426,7 @@ def tree_flatten(self) -> Tuple[Tuple, Tuple]: tuple(dynamic_field_names), tuple(static_field_names), tuple(static_field_values), - tuple(self.__meta__), + self.__meta__, ) @classmethod @@ -612,11 +440,11 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: Returns: Module: An instance of the `jaxutils.Module` class. """ - dynamic_field_names, static_field_names, static_field_values, __meta__ = aux + dynamic_field_names, static_field_names, static_field_values, meta = aux self = cls.__new__( cls=cls, - __meta_func__=lambda _: __meta__, + __meta_func__=lambda _: meta, ) for name, value in zip(dynamic_field_names, dynamic_field_values): @@ -627,8 +455,28 @@ def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: return self @property - def at(self): - return _PyTreeUpdateHelper(pytree=self) + def tree_at(self): + return _PyTreeUpdateHelper(self) + + @property + def meta_at(self): + return _MetaUpdateHelper(self) + + def training_transforms(self): + class _ConstrainHelper: + + slots = ("module",) + + def __init__(self, module): + self.module = module + + def __enter__(self): + return constrain(self.module) + + def __exit__(self, *args): + return unconstrain(self.module) + + return _ConstrainHelper(self) def constrain(self): return constrain(self) @@ -637,14 +485,17 @@ def unconstrain(self): return unconstrain(self) def stop_gradients(self): - return stop_gradients(self) + class _StopGradientsHelper: + + slots = ("module",) + + def __init__(self, module): + self.module = module + + def __enter__(self): + return stop_gradients(self.module) + def __exit__(self, *args): + return True -# __all__ = [ -# "Module", -# "param", -# "static", -# "constrain", -# "unconstrain", -# "stop_gradients", -# ] + return _StopGradientsHelper(self) diff --git a/tests/test_module.py b/tests/test_module.py index ef0307c..8c49a0f 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,7 +14,7 @@ # ============================================================================== import jax.numpy as jnp -from jaxutils.module import Module, constrain, param, stop_gradients, unconstrain +from jaxutils.module import Module, constrain, param, unconstrain from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax @@ -46,11 +46,11 @@ class Tree(Module): ) assert isinstance(tree, Module) - assert isinstance(tree.trainables, Module) - assert isinstance(tree.bijectors, Module) + assert isinstance(tree.meta_at[...].get("trainable"), Module) + assert isinstance(tree.meta_at[...].get("transform"), Module) assert isinstance(tree, eqx.Module) - assert isinstance(tree.trainables, eqx.Module) - assert isinstance(tree.bijectors, eqx.Module) + assert isinstance(tree.meta_at[...].get("trainable"), eqx.Module) + assert isinstance(tree.meta_at[...].get("transform"), eqx.Module) assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 @@ -59,7 +59,7 @@ class Tree(Module): assert tree.param_b == 5.0 # Test default bijectors - bijectors = tree.bijectors + bijectors = tree.meta_at[...].get("transform") bijector_list = jtu.tree_leaves(bijectors) for b1, b2 in zip( @@ -68,7 +68,7 @@ class Tree(Module): assert b1 == b2 # Test default trainables - trainables = tree.trainables + trainables = tree.meta_at[...].get("trainable") trainable_list = jtu.tree_leaves(trainables) for t1, t2 in zip(trainable_list, [True, True, True, True, True]): @@ -94,21 +94,20 @@ class Tree(Module): ): assert bij.inverse(l1) == l2 - _, tree_def = jtu.tree_flatten(tree) - trainables = tree_def.unflatten([True, False, True, False, False]) - - new_tree = tree.set_trainables(trainables) + new_tree = tree.meta_at[ + lambda t: (t.sub_tree.param_c, t.param_b, t.sub_tree.param_e) + ].set(trainable=[False, False, False]) # Test stop gradients def loss(tree): - tree = stop_gradients(tree) - return jnp.sum( - tree.param_a**2 - + tree.sub_tree.param_c**2 - + tree.sub_tree.param_d**2 - + tree.sub_tree.param_e**2 - + tree.param_b**2 - ) + with tree.stop_gradients() as t: + return jnp.sum( + t.param_a**2 + + t.sub_tree.param_c**2 + + t.sub_tree.param_d**2 + + t.sub_tree.param_e**2 + + t.param_b**2 + ) g = jax.grad(loss)(new_tree) @@ -172,9 +171,9 @@ class Tree(Module): tree = Tree((SubTree(), SubTree(), SubTree())) - assert len(tree.__meta__.trainables) == 9 - assert len(tree.__meta__.bijectors) == 9 - assert tree.__meta__.trainables == ( + assert len([meta.get("trainable") for meta in tree.__meta__]) == 9 + assert len([meta.get("transform") for meta in tree.__meta__]) == 9 + assert [meta.get("trainable") for meta in tree.__meta__] == [ True, True, False, @@ -184,8 +183,8 @@ class Tree(Module): True, True, False, - ) - assert tree.__meta__.bijectors == ( + ] + assert [meta.get("transform") for meta in tree.__meta__] == [ Identity, Softplus, Identity, @@ -195,7 +194,7 @@ class Tree(Module): Identity, Softplus, Identity, - ) + ] def test_list_attribute(): @@ -209,9 +208,9 @@ class Tree(Module): tree = Tree([SubTree(), SubTree(), SubTree()]) - assert len(tree.__meta__.trainables) == 9 - assert len(tree.__meta__.bijectors) == 9 - assert tree.__meta__.trainables == ( + assert len([meta.get("trainable") for meta in tree.__meta__]) == 9 + assert len([meta.get("transform") for meta in tree.__meta__]) == 9 + assert [meta.get("trainable") for meta in tree.__meta__] == [ True, True, False, @@ -221,8 +220,8 @@ class Tree(Module): True, True, False, - ) - assert tree.__meta__.bijectors == ( + ] + assert [meta.get("transform") for meta in tree.__meta__] == [ Identity, Softplus, Identity, @@ -232,7 +231,7 @@ class Tree(Module): Identity, Softplus, Identity, - ) + ] def test_module_not_enough_attributes(): From ce5264051a028dd377dd5fd30ea7a075e9297610 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 22 Feb 2023 10:21:20 +0000 Subject: [PATCH 51/81] Python 3.8 does not like "|" --- jaxutils/module.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxutils/module.py b/jaxutils/module.py index 69a1d05..a3294f7 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -307,7 +307,7 @@ def _default_meta(obj: Module) -> tuple[Dict]: for meta_ in _default_meta(node_): meta.append(meta_) - elif isinstance(node_, list | tuple): + elif isinstance(node_, list) | isinstance(node_, tuple): for item in node_: for meta_ in _default_meta(item): meta.append(meta_) From c2891339b514c279af91ce820d9cc3a40a9b5331 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 22 Feb 2023 10:33:38 +0000 Subject: [PATCH 52/81] Update test_module.py --- tests/test_module.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/tests/test_module.py b/tests/test_module.py index 8c49a0f..8250971 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,7 +14,7 @@ # ============================================================================== import jax.numpy as jnp -from jaxutils.module import Module, constrain, param, unconstrain +from jaxutils.module import Module, constrain, param, unconstrain, stop_gradients from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax @@ -99,15 +99,25 @@ class Tree(Module): ].set(trainable=[False, False, False]) # Test stop gradients + # def loss(tree): + # with tree.stop_gradients() as t: + # return jnp.sum( + # t.param_a**2 + # + t.sub_tree.param_c**2 + # + t.sub_tree.param_d**2 + # + t.sub_tree.param_e**2 + # + t.param_b**2 + # ) + def loss(tree): - with tree.stop_gradients() as t: - return jnp.sum( - t.param_a**2 - + t.sub_tree.param_c**2 - + t.sub_tree.param_d**2 - + t.sub_tree.param_e**2 - + t.param_b**2 - ) + tree = stop_gradients(tree) + return jnp.sum( + tree.param_a**2 + + tree.sub_tree.param_c**2 + + tree.sub_tree.param_d**2 + + tree.sub_tree.param_e**2 + + tree.param_b**2 + ) g = jax.grad(loss)(new_tree) From a47c8dda9783b9949e1ea6da6ef656b378a068a8 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 22 Feb 2023 10:34:55 +0000 Subject: [PATCH 53/81] Update test_module.py --- tests/test_module.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_module.py b/tests/test_module.py index 8250971..1d98597 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -98,6 +98,12 @@ class Tree(Module): lambda t: (t.sub_tree.param_c, t.param_b, t.sub_tree.param_e) ].set(trainable=[False, False, False]) + new_trainables = new_tree.meta_at[...].get("trainable") + new_trainable_list = jtu.tree_leaves(new_trainables) + + for t1, t2 in zip(new_trainable_list, [True, False, True, False, False]): + assert t1 == t2 + # Test stop gradients # def loss(tree): # with tree.stop_gradients() as t: From 08920bf647529ea12224fb35c2b2479eb3c16a5a Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Tue, 7 Mar 2023 16:33:28 +0000 Subject: [PATCH 54/81] Redesign PyTree and introduce Module. For transparency this is heavily inspired by `Equinox` and `Simple-Pytree`, which have been adapted to provide metadata functionality, to apply transformations and stop gradients, etc. We hope to be Equinox compatible, as much as possible. --- jaxutils/__init__.py | 14 +- jaxutils/_meta.py | 276 ------------------------------- jaxutils/_module.py | 129 +++++++++++++++ jaxutils/_pytree.py | 46 ++++-- jaxutils/bijectors.py | 22 ++- jaxutils/dataset.py | 5 +- jaxutils/distributions.py | 4 +- jaxutils/fit.py | 11 +- jaxutils/module.py | 262 +++++------------------------ jaxutils/node.py | 194 ++++++++++++++++++++++ jaxutils/objective.py | 25 ++- jaxutils/pytree.py | 339 ++++++++++++++++++++++++++++++++++++++ setup.py | 15 +- tests/test_fit.py | 4 + tests/test_module.py | 201 +++++++++------------- 15 files changed, 877 insertions(+), 670 deletions(-) delete mode 100644 jaxutils/_meta.py create mode 100644 jaxutils/_module.py create mode 100644 jaxutils/node.py create mode 100644 jaxutils/pytree.py diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index 2f643da..3f5431d 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,14 +13,14 @@ # limitations under the License. # ============================================================================== -from .module import Module, constrain, param, static, unconstrain, stop_gradients +from .pytree import PyTree, static +from .module import Module, param from .bijectors import Bijector, Identity, Softplus from .objective import Objective from .dataset import Dataset from .fit import fit, get_batch from .scan import vscan - __authors__ = "Thomas Pinder, Daniel Dodd" __license__ = "MIT" __emails__ = "tompinder@live.co.uk, d.dodd1@lancaster.ac.uk" @@ -32,17 +32,15 @@ ) __all__ = [ + "PyTree", + "static", + "Module", + "param", "Bijector", "Identity", "Softplus", "Objective", "Dataset", - "Module", - "param", - "static", - "constrain", - "unconstrain", - "stop_gradients", "fit", "get_batch", "vscan", diff --git a/jaxutils/_meta.py b/jaxutils/_meta.py deleted file mode 100644 index 06a98cd..0000000 --- a/jaxutils/_meta.py +++ /dev/null @@ -1,276 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` metadata via the `jax.numpy` e.g. `.at` and `.set` syntax. - -The following classes mimic what is done in lax.numpy. -""" - -from __future__ import annotations -from typing import Callable, Any, Union, Sequence, Iterable -from jaxtyping import PyTree -import jax.tree_util as jtu - - -class _MetaUpdateRef: - - __slots__ = ( - "pytree", - "where", - ) - - def __init__(self, pytree: PyTree, where: Callable[[PyTree], PyTree]) -> None: - self.pytree = pytree - self.where = where - - def __repr__(self) -> str: - return f"_MetaUpdateRef({repr(self.pytree)}, {repr(self.where)})" - - def get(self, name: str = None, value: Any = None) -> PyTree: - if name is None: - return self.where( - jtu.tree_structure(self.pytree).unflatten(self.pytree.__meta__) - ) - - else: - return self.where( - jtu.tree_structure(self.pytree).unflatten( - [meta_.get(name, value) for meta_ in self.pytree.__meta__] - ) - ) - - def set(self, **kwargs) -> PyTree: - return _meta_at(where=self.where, pytree=self.pytree, replace=kwargs) - - def apply(self, func: Callable) -> PyTree: - return _meta_at(where=self.where, pytree=self.pytree, replace_fn=func) - - -class _MetaUpdateHelper: - """Helper class for updating a PyTree.""" - - __slots__ = ("pytree",) - - def __init__(self, pytree: PyTree) -> None: - self.pytree = pytree - - def __getitem__(self, where: Callable[[PyTree], PyTree]) -> _MetaUpdateRef: - return _MetaUpdateRef(self.pytree, _to_callable(where)) - - def __repr__(self) -> str: - return f"_MetaUpdateHelper({repr(self.pytree)})" - - -def _to_callable(where: Union[Callable, Sequence[str], Ellipsis]) -> Callable: - - if isinstance(where, str): - where = eval("lambda x: x." + where) - - if isinstance(where, Iterable): - - def _to_path(it: Iterable): - return "".join( - [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] - ) - - where = eval("lambda x: x" + _to_path(where)) - - if isinstance(where, type(Ellipsis)): - where = lambda x: x - - return where - - -from typing import Any -import jax.tree_util as jtu - -_Node = Any - - -class _LeafWrapper: - __slots__ = ("value",) - - def __init__(self, value: Any): - self.value = value - - -def _remove_leaf_wrapper(x: _LeafWrapper) -> Any: - assert type(x) is _LeafWrapper - return x.value - - -class _CountedIdDict: - - __slots__ = ("_dict",) - - def __init__(self, keys, values): - assert len(keys) == len(values) - self._dict = {id(k): (0, v) for k, v in zip(keys, values)} - - def __contains__(self, item): - return id(item) in self._dict - - def __getitem__(self, item): - c, v = self._dict[id(item)] - self._dict[id(item)] = (c + 1, v) - return v - - def get(self, item, default): - try: - return self[item] - except KeyError: - return default - - def count(self, item): - return self._dict[id(item)][0] - - -def _meta_map(f: Callable[..., Any], tree: PyTree) -> PyTree: - """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves.""" - leaves, treedef = jtu.tree_flatten(tree) - meta_leaves = tree.__meta__ - all_leaves = [leaves] + [meta_leaves] - return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) - - -# TODO: Rerwite this function to exploit flattened meta pytree structure -> This would be faster than the current implementation that has to unflatten the meta pytree for each leaf. -def _meta_at( - where, - pytree, - replace=None, - replace_fn=None, - is_leaf=lambda x: isinstance(x, dict), -): - """Adapted from Equinox's `tree_at`.""" - - # We need to specify a particular node in a PyTree. - # This is surprisingly difficult to do! As far as I can see, pretty much the only - # way of doing this is to specify e.g. `x.foo[0].bar` via `is`, and then pulling - # a few tricks to try and ensure that the same object doesn't appear multiple - # times in the same PyTree. - # - # So this first `tree_map` serves a dual purpose. - # 1) Makes a copy of the composite nodes in the PyTree, to avoid aliasing via - # e.g. `pytree=[(1,)] * 5`. This has the tuple `(1,)` appear multiple times. - # 2) It makes each leaf be a unique Python object, as it's wrapped in - # `_LeafWrapper`. This is needed because Python caches a few builtin objects: - # `assert 0 + 1 is 1`. I think only a few leaf types are subject to this. - # So point 1) should ensure that all composite nodes are unique Python objects, - # and point 2) should ensure that all leaves are unique Python objects. - # Between them, all nodes of `pytree` are handled. - # - # I think pretty much the only way this can fail is when using a custom node with - # singleton-like flatten+unflatten behaviour, which is pretty edge case. And we've - # added a check for it at the bottom of this function, just to be sure. - # - # Whilst we're here: we also double-check that `where` is well-formed and doesn't - # use leaf information. (As else `node_or_nodes` will be wrong.) - pytree_old = pytree - pytree = jtu.tree_structure(pytree).unflatten(pytree.__meta__) - - node_or_nodes_nowrapper = where(pytree) - pytree = jtu.tree_map(_LeafWrapper, pytree, is_leaf=is_leaf) - node_or_nodes = where(pytree) - leaves1, structure1 = jtu.tree_flatten(node_or_nodes_nowrapper, is_leaf=is_leaf) - leaves2, structure2 = jtu.tree_flatten(node_or_nodes) - leaves2 = [_remove_leaf_wrapper(x) for x in leaves2] - if ( - structure1 != structure2 - or len(leaves1) != len(leaves2) - or any(l1 is not l2 for l1, l2 in zip(leaves1, leaves2)) - ): - raise ValueError( - "`where` must use just the PyTree structure of `pytree`. `where` must not " - "depend on the leaves in `pytree`." - ) - del node_or_nodes_nowrapper, leaves1, structure1, leaves2, structure2 - - # Normalise whether we were passed a single node or a sequence of nodes. - in_pytree = False - - def _in_pytree(x): - nonlocal in_pytree - if x is node_or_nodes: # noqa: F821 - in_pytree = True - return x # needed for jax.tree_util.Partial, which has a dodgy constructor - - jtu.tree_map(_in_pytree, pytree, is_leaf=lambda x: x is node_or_nodes) # noqa: F821 - - if in_pytree: - nodes = (node_or_nodes,) - if replace is not None: - replace = (replace,) - else: - nodes = node_or_nodes - del in_pytree, node_or_nodes - - # Normalise replace vs replace_fn - if replace is None: - if replace_fn is None: - raise ValueError( - "Precisely one of `replace` and `replace_fn` must be specified." - ) - else: - - def _replace_fn(x): - x = jtu.tree_map(_remove_leaf_wrapper, x) - return replace_fn(x) - - replace_fns = [_replace_fn] * len(nodes) - else: - if replace_fn is None: - - # TODO: Need to fix this. - def _replace_fn(x, i): - x = jtu.tree_map(_remove_leaf_wrapper, x) - - for k, v in replace.items(): - - # if len(nodes) != len(v): - # raise ValueError( - # "`where` must return a sequence of leaves of the same length as " - # "`replace`." - # ) - - try: - value = v[i] - except: - TypeError - value = v - - x.update({k: value}) - - return x - - replace_fns = [lambda x, i=i: _replace_fn(x, i) for i in range(len(nodes))] - else: - raise ValueError( - "Precisely one of `replace` and `replace_fn` must be specified." - ) - node_replace_fns = _CountedIdDict(nodes, replace_fns) - - # Actually do the replacement - def _make_replacement(x: _Node) -> Any: - return node_replace_fns.get(x, _remove_leaf_wrapper)(x) - - out = jtu.tree_map( - _make_replacement, pytree, is_leaf=lambda x: x in node_replace_fns - ) - - print(out) - - new = pytree_old.__set_meta_func__(lambda _: jtu.tree_leaves(out, is_leaf=is_leaf)) - - return new diff --git a/jaxutils/_module.py b/jaxutils/_module.py new file mode 100644 index 0000000..6bfa96b --- /dev/null +++ b/jaxutils/_module.py @@ -0,0 +1,129 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" +from typing import Sequence, Callable, Union, Iterable +from .module import Module +from .pytree import PyTree +from .node import node_at + + +def _to_callable( + where: Union[Callable[[Module], Sequence[Module]], Sequence[str], Ellipsis] +) -> Callable[[Module], Sequence[Module]]: + + if isinstance(where, str): + where = eval("lambda x: x." + where) + + if isinstance(where, Iterable): + + def _to_path(it: Iterable): + return "".join( + [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] + ) + + where = eval("lambda x: x" + _to_path(where)) + + if isinstance(where, type(Ellipsis)): + where = lambda x: x + + return where + + +class _ModuleNodeUpdateRef: + + __slots__ = ( + "module", + "where", + ) + + def __init__(self, module: Module, where: Union[Callable, Sequence[str]]) -> None: + self.module = module + self.where = where + + def __repr__(self) -> str: + return f"_ModuleNodeUpdateRef({repr(self.module)}, {repr(self.where)})" + + def get(self) -> PyTree: + return self.where(self.pytree) + + def set(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._replace(**kwargs), + node_type=Module, + ) + + def set_meta(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._replace_meta(**kwargs), + node_type=Module, + ) + + def update_meta(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._update_meta(**kwargs), + node_type=Module, + ) + + def trainables(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._replace_trainables(**kwargs), + node_type=Module, + ) + + def bijectors(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._replace_bijectors(**kwargs), + node_type=Module, + ) + + def priors(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.module, + replace_fn=lambda node: node._replace_priors(**kwargs), + node_type=Module, + ) + + +class _ModuleNodeUpdateHelper: + """Helper class for updating a PyTree.""" + + __slots__ = ("module",) + + def __init__(self, module: Module) -> None: + self.module = module + + def __getitem__( + self, + where: Union[Callable[[Module], Sequence[Module]], Sequence[str], Ellipsis], + ) -> _ModuleNodeUpdateRef: + + where = _to_callable(where) + + return _ModuleNodeUpdateRef(self.module, where) + + def __repr__(self) -> str: + return f"_ModuleNodeUpdateHelper({repr(self.module)})" diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py index 6424a02..84a31ba 100644 --- a/jaxutils/_pytree.py +++ b/jaxutils/_pytree.py @@ -16,12 +16,12 @@ """This non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" from __future__ import annotations -from typing import Any, Sequence, Callable, Union, Iterable -from jaxtyping import PyTree -from equinox import tree_at +from typing import Sequence, Callable, Union, Iterable +from .pytree import PyTree +from .node import node_at -class _PyTreeUpdateRef: +class _PyTreeNodeUpdateRef: __slots__ = ( "pytree", @@ -38,14 +38,29 @@ def __repr__(self) -> str: def get(self) -> PyTree: return self.where(self.pytree) - def set(self, values: Any) -> PyTree: - return tree_at(where=self.where, pytree=self.pytree, replace=values) - - def apply(self, func: Callable) -> PyTree: - return tree_at(where=self.where, pytree=self.pytree, replace_fn=func) - - -class _PyTreeUpdateHelper: + def replace(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.pytree, + replace_fn=lambda node: node._replace(**kwargs), + ) + + def replace_meta(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.pytree, + replace_fn=lambda node: node._replace_meta(**kwargs), + ) + + def update_meta(self, **kwargs) -> PyTree: + return node_at( + where=self.where, + pytree=self.pytree, + replace_fn=lambda node: node._update_meta(**kwargs), + ) + + +class _PyTreeNodeUpdateHelper: """Helper class for updating a PyTree.""" __slots__ = ("pytree",) @@ -54,8 +69,9 @@ def __init__(self, pytree: PyTree) -> None: self.pytree = pytree def __getitem__( - self, where: Union[Callable, Sequence[str], Ellipsis] - ) -> _PyTreeUpdateRef: + self, + where: Union[Callable[[PyTree], Sequence[PyTree]], Sequence[str], Ellipsis], + ) -> _PyTreeNodeUpdateRef: if isinstance(where, str): where = eval("lambda x: x." + where) @@ -75,7 +91,7 @@ def _to_path(it: Iterable): if isinstance(where, type(Ellipsis)): where = lambda x: x - return _PyTreeUpdateRef(self.pytree, where) + return _PyTreeNodeUpdateRef(self.pytree, where) def __repr__(self) -> str: return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/bijectors.py b/jaxutils/bijectors.py index c9401f2..acecef4 100644 --- a/jaxutils/bijectors.py +++ b/jaxutils/bijectors.py @@ -15,11 +15,12 @@ """Bijectors for use in model optimisation.""" import jax.numpy as jnp -import equinox as eqx from typing import Callable +from .pytree import PyTree, static -class Bijector(eqx.Module): + +class Bijector(PyTree): """Base class for parameter bijector transformations. These are useful for model optimisation, where gradients are taken in the "unconstrained" (real) parameter space, while evaluating the model takes place in the "constrained" parameter space. @@ -36,8 +37,21 @@ class Bijector(eqx.Module): Adding log_det_jacobian's etc., is on the TODO list of this class. """ - forward: Callable = eqx.static_field() - inverse: Callable = eqx.static_field() + forward: Callable = static() + inverse: Callable = static() + + def __init__(self, forward: Callable, inverse: Callable) -> None: + """Initialise the bijector. + + Args: + forward(Callable): The forward transformation. + inverse(Callable): The inverse transformation. + + Returns: + Bijector: A bijector. + """ + self.forward = forward + self.inverse = inverse """Identity bijector.""" diff --git a/jaxutils/dataset.py b/jaxutils/dataset.py index 3f6d702..fc017c0 100644 --- a/jaxutils/dataset.py +++ b/jaxutils/dataset.py @@ -17,11 +17,10 @@ import jax.numpy as jnp from jaxtyping import Array, Float from typing import Optional +from .pytree import PyTree -import equinox as eqx - -class Dataset(eqx.Module): +class Dataset(PyTree): """Base class for datasets.""" X: Optional[Float[Array, "N D"]] = None diff --git a/jaxutils/distributions.py b/jaxutils/distributions.py index 6999938..3cb2aef 100644 --- a/jaxutils/distributions.py +++ b/jaxutils/distributions.py @@ -13,10 +13,10 @@ # limitations under the License. # ============================================================================== -import equinox as eqx +from .pytree import PyTree -class Distribution(eqx.Module): +class Distribution(PyTree): """Base class for distributions.""" diff --git a/jaxutils/fit.py b/jaxutils/fit.py index f9eb0f5..350041c 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -24,7 +24,7 @@ from jaxtyping import Array, Float from typing import Any -from .module import Module, constrain, unconstrain, stop_gradients +from .module import Module from .dataset import Dataset from .objective import Objective from .scan import vscan @@ -107,12 +107,11 @@ def fit( # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: - model = stop_gradients(model) - model = constrain(model) - return objective(model, batch) + with model.stop_gradients() as model: + return objective(model.constrain(), batch) # Unconstrained space model. - model = unconstrain(model) + model = model.unconstrain() # Initialise optimiser state. state = optim.init(model) @@ -143,7 +142,7 @@ def step(carry, key): (model, _), history = scan(step, (model, state), (iter_keys), unroll=unroll) # Constrained space. - model = constrain(model) + model = model.constrain() return model, history diff --git a/jaxutils/module.py b/jaxutils/module.py index a3294f7..958c5c2 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -14,23 +14,17 @@ # ============================================================================== from __future__ import annotations - import jax -import equinox - from jax import lax -from dataclasses import fields, field -from typing import Any, Callable, Tuple, List, Dict - -from .bijectors import Bijector, Identity +from dataclasses import field +from typing import Any, Dict from .distributions import Distribution -from ._pytree import _PyTreeUpdateHelper -from ._meta import _MetaUpdateHelper, _meta_map -from ._cached import _cached_static_property +from .bijectors import Bijector, Identity +from .pytree import PyTree, _metadata_map def param( - transform: Bijector, + bijector: Bijector, trainable: bool = True, prior: Distribution = None, **kwargs: Any, @@ -95,9 +89,9 @@ def param( metadata = dict(kwargs["metadata"]) except KeyError: metadata = kwargs["metadata"] = {} - if "transform" in metadata: - raise ValueError("Cannot use metadata with `transform` already set.") - metadata["transform"] = transform + if "bijector" in metadata: + raise ValueError("Cannot use metadata with `bijector` already set.") + metadata["bijector"] = bijector if "trainable" in metadata: raise ValueError("Cannot use metadata with `trainable` already set.") metadata["trainable"] = trainable @@ -111,58 +105,7 @@ def param( return field(**kwargs) -def static(**kwargs: Any): - """Alias of `equinox.static_field`. Provided for convenience. - - Used for marking that a field should _not_ be treated as a leaf of the PyTree - of a `jaxutils.Module`/ `equinox.Module`. (And is instead treated as part of the structure, i.e. - as extra metadata.) - - Example: - This example shows us creating a module with a static field, and then flattening the module. - - >>> import jaxutils as ju - >>> - >>> class MyModule(ju.Module): - >>> normal_field: int - >>> static_field: int = ju.static() - >>> - >>> mymodule = MyModule("normal", "static") - >>> leaves, treedef = jax.tree_flatten(mymodule) - >>> print(leaves) - ['normal'] - >>> print(treedef) - PyTreeDef(, {'static_field': *}) - >>> - >>> # The same example using `equinox.static_field` - >>> import equinox as eq - >>> - >>> class MyModule(ju.Module): - >>> normal_field: int - >>> static_field: int = eq.static_field() - >>> - >>> mymodule = MyModule("normal", "static") - >>> leaves, treedef = jax.tree_flatten(mymodule) - >>> print(leaves) - ['normal'] - >>> print(treedef) - PyTreeDef(, {'static_field': *}) - - Args: - **kwargs (Any): If any are passed then they are passed on to `dataclass.field`. - (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) - """ - try: - metadata = dict(kwargs["metadata"]) - except KeyError: - metadata = kwargs["metadata"] = {} - if "static" in metadata: - raise ValueError("Cannot use metadata with `static` already set.") - metadata["static"] = True - return field(**kwargs) - - -def constrain(obj: Module) -> Module: +def _constrain(obj: Module) -> Module: """Transform model parameters to the constrained space according to their defined bijectors. Example: @@ -198,12 +141,12 @@ def constrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the constrained space. """ - return _meta_map( - lambda leaf, meta: meta.get("transform", Identity).forward(leaf), obj + return _metadata_map( + lambda leaf, meta: meta.get("bijector", Identity).forward(leaf), obj ) -def unconstrain(obj: Module) -> Module: +def _unconstrain(obj: Module) -> Module: """Transform model parameters to the unconstrained space according to their defined bijectors. Example: @@ -239,12 +182,12 @@ def unconstrain(obj: Module) -> Module: Returns: Module: PyTree tranformed to the unconstrained space. """ - return _meta_map( - lambda leaf, meta: meta.get("transform", Identity).inverse(leaf), obj + return _metadata_map( + lambda leaf, meta: meta.get("bijector", Identity).inverse(leaf), obj ) -def stop_gradients(obj: Module) -> Module: +def _stop_gradients(obj: Module) -> Module: """ Stop the gradients flowing through parameters whose trainable status is False. This is useful for stopping parameters from being updated during training. @@ -281,45 +224,17 @@ def stop_gradients(obj: Module) -> Module: Returns: Module: PyTree with gradients stopped. """ - # TODO: Remove the tree_map and work with the leaves directly. - # This is since object metadata already comprises flattened leaves. def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: """Stop gradients flowing through a given leaf if it is not trainable.""" return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - return _meta_map( + return _metadata_map( lambda leaf, meta: _stop_grad(leaf, meta.get("trainable", True)), obj ) -# TODO: Rewrite this as a generator. -def _default_meta(obj: Module) -> tuple[Dict]: - meta = [] - - for field_, node_ in ( - [f, getattr(obj, f.name)] - for f in obj.__dataclass_fields__.values() - if not f.metadata.get("static", False) - ): - - if isinstance(node_, Module): - for meta_ in _default_meta(node_): - meta.append(meta_) - - elif isinstance(node_, list) | isinstance(node_, tuple): - for item in node_: - for meta_ in _default_meta(item): - meta.append(meta_) - else: - meta.append( - {**field_.metadata} - ) # Have to do this otherwise can't pickle the Module. - - return meta - - -class Module(equinox.Module): +class Module(PyTree): """Base Module object. This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), @@ -345,124 +260,29 @@ class Module(equinox.Module): All attributes of the Module must be marked with either a `param` or `static` field or the attributes type needs to be subclass of `jaxutils.Module`. """ - def __new__( - cls, - *args: Any, - __meta_func__: Callable[[Module], List[Dict]] = _default_meta, - **kwargs: Any, - ) -> Module: - """This method is defined to set the `__meta__` attribute (as we are working with frozen dataclasses!). - - Args: - *args (Any): Arguments. - __meta_func__ (Callable[[Module], List[Dict]], optional): Function to generate the Module's meta. Defaults to _default_meta. - **kwargs (Any): Keyword arguments. - - Returns: - Module. An instance of the `jaxutils.Module`. - """ - obj = super().__new__(cls) - object.__setattr__(obj, "__meta_func__", __meta_func__) - return obj - - @_cached_static_property - def __meta__(self) -> List[Dict]: - """Return the Module's meta. - - Returns: - _Meta: The Module's meta. - """ - return self.__meta_func__(self) - - def __set_meta_func__( - self, __meta_func__: Callable[[Module], List[Dict]] - ) -> Module: - """Set function that generates parameter meta through a new Module instance. - - Example: - TODO! - - Args: - __meta_func__ (Callable[[Module], List[Dict]]): Function to generate the Module's meta. - - Returns: - Module: A new instance of the Module with updated meta. - """ - cls = self.__class__ - - new = cls.__new__( - cls=cls, - __meta_func__=__meta_func__, - ) - - for field_ in fields(self): - object.__setattr__(new, field_.name, self.__dict__[field_.name]) - - return new - - def tree_flatten(self) -> Tuple[Tuple, Tuple]: - """Identical to that of Equinox, except for the addition of a meta component. - - Returns: - Tuple: A tuple of the Module's dynamic and static fields. - """ - dynamic_field_names = [] - dynamic_field_values = [] - static_field_names = [] - static_field_values = [] - - for field_ in fields(self): - name = field_.name - try: - value = self.__dict__[name] - except KeyError: - continue - if field_.metadata.get("static", False): - static_field_names.append(name) - static_field_values.append(value) - else: - dynamic_field_names.append(name) - dynamic_field_values.append(value) - - return tuple(dynamic_field_values), ( - tuple(dynamic_field_names), - tuple(static_field_names), - tuple(static_field_values), - self.__meta__, - ) - - @classmethod - def tree_unflatten(cls, aux: Tuple, dynamic_field_values: Tuple) -> Module: - """Identical to that of Equinox, except for the addition of a meta component. - - Args: - aux (Tuple): Auxiliary data. - dynamic_field_values (Tuple): Dynamic field values. - - Returns: - Module: An instance of the `jaxutils.Module` class. - """ - dynamic_field_names, static_field_names, static_field_values, meta = aux - - self = cls.__new__( - cls=cls, - __meta_func__=lambda _: meta, - ) - - for name, value in zip(dynamic_field_names, dynamic_field_values): - object.__setattr__(self, name, value) - for name, value in zip(static_field_names, static_field_values): - object.__setattr__(self, name, value) - - return self + def _replace_trainables(self, **kwargs: Dict[str, bool]) -> Module: + _meta_wrapper = {k: {"trainable": v} for k, v in kwargs.items()} + return self._update_meta(**_meta_wrapper) + + def _replace_bijectors(self, **kwargs: Dict[str, Bijector]) -> Module: + _meta_wrapper = {k: {"bijector": v} for k, v in kwargs.items()} + return self._update_meta(**_meta_wrapper) + + def _replace_priors(self, **kwargs: Dict[str, Distribution]) -> Module: + _meta_wrapper = {k: {"prior": v} for k, v in kwargs.items()} + return self._update_meta(**_meta_wrapper) @property - def tree_at(self): - return _PyTreeUpdateHelper(self) + def at(self): + from ._module import _ModuleNodeUpdateHelper + + return _ModuleNodeUpdateHelper(self) @property - def meta_at(self): - return _MetaUpdateHelper(self) + def module_at(self): + from ._module import _ModuleNodeUpdateHelper + + return _ModuleNodeUpdateHelper(self) def training_transforms(self): class _ConstrainHelper: @@ -473,18 +293,18 @@ def __init__(self, module): self.module = module def __enter__(self): - return constrain(self.module) + return self.module.constrain() def __exit__(self, *args): - return unconstrain(self.module) + return True return _ConstrainHelper(self) def constrain(self): - return constrain(self) + return _constrain(self) def unconstrain(self): - return unconstrain(self) + return _unconstrain(self) def stop_gradients(self): class _StopGradientsHelper: @@ -495,7 +315,7 @@ def __init__(self, module): self.module = module def __enter__(self): - return stop_gradients(self.module) + return _stop_gradients(self.module) def __exit__(self, *args): return True diff --git a/jaxutils/node.py b/jaxutils/node.py new file mode 100644 index 0000000..a0e58eb --- /dev/null +++ b/jaxutils/node.py @@ -0,0 +1,194 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" + +from __future__ import annotations +from typing import Any, Callable, Sequence, TypeVar +import jax.tree_util as jtu +from .pytree import PyTree + +NodeType = TypeVar("NodeType", bound=PyTree) + + +class _LeafWrapper: + __slots__ = ("value",) + + def __init__(self, value: Any): + self.value = value + + +def _remove_leaf_wrapper(x: _LeafWrapper) -> Any: + assert type(x) is _LeafWrapper + return x.value + + +class _CountedIdDict: + __slots__ = ( + "_dict", + "_count", + ) + + def __init__(self, keys, values): + assert len(keys) == len(values) + self._dict = {id(k): v for k, v in zip(keys, values)} + self._count = {id(k): 0 for k in keys} + + def __contains__(self, item): + return id(item) in self._dict + + def __getitem__(self, item): + self._count[id(item)] += 1 + return self._dict[id(item)] + + def get(self, item, default): + try: + return self[item] + except KeyError: + return default + + def count(self, item): + return self._count[id(item)] + + +# TODO: Clean up the inside code of this function. +def node_at( + where: Callable[[NodeType], Sequence[NodeType]], + pytree: PyTree, + replace: Sequence[Any] = None, + replace_fn: Callable[[NodeType], Any] = None, + node_type: NodeType = PyTree, +): + """Update a PyTree node or nodes in-place. + + Args: + where (Callable[[NodeType], Sequence[NodeType]]): A function that takes a node of type `node_type` and returns a sequence of nodes of type `node_type`. + pytree (PyTree): The PyTree to update. + replace (Sequence[Any]): A sequence of leaves to replace the nodes returned by `where`. Must be specified if `replace_fn` is not specified. + replace_fn (Callable[[NodeType], Any]): A function that takes a node of type `node_type` and returns a leaf to replace the node. Must be specified if `replace` is not specified. + node_type (NodeType): The type of the nodes to update. Defaults to `PyTree`. + + Returns: + PyTree: The updated PyTree. + + Acknowledgements: + Adapted from Equinox's `tree_at`. + """ + is_leaf = lambda x: isinstance(x, node_type) and not pytree + + node_or_nodes_nowrapper = where(pytree) + pytree = jtu.tree_map(_LeafWrapper, pytree, is_leaf=is_leaf) + node_or_nodes = where(pytree) + leaves1, structure1 = jtu.tree_flatten(node_or_nodes_nowrapper, is_leaf=is_leaf) + leaves2, structure2 = jtu.tree_flatten(node_or_nodes) + leaves2 = [_remove_leaf_wrapper(x) for x in leaves2] + if ( + structure1 != structure2 + or len(leaves1) != len(leaves2) + or any(l1 is not l2 for l1, l2 in zip(leaves1, leaves2)) + ): + raise ValueError( + "`where` must use just the PyTree structure of `pytree`. `where` must not " + "depend on the leaves in `pytree`." + ) + del node_or_nodes_nowrapper, leaves1, structure1, leaves2, structure2 + + # Normalise whether we were passed a single node or a sequence of nodes. + in_pytree = False + + def _in_pytree(x): + nonlocal in_pytree + if x is node_or_nodes: # noqa: F821 + in_pytree = True + return x # needed for jax.tree_util.Partial, which has a dodgy constructor + + jtu.tree_map(_in_pytree, pytree, is_leaf=lambda x: x is node_or_nodes) # noqa: F821 + + if in_pytree: + nodes = (node_or_nodes,) + if replace is not None: + replace = (replace,) + else: + nodes = node_or_nodes + + del in_pytree, node_or_nodes + + # Checks on the where to ensure the node maps to another PyTree. + for num, node in enumerate(nodes): + if not isinstance(node, node_type): + raise ValueError( + f"Node number {num} in the `where` sequence is not of type node_type={node_type.__name__}." + ) + + # Normalise replace vs replace_fn + if replace is None: + if replace_fn is None: + raise ValueError( + "Precisely one of `replace` and `replace_fn` must be specified." + ) + else: + + def _replace_fn(x): + x = jtu.tree_map(_remove_leaf_wrapper, x) + return replace_fn(x) + + replace_fns = [_replace_fn] * len(nodes) + else: + if replace_fn is None: + if len(nodes) != len(replace): + raise ValueError( + "`where` must return a sequence of leaves of the same length as " + "`replace`." + ) + replace_fns = [lambda _, r=r: r for r in replace] + else: + raise ValueError( + "Precisely one of `replace` and `replace_fn` must be specified." + ) + node_replace_fns = _CountedIdDict(nodes, replace_fns) + + # Actually do the replacement + def _make_replacement(x: NodeType) -> Any: + return node_replace_fns.get(x, _remove_leaf_wrapper)(x) + + out = jtu.tree_map( + _make_replacement, pytree, is_leaf=lambda x: x in node_replace_fns + ) + + # Check that `where` is well-formed. + for node in nodes: + count = node_replace_fns.count(node) + if count == 0: + raise ValueError( + "`where` does not specify an element or elements of `pytree`." + ) + elif count == 1: + pass + else: + raise ValueError( + "`where` does not uniquely identify a single element of `pytree`. This " + "usually occurs when trying to replace a `None` value:\n" + "\n" + " >>> eqx.tree_at(lambda t: t[0], (None, None, 1), True)\n" + "\n" + "\n" + "for which the fix is to specify that `None`s should be treated as " + "leaves:\n" + "\n" + " >>> eqx.tree_at(lambda t: t[0], (None, None, 1), True,\n" + " ... is_leaf=lambda x: x is None)" + ) + + return out diff --git a/jaxutils/objective.py b/jaxutils/objective.py index bdf2600..f8fd01f 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -14,13 +14,15 @@ # ============================================================================== import abc -import equinox as eqx +from dataclasses import field +from jaxtyping import Float, Array +from .pytree import PyTree from .dataset import Dataset from .module import Module -class Objective(eqx.Module): +class Objective(PyTree): """Base class for objective functions. !!! example @@ -34,8 +36,8 @@ def evaluate(self, model, train_data): The objective function is negated if `negative=True`. """ - negative: bool = eqx.static_field() - constant: float = eqx.static_field() + negative: bool = field(metadata={"static": True}) + constant: float = field(metadata={"static": True}) def __init__(self, negative: bool = False): """Initialise the objective function. @@ -53,7 +55,7 @@ def __init__(self, negative: bool = False): self.negative = negative self.constant = -1.0 if negative else 1.0 - def __call__(self, model: Module, train_data: Dataset) -> float: + def __call__(self, model: Module, train_data: Dataset) -> Float[Array, "1"]: """Evaluate the objective function. Args: @@ -67,8 +69,17 @@ def __call__(self, model: Module, train_data: Dataset) -> float: return self.constant * self.evaluate(model, train_data) @abc.abstractmethod - def evaluate(self, model: Module, train_data: Dataset) -> float: - """Evaluate the objective function.""" + def evaluate(self, model: Module, train_data: Dataset) -> Float[Array, "1"]: + """Evaluate the objective function. + + Args: + model(Base): A model. + *args: Additional arguments. + **kwargs: Additional keyword arguments. + + Returns: + float: The objective function. + """ __all__ = [ diff --git a/jaxutils/pytree.py b/jaxutils/pytree.py new file mode 100644 index 0000000..8112b88 --- /dev/null +++ b/jaxutils/pytree.py @@ -0,0 +1,339 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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 is based on the simple-pytree package by @cgarciae. Adapted to use static field convention of Equinox, and added metadata functionality.""" + +from __future__ import annotations + +import dataclasses +from dataclasses import field +from abc import ABCMeta +from typing import Any, Set, Dict, List, Callable +from copy import copy, deepcopy + +import jax +import jax.tree_util as jtu + + +def static(**kwargs: Any): + """Alias of `equinox.static_field`. Provided for convenience. + + Used for marking that a field should _not_ be treated as a leaf of the PyTree + of a `jaxutils.Module`/ `equinox.Module`. (And is instead treated as part of the structure, i.e. + as extra metadata.) + + Example: + + Args: + **kwargs (Any): If any are passed then they are passed on to `dataclass.field`. + (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) + """ + try: + metadata = dict(kwargs["metadata"]) + except KeyError: + metadata = kwargs["metadata"] = {} + if "static" in metadata: + raise ValueError("Cannot use metadata with `static` already set.") + metadata["static"] = True + return field(**kwargs) + + +class PyTreeMeta(ABCMeta): + """Metaclass for PyTree.""" + + def __call__(self, *args: Any, **kwds: Any): + obj: PyTree = super().__call__(*args, **kwds) + object.__setattr__(obj, "_pytree__initialized", True) + return obj + + +class PyTree(metaclass=PyTreeMeta): + _pytree__initialized: bool + _pytree__static_fields: Set[str] + _pytree__class_is_mutable: bool + _pytree__meta: Dict[str, Any] + _pytree__annotations: List[str] + _pytree__is_leaf: Dict[str:bool] + _pytree__metatree_leaves: List[Dict[str:Any]] + + def __init_subclass__(cls, mutable: bool = False): + jtu.register_pytree_node( + cls, + flatten_func=tree_flatten, + unflatten_func=lambda *_args: tree_unflatten(cls, *_args), + ) + + class_annotations = _get_all_annotations(cls) + + # init class variables + cls._pytree__initialized = False # initialize mutable + cls._pytree__static_fields = set() + cls._pytree__class_is_mutable = mutable + cls._pytree__meta = {} + cls._pytree__annotations = class_annotations + cls._pytree__is_leaf = {} + cls._pytree__metatree_leaves = [] + + # get class info + class_vars = _get_all_class_vars(cls) + + for field, value in class_vars.items(): + + if "_pytree__" in field or ( + isinstance(value, dataclasses.Field) + and value.metadata is not None + and value.metadata.get("static", False) + ): + + cls._pytree__static_fields.add(field) + + elif isinstance(value, dataclasses.Field) and value.metadata is not None: + cls._pytree__meta[field] = {**value.metadata} + + for field in class_annotations: + if "_pytree__" not in field and ( + field not in cls._pytree__static_fields + and field not in cls._pytree__meta.keys() + ): + cls._pytree__meta[field] = {} + + @property + def _metatree_leaves(self) -> List[Dict[str, Any]]: + return _unpack_metatree_leaves(self) + + @property + def _metatree(self) -> Dict[str, Any]: + return jtu.tree_structure(self).unflatten(self._metatree_leaves) + + @property + def pytree_at(self): + from ._pytree import _PyTreeNodeUpdateHelper + + return _PyTreeNodeUpdateHelper(self) + + def _replace_meta(self, **kwargs: Any) -> PyTree: + """ + Replace the values of the fields of the object with the values of the + keyword arguments. If the object is a dataclass, `dataclasses.replace` + will be used. Otherwise, a new object will be created with the same + type as the original object. + """ + for key in kwargs: + if key not in self._pytree__meta.keys(): + raise ValueError(f"'{key}' is not a leaf of {type(self).__name__}") + + pytree = copy(self) + pytree.__dict__.update(_pytree__meta={**pytree._pytree__meta, **kwargs}) + return pytree + + def _update_meta(self, **kwargs: Any) -> PyTree: + """ + Replace the values of the fields of the object with the values of the + keyword arguments. If the object is a dataclass, `dataclasses.replace` + will be used. Otherwise, a new object will be created with the same + type as the original object. + """ + for key in kwargs: + if key not in self._pytree__meta.keys(): + raise ValueError( + f"'{key}' is not an attribute of {type(self).__name__}" + ) + + # TODO: Simplify. + pytree = copy(self) + new = deepcopy(pytree._pytree__meta) + for key in kwargs: + if key in new: + new[key].update(kwargs[key]) + else: + new[key] = kwargs[key] + pytree.__dict__.update(_pytree__meta=new) + return pytree + + def _replace(self: PyTree, **kwargs: PyTree) -> PyTree: + """ + Replace the values of the fields of the object with the values of the + keyword arguments. If the object is a dataclass, `dataclasses.replace` + will be used. Otherwise, a new object will be created with the same + type as the original object. + """ + if dataclasses.is_dataclass(self): + return dataclasses.replace(self, **kwargs) + + fields = vars(self) + for key in kwargs: + if key not in fields: + raise ValueError(f"'{key}' is not a field of {type(self).__name__}") + + pytree = copy(self) + pytree.__dict__.update(kwargs) + return pytree + + def __setattr__(self, field: str, value: Any): + + if field not in self._pytree__annotations: + raise AttributeError(f"{type(self)} has no annotation field {field}.") + + if self._pytree__initialized and not self._pytree__class_is_mutable: + raise AttributeError( + f"{type(self)} is immutable, trying to update field {field}." + ) + + _field_is_static = field in self._pytree__static_fields + _value_is_pytree = ( + jtu.tree_map( + lambda x: isinstance(x, PyTree), + value, + is_leaf=lambda x: isinstance(x, PyTree), + ) + == False + ) + _is_leaf = _value_is_pytree and not _field_is_static + object.__setattr__( + self, "_pytree__is_leaf", {**self._pytree__is_leaf, field: _is_leaf} + ) + object.__setattr__(self, field, value) + + if not _is_leaf and field not in self._pytree__static_fields: + + def _unpack_pytree__meta(value): + if isinstance(value, PyTree): + return value._pytree__meta + else: + return value + + _meta = jtu.tree_map( + _unpack_pytree__meta, value, is_leaf=lambda x: isinstance(x, PyTree) + ) + object.__setattr__(self, "_pytree__metatree_leaves", _meta) + + +def tree_flatten(pytree: PyTree): + node_fields = {} + static_fields = {} + + for field, value in vars(pytree).items(): + if field in pytree._pytree__static_fields: + static_fields[field] = value + else: + node_fields[field] = value + + return (node_fields,), static_fields + + +def tree_unflatten(cls: PyTree, static_fields, children): + """ + Unflattens a PyTree. + + Args: + cls (PyTree): Class to unflatten. + + Returns: + PyTree: Unflattened PyTree. + """ + (node_fields,) = children + pytree = cls.__new__(cls) + pytree.__dict__.update(node_fields, **static_fields) + return pytree + + +def _get_all_class_vars(cls: type) -> Dict[str, Any]: + """ + Returns a dictionary of all the class variables of a class. + + Args: + cls (type): Class to get the class variables of. + + Returns: + Dict[str, Any]: Dictionary of all the class variables of the class. + """ + d = {} + for c in reversed(cls.mro()): + if hasattr(c, "__dict__"): + d.update(vars(c)) + return d + + +def _get_all_annotations(cls: type) -> Dict[str, type]: + """ + Returns a dictionary of all the annotations of a class. + + Args: + cls (type): Class to get the annotations of. + + Returns: + Dict[str, type]: Dictionary of all the annotations of the class. + """ + d = {} + for c in reversed(cls.mro()): + if hasattr(c, "__annotations__"): + d.update(**c.__annotations__) + return d + + +def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: + """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. + + Args: + f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. + pytree (PyTree): The pytree to apply the function to. + + Returns: + PyTree: The transformed pytree. + """ + leaves, treedef = jtu.tree_flatten(pytree) + meta_leaves = _unpack_metatree_leaves(pytree) + all_leaves = [leaves] + [meta_leaves] + return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) + + +def _unpack_metatree_leaves(pytree: PyTree) -> List[Dict[str, Any]]: + """ + Returns a list of the PyTree leaves' metadata. + + Args: + pytree (PyTree): PyTree to get the metadata of the leaves. + + Returns: + List[Dict[str, Any]]: List of the PyTree leaves' metadata. + """ + _leaf_metadata = [ + pytree._pytree__meta[k] + for k, _is_leaf_bool in pytree._pytree__is_leaf.items() + if _is_leaf_bool + ] + + def _nested_unpack_metadata(pytree: PyTree, *rest: PyTree) -> None: + if isinstance(pytree, PyTree): + _leaf_metadata.extend( + [ + pytree._pytree__meta[k] + for k, _is_leaf_bool in pytree._pytree__is_leaf.items() + if _is_leaf_bool + ] + ) + _unpack_metadata(pytree, *rest) + + def _unpack_metadata(pytree: PyTree, *rest: PyTree) -> None: + pytrees = (pytree,) + rest + _ = jax.tree_map( + _nested_unpack_metadata, + *pytrees, + is_leaf=lambda x: isinstance(x, PyTree) and not x in pytrees, + ) + + _unpack_metadata(pytree) + + return _leaf_metadata diff --git a/setup.py b/setup.py index 1d94e8c..4ca6b40 100644 --- a/setup.py +++ b/setup.py @@ -38,14 +38,13 @@ def get_versions(): versioneer.get_versions = get_versions -REQUIRES = ["jax>=0.4.0", - "jaxlib>=0.4.0", - "jaxtyping", - "ml-collections==0.1.0", - "equinox", - "optax", - "tqdm", - ] +REQUIRES = [ + "jax>=0.4.0", + "jaxlib>=0.4.0", + "jaxtyping", + "optax", + "tqdm", +] EXTRAS = { "dev": [ diff --git a/tests/test_fit.py b/tests/test_fit.py index ecf989f..4e3c255 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -35,6 +35,10 @@ class LinearModel(Module): weight: float = param(Identity) bias: float = param(Identity) + def __init__(self, weight: float, bias: float): + self.weight = weight + self.bias = bias + def __call__(self, x): return self.weight * x + self.bias diff --git a/tests/test_module.py b/tests/test_module.py index 1d98597..2f3cf4f 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,26 +14,29 @@ # ============================================================================== import jax.numpy as jnp -from jaxutils.module import Module, constrain, param, unconstrain, stop_gradients +from jaxutils.pytree import static +from jaxutils.module import Module, param from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu import jax from typing import Any +from dataclasses import dataclass import jax.tree_util as jtu import pytest -import equinox as eqx def test_module(): # Test init + @dataclass class SubTree(Module): param_c: float = param(Identity) param_d: float = param(Softplus) param_e: float = param(Softplus) + @dataclass class Tree(Module): param_a: float = param(Identity) sub_tree: SubTree @@ -46,12 +49,7 @@ class Tree(Module): ) assert isinstance(tree, Module) - assert isinstance(tree.meta_at[...].get("trainable"), Module) - assert isinstance(tree.meta_at[...].get("transform"), Module) - assert isinstance(tree, eqx.Module) - assert isinstance(tree.meta_at[...].get("trainable"), eqx.Module) - assert isinstance(tree.meta_at[...].get("transform"), eqx.Module) - + assert isinstance(tree._metatree, Module) assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 assert tree.sub_tree.param_d == 3.0 @@ -59,71 +57,56 @@ class Tree(Module): assert tree.param_b == 5.0 # Test default bijectors - bijectors = tree.meta_at[...].get("transform") - bijector_list = jtu.tree_leaves(bijectors) + bijector_list = [leaf.get("bijector") for leaf in tree._metatree_leaves] for b1, b2 in zip( - bijector_list, [Identity, Identity, Softplus, Softplus, Softplus] + bijector_list, [Identity, Softplus, Identity, Softplus, Softplus] ): assert b1 == b2 # Test default trainables - trainables = tree.meta_at[...].get("trainable") - trainable_list = jtu.tree_leaves(trainables) + trainable_list = [leaf.get("trainable") for leaf in tree._metatree_leaves] for t1, t2 in zip(trainable_list, [True, True, True, True, True]): assert t1 == t2 # Test constrain and unconstrain - constrained = constrain(tree) - unconstrained = unconstrain(tree) + constrained = tree.constrain() + unconstrained = tree.unconstrain() leafs = jtu.tree_leaves(tree) for l1, l2, bij in zip( leafs, jtu.tree_leaves(constrained), - [Identity, Identity, Softplus, Softplus, Softplus], + [Identity, Softplus, Identity, Softplus, Softplus], ): assert bij.forward(l1) == l2 for l1, l2, bij in zip( leafs, jtu.tree_leaves(unconstrained), - [Identity, Identity, Softplus, Softplus, Softplus], + [Identity, Softplus, Identity, Softplus, Softplus], ): assert bij.inverse(l1) == l2 - new_tree = tree.meta_at[ - lambda t: (t.sub_tree.param_c, t.param_b, t.sub_tree.param_e) - ].set(trainable=[False, False, False]) - - new_trainables = new_tree.meta_at[...].get("trainable") - new_trainable_list = jtu.tree_leaves(new_trainables) + new_tree = tree.at[...].trainables(param_b=False) + new_tree = new_tree.at["sub_tree"].trainables(param_c=False, param_e=False) + new_trainable_list = [leaf.get("trainable") for leaf in new_tree._metatree_leaves] - for t1, t2 in zip(new_trainable_list, [True, False, True, False, False]): + for t1, t2 in zip(new_trainable_list, [True, False, False, True, False]): assert t1 == t2 # Test stop gradients - # def loss(tree): - # with tree.stop_gradients() as t: - # return jnp.sum( - # t.param_a**2 - # + t.sub_tree.param_c**2 - # + t.sub_tree.param_d**2 - # + t.sub_tree.param_e**2 - # + t.param_b**2 - # ) - def loss(tree): - tree = stop_gradients(tree) - return jnp.sum( - tree.param_a**2 - + tree.sub_tree.param_c**2 - + tree.sub_tree.param_d**2 - + tree.sub_tree.param_e**2 - + tree.param_b**2 - ) + with tree.stop_gradients() as t: + return jnp.sum( + t.param_a**2 + + t.sub_tree.param_c**2 + + t.sub_tree.param_d**2 + + t.sub_tree.param_e**2 + + t.param_b**2 + ) g = jax.grad(loss)(new_tree) @@ -134,62 +117,22 @@ def loss(tree): assert g.param_b == 0.0 -# TODO: Fix these tests. -# def test_module_incorrect_typing(): -# class NotAModule: -# pass - -# class SubTree(Module): -# param_c: float = param(Identity) -# param_d: float = param(Softplus) -# param_e: float = param(Softplus) - -# class Tree(Module): -# param_a: float = param(Identity) -# sub_tree: NotAModule -# param_b: float = param(Softplus) - -# with pytest.raises(ValueError): -# Tree( -# param_a=1.0, -# sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), -# param_b=5.0, -# ) - - -# def test_module_unmarked_param(): -# class SubTree(Module): -# param_c: float -# param_d: float = param(Softplus) -# param_e: float = param(Softplus) - -# class Tree(Module): -# param_a: float = param(Identity) -# sub_tree: SubTree -# param_b: float = param(Softplus) - -# with pytest.raises(ValueError): -# Tree( -# param_a=1.0, -# sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), -# param_b=5.0, -# ) - - def test_tuple_attribute(): + @dataclass class SubTree(Module): - param_a: int = param(transform=Identity, default=1) - param_b: int = param(transform=Softplus, default=2) - param_c: int = param(transform=Identity, default=3, trainable=False) + param_a: int = param(bijector=Identity, default=1) + param_b: int = param(bijector=Softplus, default=2) + param_c: int = param(bijector=Identity, default=3, trainable=False) + @dataclass class Tree(Module): trees: tuple tree = Tree((SubTree(), SubTree(), SubTree())) - assert len([meta.get("trainable") for meta in tree.__meta__]) == 9 - assert len([meta.get("transform") for meta in tree.__meta__]) == 9 - assert [meta.get("trainable") for meta in tree.__meta__] == [ + assert len([meta.get("trainable") for meta in tree._metatree_leaves]) == 9 + assert len([meta.get("bijector") for meta in tree._metatree_leaves]) == 9 + assert [meta.get("trainable") for meta in tree._metatree_leaves] == [ True, True, False, @@ -200,7 +143,7 @@ class Tree(Module): True, False, ] - assert [meta.get("transform") for meta in tree.__meta__] == [ + assert [meta.get("bijector") for meta in tree._metatree_leaves] == [ Identity, Softplus, Identity, @@ -214,19 +157,21 @@ class Tree(Module): def test_list_attribute(): + @dataclass class SubTree(Module): - param_a: int = param(transform=Identity, default=1) - param_b: int = param(transform=Softplus, default=2) - param_c: int = param(transform=Identity, default=3, trainable=False) + param_a: int = param(bijector=Identity, default=1) + param_b: int = param(bijector=Softplus, default=2) + param_c: int = param(bijector=Identity, default=3, trainable=False) + @dataclass class Tree(Module): trees: list tree = Tree([SubTree(), SubTree(), SubTree()]) - assert len([meta.get("trainable") for meta in tree.__meta__]) == 9 - assert len([meta.get("transform") for meta in tree.__meta__]) == 9 - assert [meta.get("trainable") for meta in tree.__meta__] == [ + assert len([meta.get("trainable") for meta in tree._metatree_leaves]) == 9 + assert len([meta.get("bijector") for meta in tree._metatree_leaves]) == 9 + assert [meta.get("trainable") for meta in tree._metatree_leaves] == [ True, True, False, @@ -237,7 +182,7 @@ class Tree(Module): True, False, ] - assert [meta.get("transform") for meta in tree.__meta__] == [ + assert [meta.get("bijector") for meta in tree._metatree_leaves] == [ Identity, Softplus, Identity, @@ -251,31 +196,37 @@ class Tree(Module): def test_module_not_enough_attributes(): + @dataclass class MyModule1(Module): weight: Any = param(Identity) with pytest.raises(TypeError): MyModule1() + @dataclass class MyModule2(Module): weight: Any = param(Identity) def __init__(self): - pass + return None + + # We don't check this. + # with pytest.raises(AttributeError): + # MyModule2() - with pytest.raises(ValueError): - MyModule2() with pytest.raises(TypeError): MyModule2(1) def test_module_too_many_attributes(): + @dataclass class MyModule1(Module): weight: Any = param(Identity) with pytest.raises(TypeError): MyModule1(1, 2) + @dataclass class MyModule2(Module): weight: Any = param(Identity) @@ -288,6 +239,7 @@ def __init__(self, weight): def test_module_setattr_after_init(): + @dataclass class MyModule(Module): weight: Any = param(Identity) @@ -297,6 +249,7 @@ class MyModule(Module): def test_wrong_attribute(): + @dataclass class MyModule(Module): weight: Any = param(Identity) @@ -311,9 +264,11 @@ def __init__(self, value): def test_inheritance(): # no custom init / no custom init + @dataclass class MyModule(Module): weight: Any = param(Identity) + @dataclass class MyModule2(MyModule): weight2: Any = param(Identity) @@ -331,6 +286,7 @@ class MyModule2(MyModule): # not custom init / custom init + @dataclass class MyModule3(MyModule): weight3: Any = param(Identity) @@ -344,27 +300,27 @@ def __init__(self, *, weight3, **kwargs): # custom init / no custom init + @dataclass class MyModule4(Module): weight4: Any = param(Identity) - def __init__(self, value4, **kwargs): - self.weight4 = value4 - super().__init__(**kwargs) - + @dataclass class MyModule5(MyModule4): weight5: Any = param(Identity) with pytest.raises(TypeError): m = MyModule5(value4=1, weight5=2) + @dataclass class MyModule6(MyModule4): pass - m = MyModule6(value4=1) + m = MyModule6(weight4=1) assert m.weight4 == 1 # custom init / custom init + @dataclass class MyModule7(MyModule4): weight7: Any = param(Identity) @@ -372,16 +328,17 @@ def __init__(self, value7, **kwargs): self.weight7 = value7 super().__init__(**kwargs) - m = MyModule7(value4=1, value7=2) + m = MyModule7(weight4=1, value7=2) assert m.weight4 == 1 assert m.weight7 == 2 def test_static_field(): + @dataclass class MyModule(Module): field1: int = param(Identity) - field2: int = eqx.static_field() - field3: int = eqx.static_field(default=3) + field2: int = static() + field3: int = static(default=3) m = MyModule(1, 2) flat, treedef = jtu.tree_flatten(m) @@ -393,29 +350,33 @@ class MyModule(Module): assert rm.field3 == 3 -def test_wrap_method(): - class MyModule(Module): - a: int = param(Identity) +# TODO: Wrap methods with a Partial like Equinox does in future. +# def test_wrap_method(): +# @dataclass +# class MyModule(Module): +# a: int = param(Identity) - def f(self, b): - return self.a + b +# def f(self, b): +# return self.a + b - m = MyModule(13) - assert isinstance(m.f, jtu.Partial) - flat, treedef = jtu.tree_flatten(m.f) - assert len(flat) == 1 - assert flat[0] == 13 - assert jtu.tree_unflatten(treedef, flat)(2) == 15 +# m = MyModule(13) +# assert isinstance(m.f, jtu.Partial) +# flat, treedef = jtu.tree_flatten(m.f) +# assert len(flat) == 1 +# assert flat[0] == 13 +# assert jtu.tree_unflatten(treedef, flat)(2) == 15 def test_init_subclass(): ran = [] + @dataclass class MyModule(Module): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) ran.append(True) + @dataclass class AnotherModule(MyModule): pass From 75574d9e972b738816a3e0dfcb7d3ca4e97267ab Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Wed, 8 Mar 2023 12:32:37 +0000 Subject: [PATCH 55/81] Remove some redundant code. --- jaxutils/_cached.py | 63 --------- jaxutils/_module.py | 46 +++--- jaxutils/_pytree.py | 23 +-- jaxutils/_utils.py | 61 ++++++++ jaxutils/dataset.py | 35 ++--- jaxutils/fit.py | 4 +- jaxutils/module.py | 294 +++++++-------------------------------- jaxutils/node.py | 45 ++---- jaxutils/objective.py | 19 +-- jaxutils/progress_bar.py | 126 ----------------- jaxutils/pytree.py | 65 ++------- tests/test_module.py | 49 ++++--- 12 files changed, 206 insertions(+), 624 deletions(-) delete mode 100644 jaxutils/_cached.py create mode 100644 jaxutils/_utils.py delete mode 100644 jaxutils/progress_bar.py diff --git a/jaxutils/_cached.py b/jaxutils/_cached.py deleted file mode 100644 index f8ebd85..0000000 --- a/jaxutils/_cached.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 non-public module defines the caching utilities for the Module class's static properties.""" - -from __future__ import annotations -from typing import Callable - - -class _cached_static_property: - """Decorator to cache result of static immutable properties of a PyTree. - - Example: - - This example shows us caching the result of sqauring a static float attribute of a Module. - - >>> import jaxutils as ju - >>> - >>> class MyModule(ju.Module): - >>> static_attribute: float = ju.static() - - >>> @_cached_static_property - >>> def static_property(self): - >>> return self.static_attribute ** 2 - - Note: - The decorated property must *NOT* contain any dynamic attributes / PyTree leaves, - i.e., any attributes referenced in the property must be marked as static. - - For example, the following will break durin tracing since `self.dynamic_attribute` is not static: - - >>> import jaxutils as ju - >>> - >>> class MyModule(ju.Module): - >>> static_attribute: float = ju.static() - >>> dynamic_attribute: float = ju.param(ju.Identity) - >>> - >>> @_cached_static_property - >>> def static_property(self): - >>> return self.static_attribute ** 2 + self.dynamic_attribute - """ - - def __init__(self, static_property: Callable): - """Here we store the name of the property and the function itself.""" - self.name = static_property.__name__ - self.func = static_property - - def __get__(self, instance, owner): - """Here we cache the result of the property function, by overwriting the attribute with the result.""" - attr = self.func(instance) - object.__setattr__(instance, self.name, attr) - return attr diff --git a/jaxutils/_module.py b/jaxutils/_module.py index 6bfa96b..6ea7734 100644 --- a/jaxutils/_module.py +++ b/jaxutils/_module.py @@ -14,32 +14,30 @@ # ============================================================================== """This non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" -from typing import Sequence, Callable, Union, Iterable +from typing import Sequence, Callable, Union, Dict +from .bijectors import Bijector +from .distributions import Distribution from .module import Module from .pytree import PyTree from .node import node_at -def _to_callable( - where: Union[Callable[[Module], Sequence[Module]], Sequence[str], Ellipsis] -) -> Callable[[Module], Sequence[Module]]: +def _replace_trainables(module: Module, **kwargs: Dict[str, bool]) -> Module: + """Replace the trainability status of local nodes of the PyTree.""" + _meta_wrapper = {k: {"trainable": v} for k, v in kwargs.items()} + return module._update_meta(**_meta_wrapper) - if isinstance(where, str): - where = eval("lambda x: x." + where) - if isinstance(where, Iterable): +def _replace_bijectors(module: Module, **kwargs: Dict[str, Bijector]) -> Module: + """Replace the bijectors of local nodes of the PyTree.""" + _meta_wrapper = {k: {"bijector": v} for k, v in kwargs.items()} + return module._update_meta(**_meta_wrapper) - def _to_path(it: Iterable): - return "".join( - [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] - ) - where = eval("lambda x: x" + _to_path(where)) - - if isinstance(where, type(Ellipsis)): - where = lambda x: x - - return where +def _replace_priors(module: Module, **kwargs: Dict[str, Distribution]) -> Module: + """Replace the priors of local nodes of the PyTree.""" + _meta_wrapper = {k: {"prior": v} for k, v in kwargs.items()} + return module._update_meta(**_meta_wrapper) class _ModuleNodeUpdateRef: @@ -63,7 +61,7 @@ def set(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._replace(**kwargs), + operator=lambda node: node._replace(**kwargs), node_type=Module, ) @@ -71,7 +69,7 @@ def set_meta(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._replace_meta(**kwargs), + operator=lambda node: node._replace_meta(**kwargs), node_type=Module, ) @@ -79,7 +77,7 @@ def update_meta(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._update_meta(**kwargs), + operator=lambda node: node._update_meta(**kwargs), node_type=Module, ) @@ -87,7 +85,7 @@ def trainables(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._replace_trainables(**kwargs), + operator=lambda node: _replace_trainables(node, **kwargs), node_type=Module, ) @@ -95,7 +93,7 @@ def bijectors(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._replace_bijectors(**kwargs), + operator=lambda node: _replace_bijectors(node, **kwargs), node_type=Module, ) @@ -103,7 +101,7 @@ def priors(self, **kwargs) -> PyTree: return node_at( where=self.where, pytree=self.module, - replace_fn=lambda node: node._replace_priors(**kwargs), + operator=lambda node: _replace_priors(node, **kwargs), node_type=Module, ) @@ -121,8 +119,6 @@ def __getitem__( where: Union[Callable[[Module], Sequence[Module]], Sequence[str], Ellipsis], ) -> _ModuleNodeUpdateRef: - where = _to_callable(where) - return _ModuleNodeUpdateRef(self.module, where) def __repr__(self) -> str: diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py index 84a31ba..a9c1a38 100644 --- a/jaxutils/_pytree.py +++ b/jaxutils/_pytree.py @@ -16,9 +16,10 @@ """This non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" from __future__ import annotations -from typing import Sequence, Callable, Union, Iterable +from typing import Sequence, Callable, Union from .pytree import PyTree from .node import node_at +from ._utils import _to_callable class _PyTreeNodeUpdateRef: @@ -73,25 +74,7 @@ def __getitem__( where: Union[Callable[[PyTree], Sequence[PyTree]], Sequence[str], Ellipsis], ) -> _PyTreeNodeUpdateRef: - if isinstance(where, str): - where = eval("lambda x: x." + where) - - if isinstance(where, Iterable): - - def _to_path(it: Iterable): - return "".join( - [ - str(elem) if not isinstance(elem, str) else "." + elem - for elem in it - ] - ) - - where = eval("lambda x: x" + _to_path(where)) - - if isinstance(where, type(Ellipsis)): - where = lambda x: x - - return _PyTreeNodeUpdateRef(self.pytree, where) + return _PyTreeNodeUpdateRef(self.pytree, _to_callable(where)) def __repr__(self) -> str: return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/_utils.py b/jaxutils/_utils.py new file mode 100644 index 0000000..8032cea --- /dev/null +++ b/jaxutils/_utils.py @@ -0,0 +1,61 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from typing import Sequence, Callable, Union, Iterable, Any + + +def _to_callable(where: Union[Callable, Sequence[str], Ellipsis]) -> Callable: + """Convert a where argument to a callable function. + + Args: + where (Union[Callable[[Union[Module, PyTree]], Sequence[Union[Module, PyTree]]], Sequence[str], Ellipsis]): Where argument. + + Returns: + + Callable[[Union[Module, PyTree]], Sequence[Union[Module, PyTree]]]]: Callable function. + """ + + if isinstance(where, str): + where = eval("lambda x: x." + where) + + if isinstance(where, Iterable): + + def _to_path(it: Iterable): + return "".join( + [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] + ) + + where = eval("lambda x: x" + _to_path(where)) + + if isinstance(where, type(Ellipsis)): + where = lambda x: x + + return where + + +def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: + """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. + + Args: + f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. + pytree (PyTree): The pytree to apply the function to. + + Returns: + PyTree: The transformed pytree. + """ + leaves, treedef = jtu.tree_flatten(pytree) + meta_leaves = _unpack_metatree_leaves(pytree) + all_leaves = [leaves] + [meta_leaves] + return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) diff --git a/jaxutils/dataset.py b/jaxutils/dataset.py index fc017c0..109f5ee 100644 --- a/jaxutils/dataset.py +++ b/jaxutils/dataset.py @@ -18,35 +18,24 @@ from jaxtyping import Array, Float from typing import Optional from .pytree import PyTree +from dataclasses import dataclass - +# TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. +@dataclass class Dataset(PyTree): - """Base class for datasets.""" + """Base class for datasets. + + Attributes: + X (Optional[Float[Array, "N D"]]): Input data. + y (Optional[Float[Array, "N Q"]]): Output data. + """ X: Optional[Float[Array, "N D"]] = None y: Optional[Float[Array, "N Q"]] = None - # TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. - - def __init__( - self, - X: Optional[Float[Array, "N D"]] = None, - y: Optional[Float[Array, "N Q"]] = None, - ) -> None: - """ - Initialise a dataset object. - - Args: - X(Float[Array, "N D"]]): Input data. - y(Float[Array, "N Q"]]): Output data. - - Returns: - Dataset: A dataset object. - """ - - _check_shape(X, y) - self.X = X - self.y = y + def __post_init__(self) -> None: + """Checks that the shapes of X and y are compatible.""" + _check_shape(self.X, self.y) def __repr__(self) -> str: """Returns a string representation of the dataset.""" diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 350041c..d0e29fd 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -107,8 +107,8 @@ def fit( # Unconstrained space loss function with stop-gradient rule for non-trainable params. def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: - with model.stop_gradients() as model: - return objective(model.constrain(), batch) + model = model.stop_gradients() + return objective(model.constrain(), batch) # Unconstrained space model. model = model.unconstrain() diff --git a/jaxutils/module.py b/jaxutils/module.py index 958c5c2..313c3c5 100644 --- a/jaxutils/module.py +++ b/jaxutils/module.py @@ -15,12 +15,13 @@ from __future__ import annotations import jax +import jax.tree_util as jtu from jax import lax -from dataclasses import field -from typing import Any, Dict +from dataclasses import field, Field +from typing import Any from .distributions import Distribution from .bijectors import Bijector, Identity -from .pytree import PyTree, _metadata_map +from .pytree import PyTree, _unpack_metatree_leaves def param( @@ -28,63 +29,20 @@ def param( trainable: bool = True, prior: Distribution = None, **kwargs: Any, -): - """Used for marking default parameter transformations. - - All PyTree leaves of the `jaxutils.Module` must be marked by this function, `jaxutils.static`, or must be of type `jaxutils.Module`. - - Example: - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - >>> - >>> module = MyModule(param_a=1.0, param_b=1.0) - - We can access the trainability status of the parameters using the `trainables` property. - - >>> # Print the trainability status PyTree - >>> print(module.trainables) - LinearModel(weight=True, bias=True) - - And we can access the bijectors of the parameters using the `bijectors` property. - - >>> # Print the bijectors of the PyTree - >>> print(module.bijectors) - LinearModel( - weight=Bijector(forward=>, inverse=>), - bias=Bijector(forward=>, inverse=>) - ) - - Under the hood, the `param` function is used to create a `dataclasses.field` object with the `transform` and `trainable` metadata set, - which is then used to initialise the non-public and static `Module.__meta__` attribute. - - >>> # Print the trainability status leaves from the `__meta__` attribute. - >>> print(module.__meta__.trainables) - (True, False) - >>> - >>> # Print the bijectors of the leaves from the `__meta__` attribute. - >>> print(module.__meta__.bijectors) - (Identity(forward=>, inverse=>), Softplus(forward=>, inverse=>)) +) -> Field: + """Used for marking default parameter transformations, trainable statuses and prior distributions for Module. Args: transform (Bijector): The default bijector that should be should upon Module initialisation. + trainable (bool): Whether the parameter should be trainable or not. + prior (Distribution): The prior distribution for the parameter. **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) Returns: - A `dataclasses.field` object with the `transform` and `trainable` metadata set. + Field: A `dataclasses.Field` object with the `bijector`, `trainable` and `prior` metadata set. """ - # TODO: Type check. - try: metadata = dict(kwargs["metadata"]) except KeyError: @@ -105,219 +63,65 @@ def param( return field(**kwargs) -def _constrain(obj: Module) -> Module: - """Transform model parameters to the constrained space according to their defined bijectors. - - Example: - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - >>> - >>> module = MyModule(param_a=1.0, param_b=1.0) - - We can constrain the parameters using the `constrain` function. - - >>> constrained_module = ju.constrain(module) - >>> print(constrained_module) - MyModule(param_a=1.0, param_b=0.0) - - And we can unconstrain the parameters using the `unconstrain` function. - - >>> unconstrained_module = ju.unconstrain(constrained_module) - >>> print(unconstrained_module) - MyModule(param_a=1.0, param_b=1.0) - - Args: - obj (Module): The PyTree object whoose leaves are to be transformed. - - Returns: - Module: PyTree tranformed to the constrained space. - """ - return _metadata_map( - lambda leaf, meta: meta.get("bijector", Identity).forward(leaf), obj - ) - - -def _unconstrain(obj: Module) -> Module: - """Transform model parameters to the unconstrained space according to their defined bijectors. - - Example: - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - >>> - >>> module = MyModule(param_a=1.0, param_b=1.0) - - We can constrain the parameters using the `constrain` function. - - >>> constrained_module = ju.constrain(module) - >>> print(constrained_module) - MyModule(param_a=1.0, param_b=0.0) - - And we can unconstrain the parameters using the `unconstrain` function. - - >>> unconstrained_module = ju.unconstrain(constrained_module) - >>> print(unconstrained_module) - MyModule(param_a=1.0, param_b=1.0) - - Args: - obj (Module): The PyTree object whoose leaves are to be transformed. - - Returns: - Module: PyTree tranformed to the unconstrained space. - """ - return _metadata_map( - lambda leaf, meta: meta.get("bijector", Identity).inverse(leaf), obj - ) - - -def _stop_gradients(obj: Module) -> Module: - """ - Stop the gradients flowing through parameters whose trainable status is - False. This is useful for stopping parameters from being updated during training. - - Example: - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - - We now create a dummy objective function and check the gradients of the parameters. - - >>> module = MyModule(param_a=5.0, param_b=7.0) - >>> def dummy_objective(module, x): - ... module = ju.stop_gradients(module) # Stop gradients flowing through `param_b` - ... return jnp.sum(module(x)) - >>> g = jax.grad(dummy_objective)(module, 1.0) - - We can see that the gradient of `param_a` is 1.0, but the gradient of `param_b` is 0.0, as expected. - - >>> print(g.param_a, g.param_b) - 1.0 0.0 - - Args: - obj (Module): PyTree object to stop gradients for. - - Returns: - Module: PyTree with gradients stopped. - """ - - def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: - """Stop gradients flowing through a given leaf if it is not trainable.""" - return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - - return _metadata_map( - lambda leaf, meta: _stop_grad(leaf, meta.get("trainable", True)), obj - ) - - class Module(PyTree): """Base Module object. - This object is essentially an Equinox Module (i.e., a registered PyTree dataclass with static field markers), - with modifications to handle bijector transformations and trainability statuses. - Example: - - TODO: More thorough example. - - This example shows us creating a module with two parameters, with differing transformations and trainability statuses. - - >>> import jaxutils as ju - >>> import jax.numpy as jnp - >>> - >>> class MyModule(ju.Module): - >>> param_a: float = ju.param(ju.Identity, trainable=True) - >>> param_b: float = ju.param(ju.Softplus, trainable=False) - >>> - >>> def __call__(self, x): - >>> return self.param_a * x + self.param_b - - Note: - All attributes of the Module must be marked with either a `param` or `static` field or the attributes type needs to be subclass of `jaxutils.Module`. + TODO: Give example. """ - def _replace_trainables(self, **kwargs: Dict[str, bool]) -> Module: - _meta_wrapper = {k: {"trainable": v} for k, v in kwargs.items()} - return self._update_meta(**_meta_wrapper) - - def _replace_bijectors(self, **kwargs: Dict[str, Bijector]) -> Module: - _meta_wrapper = {k: {"bijector": v} for k, v in kwargs.items()} - return self._update_meta(**_meta_wrapper) - - def _replace_priors(self, **kwargs: Dict[str, Distribution]) -> Module: - _meta_wrapper = {k: {"prior": v} for k, v in kwargs.items()} - return self._update_meta(**_meta_wrapper) - - @property - def at(self): - from ._module import _ModuleNodeUpdateHelper - - return _ModuleNodeUpdateHelper(self) - @property def module_at(self): from ._module import _ModuleNodeUpdateHelper return _ModuleNodeUpdateHelper(self) - def training_transforms(self): - class _ConstrainHelper: - - slots = ("module",) - - def __init__(self, module): - self.module = module - - def __enter__(self): - return self.module.constrain() - - def __exit__(self, *args): - return True - - return _ConstrainHelper(self) - def constrain(self): - return _constrain(self) + """Transform model parameters to the constrained space according to their defined bijectors. + + Returns: + Module: tranformed to the constrained space. + """ + return _metadata_map( + lambda leaf, meta: meta.get("bijector", Identity).forward(leaf), self + ) def unconstrain(self): - return _unconstrain(self) + """Transform model parameters to the unconstrained space according to their defined bijectors. + + Returns: + Module: tranformed to the unconstrained space. + """ + return _metadata_map( + lambda leaf, meta: meta.get("bijector", Identity).inverse(leaf), self + ) def stop_gradients(self): - class _StopGradientsHelper: + """Stop gradients flowing through the module. + + Returns: + Module: with gradients stopped. + """ + # Stop gradients flowing through a given leaf if it is not trainable. + def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: + return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - slots = ("module",) + return _metadata_map( + lambda leaf, meta: _stop_grad(leaf, meta.get("trainable", True)), self + ) - def __init__(self, module): - self.module = module - def __enter__(self): - return _stop_gradients(self.module) +def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: + """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. - def __exit__(self, *args): - return True + Args: + f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. + pytree (PyTree): The pytree to apply the function to. - return _StopGradientsHelper(self) + Returns: + PyTree: The transformed pytree. + """ + leaves, treedef = jtu.tree_flatten(pytree) + meta_leaves = _unpack_metatree_leaves(pytree) + all_leaves = [leaves] + [meta_leaves] + return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) diff --git a/jaxutils/node.py b/jaxutils/node.py index a0e58eb..b18cd65 100644 --- a/jaxutils/node.py +++ b/jaxutils/node.py @@ -67,8 +67,7 @@ def count(self, item): def node_at( where: Callable[[NodeType], Sequence[NodeType]], pytree: PyTree, - replace: Sequence[Any] = None, - replace_fn: Callable[[NodeType], Any] = None, + operator: Callable[[NodeType], Any] = None, node_type: NodeType = PyTree, ): """Update a PyTree node or nodes in-place. @@ -97,7 +96,10 @@ def node_at( if ( structure1 != structure2 or len(leaves1) != len(leaves2) - or any(l1 is not l2 for l1, l2 in zip(leaves1, leaves2)) + or any( + l1 is not l2 and isinstance(l1, node_type) + for l1, l2 in zip(leaves1, leaves2) + ) ): raise ValueError( "`where` must use just the PyTree structure of `pytree`. `where` must not " @@ -118,45 +120,16 @@ def _in_pytree(x): if in_pytree: nodes = (node_or_nodes,) - if replace is not None: - replace = (replace,) else: nodes = node_or_nodes del in_pytree, node_or_nodes - # Checks on the where to ensure the node maps to another PyTree. - for num, node in enumerate(nodes): - if not isinstance(node, node_type): - raise ValueError( - f"Node number {num} in the `where` sequence is not of type node_type={node_type.__name__}." - ) - - # Normalise replace vs replace_fn - if replace is None: - if replace_fn is None: - raise ValueError( - "Precisely one of `replace` and `replace_fn` must be specified." - ) - else: - - def _replace_fn(x): - x = jtu.tree_map(_remove_leaf_wrapper, x) - return replace_fn(x) + def _replace_fn(x): + x = jtu.tree_map(_remove_leaf_wrapper, x) + return operator(x) - replace_fns = [_replace_fn] * len(nodes) - else: - if replace_fn is None: - if len(nodes) != len(replace): - raise ValueError( - "`where` must return a sequence of leaves of the same length as " - "`replace`." - ) - replace_fns = [lambda _, r=r: r for r in replace] - else: - raise ValueError( - "Precisely one of `replace` and `replace_fn` must be specified." - ) + replace_fns = [_replace_fn] * len(nodes) node_replace_fns = _CountedIdDict(nodes, replace_fns) # Actually do the replacement diff --git a/jaxutils/objective.py b/jaxutils/objective.py index f8fd01f..b25adc4 100644 --- a/jaxutils/objective.py +++ b/jaxutils/objective.py @@ -25,14 +25,17 @@ class Objective(PyTree): """Base class for objective functions. - !!! example - ```python - class MeanSquaredError(Objective): - def evaluate(self, model, train_data): - return jnp.mean((train_data.y - model(train_data.X)) ** 2) - ``` - - !!! note + Example: + >>> from jax import numpy as jnp + >>> from jaxutils import Objective + >>> + >>> class MeanSquaredError(Objective): + ... def evaluate(self, model, train_data): + ... return jnp.mean((train_data.y - model(train_data.X)) ** 2) + ... + >>> mse = MeanSquaredError() + + Note: The objective function is negated if `negative=True`. """ diff --git a/jaxutils/progress_bar.py b/jaxutils/progress_bar.py deleted file mode 100644 index 0944ae3..0000000 --- a/jaxutils/progress_bar.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from typing import Callable, Any, Union - -from jax import lax -from jax.experimental import host_callback -from jaxtyping import Array, Float -from tqdm.auto import tqdm - - -def progress_bar(num_iters: int, log_rate: int) -> Callable: - """Progress bar decorator for the body function of a `jax.lax.scan`. - - !!! example - ```python - - carry = jnp.array(0.0) - iteration_numbers = jnp.arange(100) - - @progress_bar(num_iters=x.shape[0], log_rate=10) - def body_func(carry, x): - return carry, x - - carry, _ = jax.lax.scan(body_func, carry, iteration_numbers) - ``` - - Adapted from the excellent blog post: https://www.jeremiecoullon.com/2021/01/29/jax_progress_bar/. - - Might be nice in future to directly create a general purpose `verbose scan` inplace of a for a jax.lax.scan, - that takes the same arguments as a jax.lax.scan, but prints a progress bar. - """ - - tqdm_bars = {} - remainder = num_iters % log_rate - - """Define a tqdm progress bar.""" - tqdm_bars[0] = tqdm(range(num_iters)) - tqdm_bars[0].set_description("Compiling...", refresh=True) - - def _update_tqdm(args: Any, transform: Any) -> None: - """Update the tqdm progress bar with the latest objective value.""" - value, iter_num = args - tqdm_bars[0].set_description(f"Running", refresh=False) - tqdm_bars[0].update(iter_num) - tqdm_bars[0].set_postfix({"Value": f"{value: .2f}"}) - - def _close_tqdm(args: Any, transform: Any) -> None: - """Close the tqdm progress bar.""" - tqdm_bars[0].close() - - def _callback(cond: bool, func: Callable, arg: Any) -> None: - """Callback a function for a given argument if a condition is true.""" - dummy_result = 0 - - def _do_callback(_) -> int: - """Perform the callback.""" - return host_callback.id_tap(func, arg, result=dummy_result) - - def _not_callback(_) -> int: - """Do nothing.""" - return dummy_result - - _ = lax.cond(cond, _do_callback, _not_callback, operand=None) - - def _update_progress_bar(value: Float[Array, "1"], iter_num: int) -> None: - """Update the tqdm progress bar.""" - - # Conditions for iteration number - is_multiple: bool = (iter_num % log_rate == 0) & ( - iter_num != num_iters - remainder - ) - is_remainder: bool = iter_num == num_iters - remainder - is_last: bool = iter_num == num_iters - 1 - - # Update progress bar, if multiple of log_rate - _callback(is_multiple, _update_tqdm, (value, log_rate)) - - # Update progress bar, if remainder - _callback(is_remainder, _update_tqdm, (value, remainder)) - - # Close progress bar, if last iteration - _callback(is_last, _close_tqdm, None) - - def _progress_bar(body_fun: Callable) -> Callable: - """Decorator that adds a progress bar to `body_fun` used in `jax.lax.scan`.""" - - def wrapper_progress_bar(carry: Any, x: Union[tuple, int]) -> Any: - - # Get iteration number - if type(x) is tuple: - iter_num, *_ = x - else: - iter_num = x - - # Compute iteration step - result = body_fun(carry, x) - - # Get value - *_, value = result - - # Update progress bar - _update_progress_bar(value, iter_num) - - return result - - return wrapper_progress_bar - - return _progress_bar - - -__all__ = [ - "progress_bar", -] diff --git a/jaxutils/pytree.py b/jaxutils/pytree.py index 8112b88..92d0501 100644 --- a/jaxutils/pytree.py +++ b/jaxutils/pytree.py @@ -18,27 +18,22 @@ from __future__ import annotations import dataclasses -from dataclasses import field +from dataclasses import field, Field from abc import ABCMeta -from typing import Any, Set, Dict, List, Callable +from typing import Any, Set, Dict, List from copy import copy, deepcopy import jax import jax.tree_util as jtu -def static(**kwargs: Any): - """Alias of `equinox.static_field`. Provided for convenience. +def static(**kwargs: Any) -> Field: + """Used for marking that a field should _not_ be treated as a leaf of the PyTree. - Used for marking that a field should _not_ be treated as a leaf of the PyTree - of a `jaxutils.Module`/ `equinox.Module`. (And is instead treated as part of the structure, i.e. - as extra metadata.) - - Example: + Equivalent to `equinox.static_field`. Args: **kwargs (Any): If any are passed then they are passed on to `dataclass.field`. - (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) """ try: metadata = dict(kwargs["metadata"]) @@ -60,15 +55,17 @@ def __call__(self, *args: Any, **kwds: Any): class PyTree(metaclass=PyTreeMeta): + """Base class for PyTree.""" + _pytree__initialized: bool _pytree__static_fields: Set[str] _pytree__class_is_mutable: bool _pytree__meta: Dict[str, Any] _pytree__annotations: List[str] _pytree__is_leaf: Dict[str:bool] - _pytree__metatree_leaves: List[Dict[str:Any]] def __init_subclass__(cls, mutable: bool = False): + jtu.register_pytree_node( cls, flatten_func=tree_flatten, @@ -84,7 +81,6 @@ def __init_subclass__(cls, mutable: bool = False): cls._pytree__meta = {} cls._pytree__annotations = class_annotations cls._pytree__is_leaf = {} - cls._pytree__metatree_leaves = [] # get class info class_vars = _get_all_class_vars(cls) @@ -109,20 +105,6 @@ def __init_subclass__(cls, mutable: bool = False): ): cls._pytree__meta[field] = {} - @property - def _metatree_leaves(self) -> List[Dict[str, Any]]: - return _unpack_metatree_leaves(self) - - @property - def _metatree(self) -> Dict[str, Any]: - return jtu.tree_structure(self).unflatten(self._metatree_leaves) - - @property - def pytree_at(self): - from ._pytree import _PyTreeNodeUpdateHelper - - return _PyTreeNodeUpdateHelper(self) - def _replace_meta(self, **kwargs: Any) -> PyTree: """ Replace the values of the fields of the object with the values of the @@ -206,18 +188,11 @@ def __setattr__(self, field: str, value: Any): ) object.__setattr__(self, field, value) - if not _is_leaf and field not in self._pytree__static_fields: - - def _unpack_pytree__meta(value): - if isinstance(value, PyTree): - return value._pytree__meta - else: - return value + @property + def pytree_at(self): + from ._pytree import _PyTreeNodeUpdateHelper - _meta = jtu.tree_map( - _unpack_pytree__meta, value, is_leaf=lambda x: isinstance(x, PyTree) - ) - object.__setattr__(self, "_pytree__metatree_leaves", _meta) + return _PyTreeNodeUpdateHelper(self) def tree_flatten(pytree: PyTree): @@ -283,22 +258,6 @@ def _get_all_annotations(cls: type) -> Dict[str, type]: return d -def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: - """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. - - Args: - f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. - pytree (PyTree): The pytree to apply the function to. - - Returns: - PyTree: The transformed pytree. - """ - leaves, treedef = jtu.tree_flatten(pytree) - meta_leaves = _unpack_metatree_leaves(pytree) - all_leaves = [leaves] + [meta_leaves] - return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) - - def _unpack_metatree_leaves(pytree: PyTree) -> List[Dict[str, Any]]: """ Returns a list of the PyTree leaves' metadata. diff --git a/tests/test_module.py b/tests/test_module.py index 2f3cf4f..297830c 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -14,7 +14,7 @@ # ============================================================================== import jax.numpy as jnp -from jaxutils.pytree import static +from jaxutils.pytree import static, _unpack_metatree_leaves from jaxutils.module import Module, param from jaxutils.bijectors import Identity, Softplus import jax.tree_util as jtu @@ -49,7 +49,6 @@ class Tree(Module): ) assert isinstance(tree, Module) - assert isinstance(tree._metatree, Module) assert tree.param_a == 1.0 assert tree.sub_tree.param_c == 2.0 assert tree.sub_tree.param_d == 3.0 @@ -57,7 +56,7 @@ class Tree(Module): assert tree.param_b == 5.0 # Test default bijectors - bijector_list = [leaf.get("bijector") for leaf in tree._metatree_leaves] + bijector_list = [leaf.get("bijector") for leaf in _unpack_metatree_leaves(tree)] for b1, b2 in zip( bijector_list, [Identity, Softplus, Identity, Softplus, Softplus] @@ -65,7 +64,7 @@ class Tree(Module): assert b1 == b2 # Test default trainables - trainable_list = [leaf.get("trainable") for leaf in tree._metatree_leaves] + trainable_list = [leaf.get("trainable") for leaf in _unpack_metatree_leaves(tree)] for t1, t2 in zip(trainable_list, [True, True, True, True, True]): assert t1 == t2 @@ -90,23 +89,27 @@ class Tree(Module): ): assert bij.inverse(l1) == l2 - new_tree = tree.at[...].trainables(param_b=False) - new_tree = new_tree.at["sub_tree"].trainables(param_c=False, param_e=False) - new_trainable_list = [leaf.get("trainable") for leaf in new_tree._metatree_leaves] + new_tree = tree.module_at[lambda x: x].trainables(param_b=False) + new_tree = new_tree.module_at[lambda x: x.sub_tree].trainables( + param_c=False, param_e=False + ) + new_trainable_list = [ + leaf.get("trainable") for leaf in _unpack_metatree_leaves(new_tree) + ] for t1, t2 in zip(new_trainable_list, [True, False, False, True, False]): assert t1 == t2 # Test stop gradients def loss(tree): - with tree.stop_gradients() as t: - return jnp.sum( - t.param_a**2 - + t.sub_tree.param_c**2 - + t.sub_tree.param_d**2 - + t.sub_tree.param_e**2 - + t.param_b**2 - ) + t = tree.stop_gradients() + return jnp.sum( + t.param_a**2 + + t.sub_tree.param_c**2 + + t.sub_tree.param_d**2 + + t.sub_tree.param_e**2 + + t.param_b**2 + ) g = jax.grad(loss)(new_tree) @@ -130,9 +133,9 @@ class Tree(Module): tree = Tree((SubTree(), SubTree(), SubTree())) - assert len([meta.get("trainable") for meta in tree._metatree_leaves]) == 9 - assert len([meta.get("bijector") for meta in tree._metatree_leaves]) == 9 - assert [meta.get("trainable") for meta in tree._metatree_leaves] == [ + assert len([meta.get("trainable") for meta in _unpack_metatree_leaves(tree)]) == 9 + assert len([meta.get("bijector") for meta in _unpack_metatree_leaves(tree)]) == 9 + assert [meta.get("trainable") for meta in _unpack_metatree_leaves(tree)] == [ True, True, False, @@ -143,7 +146,7 @@ class Tree(Module): True, False, ] - assert [meta.get("bijector") for meta in tree._metatree_leaves] == [ + assert [meta.get("bijector") for meta in _unpack_metatree_leaves(tree)] == [ Identity, Softplus, Identity, @@ -169,9 +172,9 @@ class Tree(Module): tree = Tree([SubTree(), SubTree(), SubTree()]) - assert len([meta.get("trainable") for meta in tree._metatree_leaves]) == 9 - assert len([meta.get("bijector") for meta in tree._metatree_leaves]) == 9 - assert [meta.get("trainable") for meta in tree._metatree_leaves] == [ + assert len([meta.get("trainable") for meta in _unpack_metatree_leaves(tree)]) == 9 + assert len([meta.get("bijector") for meta in _unpack_metatree_leaves(tree)]) == 9 + assert [meta.get("trainable") for meta in _unpack_metatree_leaves(tree)] == [ True, True, False, @@ -182,7 +185,7 @@ class Tree(Module): True, False, ] - assert [meta.get("bijector") for meta in tree._metatree_leaves] == [ + assert [meta.get("bijector") for meta in _unpack_metatree_leaves(tree)] == [ Identity, Softplus, Identity, From 731f46e10198f94b678a40d6cb90c9e55d57ca31 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Mar 2023 13:09:33 +0000 Subject: [PATCH 56/81] ParameterState. --- jaxutils/_module.py | 125 --------------- jaxutils/_pytree.py | 80 --------- jaxutils/_utils.py | 61 ------- jaxutils/bijectors.py | 61 ++----- jaxutils/dataset.py | 6 +- jaxutils/distributions.py | 25 --- jaxutils/fit.py | 89 +++-------- jaxutils/module.py | 127 --------------- jaxutils/node.py | 167 ------------------- jaxutils/objective.py | 90 ----------- jaxutils/parameters.py | 133 +++++++++++++++ jaxutils/pytree.py | 329 +++++++------------------------------- 12 files changed, 220 insertions(+), 1073 deletions(-) delete mode 100644 jaxutils/_module.py delete mode 100644 jaxutils/_pytree.py delete mode 100644 jaxutils/_utils.py delete mode 100644 jaxutils/distributions.py delete mode 100644 jaxutils/module.py delete mode 100644 jaxutils/node.py delete mode 100644 jaxutils/objective.py create mode 100644 jaxutils/parameters.py diff --git a/jaxutils/_module.py b/jaxutils/_module.py deleted file mode 100644 index 6ea7734..0000000 --- a/jaxutils/_module.py +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" -from typing import Sequence, Callable, Union, Dict -from .bijectors import Bijector -from .distributions import Distribution -from .module import Module -from .pytree import PyTree -from .node import node_at - - -def _replace_trainables(module: Module, **kwargs: Dict[str, bool]) -> Module: - """Replace the trainability status of local nodes of the PyTree.""" - _meta_wrapper = {k: {"trainable": v} for k, v in kwargs.items()} - return module._update_meta(**_meta_wrapper) - - -def _replace_bijectors(module: Module, **kwargs: Dict[str, Bijector]) -> Module: - """Replace the bijectors of local nodes of the PyTree.""" - _meta_wrapper = {k: {"bijector": v} for k, v in kwargs.items()} - return module._update_meta(**_meta_wrapper) - - -def _replace_priors(module: Module, **kwargs: Dict[str, Distribution]) -> Module: - """Replace the priors of local nodes of the PyTree.""" - _meta_wrapper = {k: {"prior": v} for k, v in kwargs.items()} - return module._update_meta(**_meta_wrapper) - - -class _ModuleNodeUpdateRef: - - __slots__ = ( - "module", - "where", - ) - - def __init__(self, module: Module, where: Union[Callable, Sequence[str]]) -> None: - self.module = module - self.where = where - - def __repr__(self) -> str: - return f"_ModuleNodeUpdateRef({repr(self.module)}, {repr(self.where)})" - - def get(self) -> PyTree: - return self.where(self.pytree) - - def set(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: node._replace(**kwargs), - node_type=Module, - ) - - def set_meta(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: node._replace_meta(**kwargs), - node_type=Module, - ) - - def update_meta(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: node._update_meta(**kwargs), - node_type=Module, - ) - - def trainables(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: _replace_trainables(node, **kwargs), - node_type=Module, - ) - - def bijectors(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: _replace_bijectors(node, **kwargs), - node_type=Module, - ) - - def priors(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.module, - operator=lambda node: _replace_priors(node, **kwargs), - node_type=Module, - ) - - -class _ModuleNodeUpdateHelper: - """Helper class for updating a PyTree.""" - - __slots__ = ("module",) - - def __init__(self, module: Module) -> None: - self.module = module - - def __getitem__( - self, - where: Union[Callable[[Module], Sequence[Module]], Sequence[str], Ellipsis], - ) -> _ModuleNodeUpdateRef: - - return _ModuleNodeUpdateRef(self.module, where) - - def __repr__(self) -> str: - return f"_ModuleNodeUpdateHelper({repr(self.module)})" diff --git a/jaxutils/_pytree.py b/jaxutils/_pytree.py deleted file mode 100644 index a9c1a38..0000000 --- a/jaxutils/_pytree.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" - -from __future__ import annotations -from typing import Sequence, Callable, Union -from .pytree import PyTree -from .node import node_at -from ._utils import _to_callable - - -class _PyTreeNodeUpdateRef: - - __slots__ = ( - "pytree", - "where", - ) - - def __init__(self, pytree: PyTree, where: Union[Callable, Sequence[str]]) -> None: - self.pytree = pytree - self.where = where - - def __repr__(self) -> str: - return f"_PyTreeUpdateRef({repr(self.pytree)}, {repr(self.where)})" - - def get(self) -> PyTree: - return self.where(self.pytree) - - def replace(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.pytree, - replace_fn=lambda node: node._replace(**kwargs), - ) - - def replace_meta(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.pytree, - replace_fn=lambda node: node._replace_meta(**kwargs), - ) - - def update_meta(self, **kwargs) -> PyTree: - return node_at( - where=self.where, - pytree=self.pytree, - replace_fn=lambda node: node._update_meta(**kwargs), - ) - - -class _PyTreeNodeUpdateHelper: - """Helper class for updating a PyTree.""" - - __slots__ = ("pytree",) - - def __init__(self, pytree: PyTree) -> None: - self.pytree = pytree - - def __getitem__( - self, - where: Union[Callable[[PyTree], Sequence[PyTree]], Sequence[str], Ellipsis], - ) -> _PyTreeNodeUpdateRef: - - return _PyTreeNodeUpdateRef(self.pytree, _to_callable(where)) - - def __repr__(self) -> str: - return f"_PyTreeUpdateHelper({repr(self.pytree)})" diff --git a/jaxutils/_utils.py b/jaxutils/_utils.py deleted file mode 100644 index 8032cea..0000000 --- a/jaxutils/_utils.py +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from typing import Sequence, Callable, Union, Iterable, Any - - -def _to_callable(where: Union[Callable, Sequence[str], Ellipsis]) -> Callable: - """Convert a where argument to a callable function. - - Args: - where (Union[Callable[[Union[Module, PyTree]], Sequence[Union[Module, PyTree]]], Sequence[str], Ellipsis]): Where argument. - - Returns: - - Callable[[Union[Module, PyTree]], Sequence[Union[Module, PyTree]]]]: Callable function. - """ - - if isinstance(where, str): - where = eval("lambda x: x." + where) - - if isinstance(where, Iterable): - - def _to_path(it: Iterable): - return "".join( - [str(elem) if not isinstance(elem, str) else "." + elem for elem in it] - ) - - where = eval("lambda x: x" + _to_path(where)) - - if isinstance(where, type(Ellipsis)): - where = lambda x: x - - return where - - -def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: - """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. - - Args: - f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. - pytree (PyTree): The pytree to apply the function to. - - Returns: - PyTree: The transformed pytree. - """ - leaves, treedef = jtu.tree_flatten(pytree) - meta_leaves = _unpack_metatree_leaves(pytree) - all_leaves = [leaves] + [meta_leaves] - return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) diff --git a/jaxutils/bijectors.py b/jaxutils/bijectors.py index acecef4..adea7d8 100644 --- a/jaxutils/bijectors.py +++ b/jaxutils/bijectors.py @@ -12,63 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== -"""Bijectors for use in model optimisation.""" +import distrax as dx import jax.numpy as jnp -from typing import Callable +import tensorflow_probability.substrates.jax as tfb -from .pytree import PyTree, static +Identity = dx.Lambda(forward=lambda x: x, inverse=lambda x: x) - -class Bijector(PyTree): - """Base class for parameter bijector transformations. These are useful for model optimisation, where - gradients are taken in the "unconstrained" (real) parameter space, while evaluating the model takes place - in the "constrained" parameter space. - - For example, the Softplus bijector, f, is defined as: - f(x) = log(1 + exp(x)) - f^{-1}(y) = log(exp(y) - 1) - - gives the "unconstrained" parameter space as the real line, while the "constrained" parameter space is the positive real line. - This means we can ensure that the corresponding model parameter remains positive during optimisation. - - To implement your own bijector, you need to do is define a `forward` and `inverse` transformation! - - Adding log_det_jacobian's etc., is on the TODO list of this class. - """ - - forward: Callable = static() - inverse: Callable = static() - - def __init__(self, forward: Callable, inverse: Callable) -> None: - """Initialise the bijector. - - Args: - forward(Callable): The forward transformation. - inverse(Callable): The inverse transformation. - - Returns: - Bijector: A bijector. - """ - self.forward = forward - self.inverse = inverse - - -"""Identity bijector.""" -Identity = Bijector(forward=lambda x: x, inverse=lambda x: x) - -"""Softplus bijector.""" -Softplus = Bijector( +Softplus = dx.Lambda( forward=lambda x: jnp.log(1 + jnp.exp(x)), inverse=lambda x: jnp.log(jnp.exp(x) - 1.0), ) -"""Triangular bijector.""" -# TODO: Add triangular bijector. - - -__all__ = [ - "Bijector", - "Identity", - "Softplus", -] +FillScaleTriL = dx.Chain( + [ + tfb.FillScaleTriL(diag_shift=jnp.array(1e-6)), + ] +) diff --git a/jaxutils/dataset.py b/jaxutils/dataset.py index 109f5ee..ca8c4c7 100644 --- a/jaxutils/dataset.py +++ b/jaxutils/dataset.py @@ -17,12 +17,12 @@ import jax.numpy as jnp from jaxtyping import Array, Float from typing import Optional -from .pytree import PyTree +from simple_pytree import Pytree from dataclasses import dataclass -# TODO: Consider HeterotopicDataset and IsotopicDataset abstractions. + @dataclass -class Dataset(PyTree): +class Dataset(Pytree): """Base class for datasets. Attributes: diff --git a/jaxutils/distributions.py b/jaxutils/distributions.py deleted file mode 100644 index 3cb2aef..0000000 --- a/jaxutils/distributions.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from .pytree import PyTree - - -class Distribution(PyTree): - """Base class for distributions.""" - - -__all__ = [ - "Distribution", -] diff --git a/jaxutils/fit.py b/jaxutils/fit.py index d0e29fd..1508284 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -24,16 +24,15 @@ from jaxtyping import Array, Float from typing import Any -from .module import Module +from .parameters import Parameters from .dataset import Dataset -from .objective import Objective from .scan import vscan def fit( *, - model: Module, - objective: Objective, + params: Parameters, + objective: callable[[Parameters, Dataset], Float[Array, "1"]], train_data: Dataset, optim: ox.GradientTransformation, num_iters: Optional[int] = 100, @@ -42,45 +41,12 @@ def fit( log_rate: Optional[int] = 10, verbose: Optional[bool] = True, unroll: int = 1, -) -> Tuple[Module, Array]: +) -> Tuple[Parameters, Array]: """Train a Module model with respect to a supplied Objective function. Optimisers used here should originate from Optax. - Example: - >>> import jax.numpy as jnp - >>> import jax.random as jr - >>> import optax as ox - >>> import jaxutils as ju - >>> - >>> # (1) Create a dataset: - >>> X = jnp.linspace(0.0, 10.0, 100)[:, None] - >>> y = 2.0 * X + 1.0 + 10 * jr.normal(jr.PRNGKey(0), X.shape) - >>> D = ju.Dataset(X, y) - >>> - >>> # (2) Define your model: - >>> class LinearModel(ju.Module): - ... weight: float = ju.param(ju.Identity) - ... bias: float = ju.param(ju.Identity) - ... - ... def __call__(self, x): - ... return self.weight * x + self.bias - ... - >>> model = LinearModel(weight=1.0, bias=1.0) - >>> - >>> # (3) Define your loss function: - >>> class MeanSqaureError(ju.Objective): - ... def evaluate(self, model: LinearModel, train_data: ju.Dataset) -> float: - ... return jnp.mean((train_data.y - model(train_data.X)) ** 2) - ... - >>> loss = MeanSqaureError() - >>> - >>> # (4) Train! - >>> trained_model, history = ju.fit( - ... model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=1000 - ... ) - Args: - model (Module): The model Module to be optimised. - objective (Objective): The objective function that we are optimising with respect to. + params (Parameters): The parameters to be optimised. + objective (callable[[Parameters, Dataset], Float[Array, "1"]]): The objective function that we are optimising with respect to. train_data (Dataset): The training data to be used for the optimisation. optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. @@ -95,8 +61,6 @@ def fit( """ # Check inputs. - _check_model(model) - _check_objective(objective) _check_train_data(train_data) _check_optim(optim) _check_num_iters(num_iters) @@ -106,45 +70,46 @@ def fit( _check_verbose(verbose) # Unconstrained space loss function with stop-gradient rule for non-trainable params. - def loss(model: Module, batch: Dataset) -> Float[Array, "1"]: - model = model.stop_gradients() - return objective(model.constrain(), batch) + def loss(params: Parameters, batch: Dataset) -> Float[Array, "1"]: + params = params.stop_gradients() + return objective(params.constrain(), batch) - # Unconstrained space model. - model = model.unconstrain() + # Unconstrained space params. + params = params.unconstrain() # Initialise optimiser state. - state = optim.init(model) + state = optim.init(params) # Mini-batch random keys to scan over. iter_keys = jr.split(key, num_iters) # Optimisation step. def step(carry, key): - model, opt_state = carry + params, opt_state = carry if batch_size != -1: batch = get_batch(train_data, batch_size, key) else: batch = train_data - loss_val, loss_gradient = jax.value_and_grad(loss)(model, batch) - updates, opt_state = optim.update(loss_gradient, opt_state, model) - model = ox.apply_updates(model, updates) + loss_val, loss_gradient = jax.value_and_grad(loss)(params, batch) + updates, opt_state = optim.update(loss_gradient, opt_state, params) + params = ox.apply_updates(params, updates) - carry = model, opt_state + carry = params, opt_state return carry, loss_val # Optimisation scan. scan = vscan if verbose else jax.lax.scan # Optimisation loop. - (model, _), history = scan(step, (model, state), (iter_keys), unroll=unroll) + (params, _), history = scan(step, (params, state), (iter_keys), unroll=unroll) # Constrained space. - model = model.constrain() + params = params.constrain() + params.training_history = history - return model, history + return params def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: @@ -166,18 +131,6 @@ def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset: return Dataset(X=x[indicies], y=y[indicies]) -def _check_model(model: Any) -> None: - """Check that the model is of type Module. Check trainables and bijectors tree structure.""" - if not isinstance(model, Module): - raise TypeError("model must be of type jaxutils.Module") - - -def _check_objective(objective: Any) -> None: - """Check that the objective is of type Objective.""" - if not isinstance(objective, Objective): - raise TypeError("objective must be of type jaxutils.Objective") - - def _check_train_data(train_data: Any) -> None: """Check that the train_data is of type Dataset.""" if not isinstance(train_data, Dataset): diff --git a/jaxutils/module.py b/jaxutils/module.py deleted file mode 100644 index 313c3c5..0000000 --- a/jaxutils/module.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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. -# ============================================================================== - -from __future__ import annotations -import jax -import jax.tree_util as jtu -from jax import lax -from dataclasses import field, Field -from typing import Any -from .distributions import Distribution -from .bijectors import Bijector, Identity -from .pytree import PyTree, _unpack_metatree_leaves - - -def param( - bijector: Bijector, - trainable: bool = True, - prior: Distribution = None, - **kwargs: Any, -) -> Field: - """Used for marking default parameter transformations, trainable statuses and prior distributions for Module. - - Args: - transform (Bijector): The default bijector that should be should upon Module initialisation. - trainable (bool): Whether the parameter should be trainable or not. - prior (Distribution): The prior distribution for the parameter. - **kwargs (Any): If any are passed then they are passed on to `datacalss.field`. - (Recall that JaxUtils uses dataclasses for its modules, based on Equinox's infrastructure.) - - Returns: - Field: A `dataclasses.Field` object with the `bijector`, `trainable` and `prior` metadata set. - """ - - try: - metadata = dict(kwargs["metadata"]) - except KeyError: - metadata = kwargs["metadata"] = {} - if "bijector" in metadata: - raise ValueError("Cannot use metadata with `bijector` already set.") - metadata["bijector"] = bijector - if "trainable" in metadata: - raise ValueError("Cannot use metadata with `trainable` already set.") - metadata["trainable"] = trainable - if "prior" in metadata: - raise ValueError("Cannot use metadata with `prior` already set.") - metadata["prior"] = prior - if "param" in metadata: - raise ValueError("Cannot use metadata with `param` already set.") - metadata["param"] = True - - return field(**kwargs) - - -class Module(PyTree): - """Base Module object. - - Example: - TODO: Give example. - """ - - @property - def module_at(self): - from ._module import _ModuleNodeUpdateHelper - - return _ModuleNodeUpdateHelper(self) - - def constrain(self): - """Transform model parameters to the constrained space according to their defined bijectors. - - Returns: - Module: tranformed to the constrained space. - """ - return _metadata_map( - lambda leaf, meta: meta.get("bijector", Identity).forward(leaf), self - ) - - def unconstrain(self): - """Transform model parameters to the unconstrained space according to their defined bijectors. - - Returns: - Module: tranformed to the unconstrained space. - """ - return _metadata_map( - lambda leaf, meta: meta.get("bijector", Identity).inverse(leaf), self - ) - - def stop_gradients(self): - """Stop gradients flowing through the module. - - Returns: - Module: with gradients stopped. - """ - # Stop gradients flowing through a given leaf if it is not trainable. - def _stop_grad(leaf: jax.Array, trainable: bool) -> jax.Array: - return lax.cond(trainable, lambda x: x, lax.stop_gradient, leaf) - - return _metadata_map( - lambda leaf, meta: _stop_grad(leaf, meta.get("trainable", True)), self - ) - - -def _metadata_map(f: Callable[[Any, Dict[str, Any]], Any], pytree: PyTree) -> PyTree: - """Apply a function to a pytree where the first argument are the pytree leaves, and the second argument are the pytree metadata leaves. - - Args: - f (Callable[[Any, Dict[str, Any]], Any]): The function to apply to the pytree. - pytree (PyTree): The pytree to apply the function to. - - Returns: - PyTree: The transformed pytree. - """ - leaves, treedef = jtu.tree_flatten(pytree) - meta_leaves = _unpack_metatree_leaves(pytree) - all_leaves = [leaves] + [meta_leaves] - return treedef.unflatten(f(*xs) for xs in zip(*all_leaves)) diff --git a/jaxutils/node.py b/jaxutils/node.py deleted file mode 100644 index b18cd65..0000000 --- a/jaxutils/node.py +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 non-public module defines PyTree node updating functionality for the `jaxutils.Module` via the `jax.numpy` e.g. `.at` and `.set` syntax.""" - -from __future__ import annotations -from typing import Any, Callable, Sequence, TypeVar -import jax.tree_util as jtu -from .pytree import PyTree - -NodeType = TypeVar("NodeType", bound=PyTree) - - -class _LeafWrapper: - __slots__ = ("value",) - - def __init__(self, value: Any): - self.value = value - - -def _remove_leaf_wrapper(x: _LeafWrapper) -> Any: - assert type(x) is _LeafWrapper - return x.value - - -class _CountedIdDict: - __slots__ = ( - "_dict", - "_count", - ) - - def __init__(self, keys, values): - assert len(keys) == len(values) - self._dict = {id(k): v for k, v in zip(keys, values)} - self._count = {id(k): 0 for k in keys} - - def __contains__(self, item): - return id(item) in self._dict - - def __getitem__(self, item): - self._count[id(item)] += 1 - return self._dict[id(item)] - - def get(self, item, default): - try: - return self[item] - except KeyError: - return default - - def count(self, item): - return self._count[id(item)] - - -# TODO: Clean up the inside code of this function. -def node_at( - where: Callable[[NodeType], Sequence[NodeType]], - pytree: PyTree, - operator: Callable[[NodeType], Any] = None, - node_type: NodeType = PyTree, -): - """Update a PyTree node or nodes in-place. - - Args: - where (Callable[[NodeType], Sequence[NodeType]]): A function that takes a node of type `node_type` and returns a sequence of nodes of type `node_type`. - pytree (PyTree): The PyTree to update. - replace (Sequence[Any]): A sequence of leaves to replace the nodes returned by `where`. Must be specified if `replace_fn` is not specified. - replace_fn (Callable[[NodeType], Any]): A function that takes a node of type `node_type` and returns a leaf to replace the node. Must be specified if `replace` is not specified. - node_type (NodeType): The type of the nodes to update. Defaults to `PyTree`. - - Returns: - PyTree: The updated PyTree. - - Acknowledgements: - Adapted from Equinox's `tree_at`. - """ - is_leaf = lambda x: isinstance(x, node_type) and not pytree - - node_or_nodes_nowrapper = where(pytree) - pytree = jtu.tree_map(_LeafWrapper, pytree, is_leaf=is_leaf) - node_or_nodes = where(pytree) - leaves1, structure1 = jtu.tree_flatten(node_or_nodes_nowrapper, is_leaf=is_leaf) - leaves2, structure2 = jtu.tree_flatten(node_or_nodes) - leaves2 = [_remove_leaf_wrapper(x) for x in leaves2] - if ( - structure1 != structure2 - or len(leaves1) != len(leaves2) - or any( - l1 is not l2 and isinstance(l1, node_type) - for l1, l2 in zip(leaves1, leaves2) - ) - ): - raise ValueError( - "`where` must use just the PyTree structure of `pytree`. `where` must not " - "depend on the leaves in `pytree`." - ) - del node_or_nodes_nowrapper, leaves1, structure1, leaves2, structure2 - - # Normalise whether we were passed a single node or a sequence of nodes. - in_pytree = False - - def _in_pytree(x): - nonlocal in_pytree - if x is node_or_nodes: # noqa: F821 - in_pytree = True - return x # needed for jax.tree_util.Partial, which has a dodgy constructor - - jtu.tree_map(_in_pytree, pytree, is_leaf=lambda x: x is node_or_nodes) # noqa: F821 - - if in_pytree: - nodes = (node_or_nodes,) - else: - nodes = node_or_nodes - - del in_pytree, node_or_nodes - - def _replace_fn(x): - x = jtu.tree_map(_remove_leaf_wrapper, x) - return operator(x) - - replace_fns = [_replace_fn] * len(nodes) - node_replace_fns = _CountedIdDict(nodes, replace_fns) - - # Actually do the replacement - def _make_replacement(x: NodeType) -> Any: - return node_replace_fns.get(x, _remove_leaf_wrapper)(x) - - out = jtu.tree_map( - _make_replacement, pytree, is_leaf=lambda x: x in node_replace_fns - ) - - # Check that `where` is well-formed. - for node in nodes: - count = node_replace_fns.count(node) - if count == 0: - raise ValueError( - "`where` does not specify an element or elements of `pytree`." - ) - elif count == 1: - pass - else: - raise ValueError( - "`where` does not uniquely identify a single element of `pytree`. This " - "usually occurs when trying to replace a `None` value:\n" - "\n" - " >>> eqx.tree_at(lambda t: t[0], (None, None, 1), True)\n" - "\n" - "\n" - "for which the fix is to specify that `None`s should be treated as " - "leaves:\n" - "\n" - " >>> eqx.tree_at(lambda t: t[0], (None, None, 1), True,\n" - " ... is_leaf=lambda x: x is None)" - ) - - return out diff --git a/jaxutils/objective.py b/jaxutils/objective.py deleted file mode 100644 index b25adc4..0000000 --- a/jaxutils/objective.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. 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 -# -# 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 abc -from dataclasses import field -from jaxtyping import Float, Array - -from .pytree import PyTree -from .dataset import Dataset -from .module import Module - - -class Objective(PyTree): - """Base class for objective functions. - - Example: - >>> from jax import numpy as jnp - >>> from jaxutils import Objective - >>> - >>> class MeanSquaredError(Objective): - ... def evaluate(self, model, train_data): - ... return jnp.mean((train_data.y - model(train_data.X)) ** 2) - ... - >>> mse = MeanSquaredError() - - Note: - The objective function is negated if `negative=True`. - """ - - negative: bool = field(metadata={"static": True}) - constant: float = field(metadata={"static": True}) - - def __init__(self, negative: bool = False): - """Initialise the objective function. - - Args: - negative(bool): Whether to negate the objective function. - - Returns: - Objective: An objective function. - """ - - if not isinstance(negative, bool): - raise TypeError("negative must be a bool.") - - self.negative = negative - self.constant = -1.0 if negative else 1.0 - - def __call__(self, model: Module, train_data: Dataset) -> Float[Array, "1"]: - """Evaluate the objective function. - - Args: - model(Base): A model. - *args: Additional arguments. - **kwargs: Additional keyword arguments. - - Returns: - float: The objective function. - """ - return self.constant * self.evaluate(model, train_data) - - @abc.abstractmethod - def evaluate(self, model: Module, train_data: Dataset) -> Float[Array, "1"]: - """Evaluate the objective function. - - Args: - model(Base): A model. - *args: Additional arguments. - **kwargs: Additional keyword arguments. - - Returns: - float: The objective function. - """ - - -__all__ = [ - "Objective", -] diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py new file mode 100644 index 0000000..e6365ff --- /dev/null +++ b/jaxutils/parameters.py @@ -0,0 +1,133 @@ +# Copyright 2023 The JaxGaussianProcesses Contributors. 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 +# +# 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. +# ============================================================================== + +from __future__ import annotations + +import jax.tree_util as jtu +import jax +from typing import Dict, Any +from .bijectors import Identity +from simple_pytree import Pytree, static_field + + +class Parameters(Pytree, dict): + """ + The state of the model. This includes the parameter set, which parameters + are to be trained and bijectors that allow parameters to be constrained and + unconstrained. + """ + + _param_dict: Dict + _bijector_dict: Dict = static_field() + _trainable_dict: Dict = static_field() + _training_history: list = static_field() + + def __init__( + self, + params: Dict, + bijectors: Dict = None, + trainables: Dict = None, + training_history: list = None, + ): + + if bijectors is None: + bijectors = jtu.tree_map(lambda _: Identity, params) + + if trainables is None: + trainables = jtu.tree_map(lambda _: True, params) + + self._param_dict = params + self._trainable_dict = trainables + self._bijector_dict = bijectors + self._training_history = training_history + + def __repr__(self) -> str: + return f"Parameters({self.params.__repr__()})" + + def __getitem__(self, __name: str) -> Any: + return self._param_dict.__getitem__(__name) + + def __setitem__(self, __name: str, __value: Any) -> None: + return self._param_dict.__setitem__(__name, __value) + + @property + def params(self) -> Dict: + return self._param_dict + + def update_params(self, value: Dict) -> Parameters: + return Parameters(value, self.bijectors, self.trainables, self.training_history) + + @property + def bijectors(self) -> Dict: + return self._bijector_dict + + def update_bijectors(self, value: Dict) -> Parameters: + return Parameters(self.params, value, self.trainables, self.training_history) + + @property + def trainables(self) -> Dict: + return self._trainable_dict + + def update_trainables(self, value: Dict) -> Parameters: + return Parameters(self.params, self.bijectors, value, self.training_history) + + @property + def training_history(self) -> list: + return self._training_history + + def update_training_history(self, value: list) -> Parameters: + return Parameters( + self.params, + self.bijectors, + self.trainables, + self.training_history.append(value), + ) + + def unpack(self): + """Unpack the state into a tuple of parameters, trainables and bijectors. + + Returns: + Tuple[Dict, Dict, Dict]: The parameters, trainables and bijectors. + """ + return self.params, self.trainables, self.bijectors + + def constrain(self): + return self.update_params( + jtu.tree_map( + lambda param, trans: trans.forward(param), self.params, self.bijectors + ) + ) + + def unconstrain(self): + return self.update_params( + jtu.tree_map( + lambda param, trans: trans.inverse(param), self.params, self.bijectors + ) + ) + + def stop_gradients(self): + def _stop_grad(param: Dict, trainable: Dict) -> Dict: + return jax.lax.cond(trainable, lambda x: x, jax.lax.stop_gradient, param) + + return self.update_params( + jtu.tree_map( + lambda param, trainable: _stop_grad(param, trainable), + self.params, + self.trainables, + ) + ) + + +__all__ = ["Parameters"] diff --git a/jaxutils/pytree.py b/jaxutils/pytree.py index 92d0501..c16a356 100644 --- a/jaxutils/pytree.py +++ b/jaxutils/pytree.py @@ -1,4 +1,4 @@ -# Copyright 2023 The JaxGaussianProcesses Contributors. All Rights Reserved. +# Copyright 2022 The JaxGaussianProcesses Contributors. 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. @@ -13,286 +13,65 @@ # limitations under the License. # ============================================================================== -"""This is based on the simple-pytree package by @cgarciae. Adapted to use static field convention of Equinox, and added metadata functionality.""" - -from __future__ import annotations - -import dataclasses -from dataclasses import field, Field -from abc import ABCMeta -from typing import Any, Set, Dict, List -from copy import copy, deepcopy - +import abc import jax -import jax.tree_util as jtu - - -def static(**kwargs: Any) -> Field: - """Used for marking that a field should _not_ be treated as a leaf of the PyTree. - - Equivalent to `equinox.static_field`. - - Args: - **kwargs (Any): If any are passed then they are passed on to `dataclass.field`. - """ - try: - metadata = dict(kwargs["metadata"]) - except KeyError: - metadata = kwargs["metadata"] = {} - if "static" in metadata: - raise ValueError("Cannot use metadata with `static` already set.") - metadata["static"] = True - return field(**kwargs) - - -class PyTreeMeta(ABCMeta): - """Metaclass for PyTree.""" - - def __call__(self, *args: Any, **kwds: Any): - obj: PyTree = super().__call__(*args, **kwds) - object.__setattr__(obj, "_pytree__initialized", True) +from typing import Any + +# TODO: To drop this in place of simple_pytree's Pytree. + + +class PyTree(metaclass=abc.ABCMeta): + """An abstract base class for a JAX compatible pytree. Adapted from `distrax._src.utils.jittable.Jittable`.""" + + def __new__(cls, *args, **kwargs): + # Discard the parameters to this function because the constructor is not + # called during serialization: its `__dict__` gets repopulated directly. + del args, kwargs + try: + registered_cls = jax.tree_util.register_pytree_node_class(cls) + except ValueError: + registered_cls = cls # Already registered. + return object.__new__(registered_cls) + + def tree_flatten(self): + leaves, treedef = jax.tree_util.tree_flatten(self.__dict__) + switch = list(map(is_jax_type, leaves)) + children = [leaf if s else None for leaf, s in zip(leaves, switch)] + metadata = [None if s else leaf for leaf, s in zip(leaves, switch)] + return children, (metadata, switch, treedef) + + @classmethod + def tree_unflatten(cls, aux_data, children): + metadata, switch, treedef = aux_data + leaves = [j if s else p for j, p, s in zip(children, metadata, switch)] + obj = object.__new__(cls) + obj.__dict__ = jax.tree_util.tree_unflatten(treedef, leaves) return obj -class PyTree(metaclass=PyTreeMeta): - """Base class for PyTree.""" - - _pytree__initialized: bool - _pytree__static_fields: Set[str] - _pytree__class_is_mutable: bool - _pytree__meta: Dict[str, Any] - _pytree__annotations: List[str] - _pytree__is_leaf: Dict[str:bool] - - def __init_subclass__(cls, mutable: bool = False): - - jtu.register_pytree_node( - cls, - flatten_func=tree_flatten, - unflatten_func=lambda *_args: tree_unflatten(cls, *_args), - ) - - class_annotations = _get_all_annotations(cls) - - # init class variables - cls._pytree__initialized = False # initialize mutable - cls._pytree__static_fields = set() - cls._pytree__class_is_mutable = mutable - cls._pytree__meta = {} - cls._pytree__annotations = class_annotations - cls._pytree__is_leaf = {} - - # get class info - class_vars = _get_all_class_vars(cls) - - for field, value in class_vars.items(): - - if "_pytree__" in field or ( - isinstance(value, dataclasses.Field) - and value.metadata is not None - and value.metadata.get("static", False) - ): - - cls._pytree__static_fields.add(field) - - elif isinstance(value, dataclasses.Field) and value.metadata is not None: - cls._pytree__meta[field] = {**value.metadata} - - for field in class_annotations: - if "_pytree__" not in field and ( - field not in cls._pytree__static_fields - and field not in cls._pytree__meta.keys() - ): - cls._pytree__meta[field] = {} - - def _replace_meta(self, **kwargs: Any) -> PyTree: - """ - Replace the values of the fields of the object with the values of the - keyword arguments. If the object is a dataclass, `dataclasses.replace` - will be used. Otherwise, a new object will be created with the same - type as the original object. - """ - for key in kwargs: - if key not in self._pytree__meta.keys(): - raise ValueError(f"'{key}' is not a leaf of {type(self).__name__}") - - pytree = copy(self) - pytree.__dict__.update(_pytree__meta={**pytree._pytree__meta, **kwargs}) - return pytree - - def _update_meta(self, **kwargs: Any) -> PyTree: - """ - Replace the values of the fields of the object with the values of the - keyword arguments. If the object is a dataclass, `dataclasses.replace` - will be used. Otherwise, a new object will be created with the same - type as the original object. - """ - for key in kwargs: - if key not in self._pytree__meta.keys(): - raise ValueError( - f"'{key}' is not an attribute of {type(self).__name__}" - ) - - # TODO: Simplify. - pytree = copy(self) - new = deepcopy(pytree._pytree__meta) - for key in kwargs: - if key in new: - new[key].update(kwargs[key]) - else: - new[key] = kwargs[key] - pytree.__dict__.update(_pytree__meta=new) - return pytree - - def _replace(self: PyTree, **kwargs: PyTree) -> PyTree: - """ - Replace the values of the fields of the object with the values of the - keyword arguments. If the object is a dataclass, `dataclasses.replace` - will be used. Otherwise, a new object will be created with the same - type as the original object. - """ - if dataclasses.is_dataclass(self): - return dataclasses.replace(self, **kwargs) - - fields = vars(self) - for key in kwargs: - if key not in fields: - raise ValueError(f"'{key}' is not a field of {type(self).__name__}") +def is_jax_type(x: Any) -> bool: + """Check whether `x` is an instance of a JAX-compatible type.""" + # If it's a tracer, then it's already been converted by JAX. + if isinstance(x, jax.core.Tracer): + return True - pytree = copy(self) - pytree.__dict__.update(kwargs) - return pytree + # `jax.vmap` replaces vmappable leaves with `object()` during serialization. + if type(x) is object: # pylint: disable=unidiomatic-typecheck + return True - def __setattr__(self, field: str, value: Any): + # Primitive types (e.g. shape tuples) are treated as metadata for Distrax. + if isinstance(x, (bool, int, float)) or x is None: + return False - if field not in self._pytree__annotations: - raise AttributeError(f"{type(self)} has no annotation field {field}.") - - if self._pytree__initialized and not self._pytree__class_is_mutable: - raise AttributeError( - f"{type(self)} is immutable, trying to update field {field}." - ) - - _field_is_static = field in self._pytree__static_fields - _value_is_pytree = ( - jtu.tree_map( - lambda x: isinstance(x, PyTree), - value, - is_leaf=lambda x: isinstance(x, PyTree), - ) - == False - ) - _is_leaf = _value_is_pytree and not _field_is_static - object.__setattr__( - self, "_pytree__is_leaf", {**self._pytree__is_leaf, field: _is_leaf} - ) - object.__setattr__(self, field, value) - - @property - def pytree_at(self): - from ._pytree import _PyTreeNodeUpdateHelper - - return _PyTreeNodeUpdateHelper(self) - - -def tree_flatten(pytree: PyTree): - node_fields = {} - static_fields = {} - - for field, value in vars(pytree).items(): - if field in pytree._pytree__static_fields: - static_fields[field] = value - else: - node_fields[field] = value - - return (node_fields,), static_fields - - -def tree_unflatten(cls: PyTree, static_fields, children): - """ - Unflattens a PyTree. - - Args: - cls (PyTree): Class to unflatten. - - Returns: - PyTree: Unflattened PyTree. - """ - (node_fields,) = children - pytree = cls.__new__(cls) - pytree.__dict__.update(node_fields, **static_fields) - return pytree - - -def _get_all_class_vars(cls: type) -> Dict[str, Any]: - """ - Returns a dictionary of all the class variables of a class. - - Args: - cls (type): Class to get the class variables of. - - Returns: - Dict[str, Any]: Dictionary of all the class variables of the class. - """ - d = {} - for c in reversed(cls.mro()): - if hasattr(c, "__dict__"): - d.update(vars(c)) - return d - - -def _get_all_annotations(cls: type) -> Dict[str, type]: - """ - Returns a dictionary of all the annotations of a class. - - Args: - cls (type): Class to get the annotations of. - - Returns: - Dict[str, type]: Dictionary of all the annotations of the class. - """ - d = {} - for c in reversed(cls.mro()): - if hasattr(c, "__annotations__"): - d.update(**c.__annotations__) - return d - - -def _unpack_metatree_leaves(pytree: PyTree) -> List[Dict[str, Any]]: - """ - Returns a list of the PyTree leaves' metadata. - - Args: - pytree (PyTree): PyTree to get the metadata of the leaves. - - Returns: - List[Dict[str, Any]]: List of the PyTree leaves' metadata. - """ - _leaf_metadata = [ - pytree._pytree__meta[k] - for k, _is_leaf_bool in pytree._pytree__is_leaf.items() - if _is_leaf_bool - ] - - def _nested_unpack_metadata(pytree: PyTree, *rest: PyTree) -> None: - if isinstance(pytree, PyTree): - _leaf_metadata.extend( - [ - pytree._pytree__meta[k] - for k, _is_leaf_bool in pytree._pytree__is_leaf.items() - if _is_leaf_bool - ] - ) - _unpack_metadata(pytree, *rest) - - def _unpack_metadata(pytree: PyTree, *rest: PyTree) -> None: - pytrees = (pytree,) + rest - _ = jax.tree_map( - _nested_unpack_metadata, - *pytrees, - is_leaf=lambda x: isinstance(x, PyTree) and not x in pytrees, - ) + # Otherwise, try to make it into a tracer. If it succeeds, then it's JAX data. + try: + jax.xla.abstractify(x) + return True + except TypeError: + return False - _unpack_metadata(pytree) - return _leaf_metadata +__all__ = [ + "PyTree", + "is_jax_type", +] From 3710e9c8080e2b8cb4415291d75da84aa8d527c4 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Mar 2023 13:43:28 +0000 Subject: [PATCH 57/81] Add stuff to __init__ --- jaxutils/__init__.py | 14 +++++--------- jaxutils/bijectors.py | 8 +++++++- jaxutils/fit.py | 6 +++--- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/jaxutils/__init__.py b/jaxutils/__init__.py index 3f5431d..ef1b894 100644 --- a/jaxutils/__init__.py +++ b/jaxutils/__init__.py @@ -13,10 +13,9 @@ # limitations under the License. # ============================================================================== -from .pytree import PyTree, static -from .module import Module, param -from .bijectors import Bijector, Identity, Softplus -from .objective import Objective +from .pytree import PyTree +from .parameters import Parameters +from .bijectors import Identity, Softplus, FillScaleTriL from .dataset import Dataset from .fit import fit, get_batch from .scan import vscan @@ -33,13 +32,10 @@ __all__ = [ "PyTree", - "static", - "Module", - "param", - "Bijector", + "Parameters", "Identity", "Softplus", - "Objective", + "FillScaleTriL", "Dataset", "fit", "get_batch", diff --git a/jaxutils/bijectors.py b/jaxutils/bijectors.py index adea7d8..4676542 100644 --- a/jaxutils/bijectors.py +++ b/jaxutils/bijectors.py @@ -15,7 +15,7 @@ import distrax as dx import jax.numpy as jnp -import tensorflow_probability.substrates.jax as tfb +import tensorflow_probability.substrates.jax.bijectors as tfb Identity = dx.Lambda(forward=lambda x: x, inverse=lambda x: x) @@ -29,3 +29,9 @@ tfb.FillScaleTriL(diag_shift=jnp.array(1e-6)), ] ) + +__all__ = [ + "Identity", + "Softplus", + "FillScaleTriL", +] diff --git a/jaxutils/fit.py b/jaxutils/fit.py index 1508284..d7600be 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -13,7 +13,7 @@ # limitations under the License. # ============================================================================== -from typing import Optional, Tuple +from typing import Optional, Tuple, Callable import jax import jax.random as jr @@ -32,7 +32,7 @@ def fit( *, params: Parameters, - objective: callable[[Parameters, Dataset], Float[Array, "1"]], + objective: Callable[[Parameters, Dataset], Float[Array, "1"]], train_data: Dataset, optim: ox.GradientTransformation, num_iters: Optional[int] = 100, @@ -46,7 +46,7 @@ def fit( Args: params (Parameters): The parameters to be optimised. - objective (callable[[Parameters, Dataset], Float[Array, "1"]]): The objective function that we are optimising with respect to. + objective (Callable[[Parameters, Dataset], Float[Array, "1"]]): The objective function that we are optimising with respect to. train_data (Dataset): The training data to be used for the optimisation. optim (GradientTransformation): The Optax optimiser that is to be used for learning a parameter set. num_iters (Optional[int]): The number of optimisation steps to run. Defaults to 100. From aadf1d013962f8c4bde870298457a287f00d6a9f Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Mar 2023 14:36:26 +0000 Subject: [PATCH 58/81] Minimal test for `fit`. --- jaxutils/fit.py | 2 +- jaxutils/parameters.py | 4 +- tests/test_bijectors.py | 36 ---- tests/test_fit.py | 45 +++-- tests/test_module.py | 386 ---------------------------------------- tests/test_objective.py | 54 ------ 6 files changed, 23 insertions(+), 504 deletions(-) delete mode 100644 tests/test_bijectors.py delete mode 100644 tests/test_module.py delete mode 100644 tests/test_objective.py diff --git a/jaxutils/fit.py b/jaxutils/fit.py index d7600be..509bfe8 100644 --- a/jaxutils/fit.py +++ b/jaxutils/fit.py @@ -107,7 +107,7 @@ def step(carry, key): # Constrained space. params = params.constrain() - params.training_history = history + params = params.update_training_history(history) return params diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index e6365ff..1153166 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -39,7 +39,7 @@ def __init__( params: Dict, bijectors: Dict = None, trainables: Dict = None, - training_history: list = None, + training_history=None, ): if bijectors is None: @@ -92,7 +92,7 @@ def update_training_history(self, value: list) -> Parameters: self.params, self.bijectors, self.trainables, - self.training_history.append(value), + value, ) def unpack(self): diff --git a/tests/test_bijectors.py b/tests/test_bijectors.py deleted file mode 100644 index e89529e..0000000 --- a/tests/test_bijectors.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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 jax.numpy as jnp -import pytest -from jaxutils.bijectors import Bijector, Identity, Softplus -from typing import Callable - -@pytest.mark.parametrize("fwd", [lambda x: x, lambda x: jnp.log(x)]) -@pytest.mark.parametrize("inv", [lambda x: x, lambda x: jnp.exp(x)]) -def test_bijector(fwd: Callable, inv: Callable) -> None: - b = Bijector(fwd, inv) - assert b.forward(1.0) == fwd(1.0) - assert b.inverse(1.0) == inv(1.0) - -def test_identity() -> None: - b = Identity - assert b.forward(10.0) == 10.0 - assert b.inverse(29.0) == 29.0 - -def test_softplus() -> None: - b = Softplus - assert b.forward(10.0) == jnp.log(1.0 + jnp.exp(10.0)) - assert b.inverse(29.0) == jnp.log(jnp.exp(29.0) - 1.0) \ No newline at end of file diff --git a/tests/test_fit.py b/tests/test_fit.py index 4e3c255..2ea8a7d 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -15,13 +15,11 @@ from jaxutils.dataset import Dataset from jaxutils.fit import fit -from jaxutils.bijectors import Identity -from jaxutils.module import param, Module -from jaxutils.objective import Objective - +from jaxutils.parameters import Parameters import jax.numpy as jnp import jax.random as jr import optax as ox +from simple_pytree import Pytree def test_simple_linear_model(): @@ -31,31 +29,28 @@ def test_simple_linear_model(): D = Dataset(X, y) # (2) Define your model: - class LinearModel(Module): - weight: float = param(Identity) - bias: float = param(Identity) - - def __init__(self, weight: float, bias: float): - self.weight = weight - self.bias = bias - - def __call__(self, x): - return self.weight * x + self.bias + class LinearModel(Pytree): + def predict(self, params: Parameters, x): + return params["weight"] * x + params["bias"] - model = LinearModel(weight=1.0, bias=1.0) + def init_params(self): + return Parameters({"weight": 1.0, "bias": 1.0}) - # (3) Define your loss function: - class MeanSqaureError(Objective): - def evaluate(self, model: LinearModel, train_data: Dataset) -> float: - return jnp.mean((train_data.y - model(train_data.X)) ** 2) + def objective(self, params: Parameters, train_data: Dataset) -> float: + return jnp.mean((train_data.y - self.predict(params, train_data.X)) ** 2) - loss = MeanSqaureError() + model = LinearModel() + params = model.init_params() # (4) Train! - trained_model, hist = fit( - model=model, objective=loss, train_data=D, optim=ox.sgd(0.001), num_iters=100 + trained_params = fit( + params=params, + objective=model.objective, + train_data=D, + optim=ox.sgd(0.001), + num_iters=100, ) - assert len(hist) == 100 - assert isinstance(trained_model, LinearModel) - assert loss(trained_model, D) < loss(model, D) + assert len(trained_params.training_history) == 100 + assert isinstance(trained_params, Parameters) + assert model.objective(trained_params, D) < model.objective(params, D) diff --git a/tests/test_module.py b/tests/test_module.py deleted file mode 100644 index 297830c..0000000 --- a/tests/test_module.py +++ /dev/null @@ -1,386 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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 jax.numpy as jnp -from jaxutils.pytree import static, _unpack_metatree_leaves -from jaxutils.module import Module, param -from jaxutils.bijectors import Identity, Softplus -import jax.tree_util as jtu -import jax - -from typing import Any -from dataclasses import dataclass - -import jax.tree_util as jtu -import pytest - - -def test_module(): - - # Test init - @dataclass - class SubTree(Module): - param_c: float = param(Identity) - param_d: float = param(Softplus) - param_e: float = param(Softplus) - - @dataclass - class Tree(Module): - param_a: float = param(Identity) - sub_tree: SubTree - param_b: float = param(Softplus) - - tree = Tree( - param_a=1.0, - sub_tree=SubTree(param_c=2.0, param_d=3.0, param_e=4.0), - param_b=5.0, - ) - - assert isinstance(tree, Module) - assert tree.param_a == 1.0 - assert tree.sub_tree.param_c == 2.0 - assert tree.sub_tree.param_d == 3.0 - assert tree.sub_tree.param_e == 4.0 - assert tree.param_b == 5.0 - - # Test default bijectors - bijector_list = [leaf.get("bijector") for leaf in _unpack_metatree_leaves(tree)] - - for b1, b2 in zip( - bijector_list, [Identity, Softplus, Identity, Softplus, Softplus] - ): - assert b1 == b2 - - # Test default trainables - trainable_list = [leaf.get("trainable") for leaf in _unpack_metatree_leaves(tree)] - - for t1, t2 in zip(trainable_list, [True, True, True, True, True]): - assert t1 == t2 - - # Test constrain and unconstrain - constrained = tree.constrain() - unconstrained = tree.unconstrain() - - leafs = jtu.tree_leaves(tree) - - for l1, l2, bij in zip( - leafs, - jtu.tree_leaves(constrained), - [Identity, Softplus, Identity, Softplus, Softplus], - ): - assert bij.forward(l1) == l2 - - for l1, l2, bij in zip( - leafs, - jtu.tree_leaves(unconstrained), - [Identity, Softplus, Identity, Softplus, Softplus], - ): - assert bij.inverse(l1) == l2 - - new_tree = tree.module_at[lambda x: x].trainables(param_b=False) - new_tree = new_tree.module_at[lambda x: x.sub_tree].trainables( - param_c=False, param_e=False - ) - new_trainable_list = [ - leaf.get("trainable") for leaf in _unpack_metatree_leaves(new_tree) - ] - - for t1, t2 in zip(new_trainable_list, [True, False, False, True, False]): - assert t1 == t2 - - # Test stop gradients - def loss(tree): - t = tree.stop_gradients() - return jnp.sum( - t.param_a**2 - + t.sub_tree.param_c**2 - + t.sub_tree.param_d**2 - + t.sub_tree.param_e**2 - + t.param_b**2 - ) - - g = jax.grad(loss)(new_tree) - - assert g.param_a == 2.0 - assert g.sub_tree.param_c == 0.0 - assert g.sub_tree.param_d == 6.0 - assert g.sub_tree.param_e == 0.0 - assert g.param_b == 0.0 - - -def test_tuple_attribute(): - @dataclass - class SubTree(Module): - param_a: int = param(bijector=Identity, default=1) - param_b: int = param(bijector=Softplus, default=2) - param_c: int = param(bijector=Identity, default=3, trainable=False) - - @dataclass - class Tree(Module): - trees: tuple - - tree = Tree((SubTree(), SubTree(), SubTree())) - - assert len([meta.get("trainable") for meta in _unpack_metatree_leaves(tree)]) == 9 - assert len([meta.get("bijector") for meta in _unpack_metatree_leaves(tree)]) == 9 - assert [meta.get("trainable") for meta in _unpack_metatree_leaves(tree)] == [ - True, - True, - False, - True, - True, - False, - True, - True, - False, - ] - assert [meta.get("bijector") for meta in _unpack_metatree_leaves(tree)] == [ - Identity, - Softplus, - Identity, - Identity, - Softplus, - Identity, - Identity, - Softplus, - Identity, - ] - - -def test_list_attribute(): - @dataclass - class SubTree(Module): - param_a: int = param(bijector=Identity, default=1) - param_b: int = param(bijector=Softplus, default=2) - param_c: int = param(bijector=Identity, default=3, trainable=False) - - @dataclass - class Tree(Module): - trees: list - - tree = Tree([SubTree(), SubTree(), SubTree()]) - - assert len([meta.get("trainable") for meta in _unpack_metatree_leaves(tree)]) == 9 - assert len([meta.get("bijector") for meta in _unpack_metatree_leaves(tree)]) == 9 - assert [meta.get("trainable") for meta in _unpack_metatree_leaves(tree)] == [ - True, - True, - False, - True, - True, - False, - True, - True, - False, - ] - assert [meta.get("bijector") for meta in _unpack_metatree_leaves(tree)] == [ - Identity, - Softplus, - Identity, - Identity, - Softplus, - Identity, - Identity, - Softplus, - Identity, - ] - - -def test_module_not_enough_attributes(): - @dataclass - class MyModule1(Module): - weight: Any = param(Identity) - - with pytest.raises(TypeError): - MyModule1() - - @dataclass - class MyModule2(Module): - weight: Any = param(Identity) - - def __init__(self): - return None - - # We don't check this. - # with pytest.raises(AttributeError): - # MyModule2() - - with pytest.raises(TypeError): - MyModule2(1) - - -def test_module_too_many_attributes(): - @dataclass - class MyModule1(Module): - weight: Any = param(Identity) - - with pytest.raises(TypeError): - MyModule1(1, 2) - - @dataclass - class MyModule2(Module): - weight: Any = param(Identity) - - def __init__(self, weight): - self.weight = weight - self.something_else = True - - with pytest.raises(AttributeError): - MyModule2(1) - - -def test_module_setattr_after_init(): - @dataclass - class MyModule(Module): - weight: Any = param(Identity) - - m = MyModule(1) - with pytest.raises(AttributeError): - m.asdf = True - - -def test_wrong_attribute(): - @dataclass - class MyModule(Module): - weight: Any = param(Identity) - - def __init__(self, value): - self.not_weight = value - - with pytest.raises(AttributeError): - MyModule(1) - - -# The main part of this test is to check that __init__ works correctly. -def test_inheritance(): - # no custom init / no custom init - - @dataclass - class MyModule(Module): - weight: Any = param(Identity) - - @dataclass - class MyModule2(MyModule): - weight2: Any = param(Identity) - - m = MyModule2(1, 2) - assert m.weight == 1 - assert m.weight2 == 2 - m = MyModule2(1, weight2=2) - assert m.weight == 1 - assert m.weight2 == 2 - m = MyModule2(weight=1, weight2=2) - assert m.weight == 1 - assert m.weight2 == 2 - with pytest.raises(TypeError): - m = MyModule2(2, weight=2) - - # not custom init / custom init - - @dataclass - class MyModule3(MyModule): - weight3: Any = param(Identity) - - def __init__(self, *, weight3, **kwargs): - self.weight3 = weight3 - super().__init__(**kwargs) - - m = MyModule3(weight=1, weight3=3) - assert m.weight == 1 - assert m.weight3 == 3 - - # custom init / no custom init - - @dataclass - class MyModule4(Module): - weight4: Any = param(Identity) - - @dataclass - class MyModule5(MyModule4): - weight5: Any = param(Identity) - - with pytest.raises(TypeError): - m = MyModule5(value4=1, weight5=2) - - @dataclass - class MyModule6(MyModule4): - pass - - m = MyModule6(weight4=1) - assert m.weight4 == 1 - - # custom init / custom init - - @dataclass - class MyModule7(MyModule4): - weight7: Any = param(Identity) - - def __init__(self, value7, **kwargs): - self.weight7 = value7 - super().__init__(**kwargs) - - m = MyModule7(weight4=1, value7=2) - assert m.weight4 == 1 - assert m.weight7 == 2 - - -def test_static_field(): - @dataclass - class MyModule(Module): - field1: int = param(Identity) - field2: int = static() - field3: int = static(default=3) - - m = MyModule(1, 2) - flat, treedef = jtu.tree_flatten(m) - assert len(flat) == 1 - assert flat[0] == 1 - rm = jtu.tree_unflatten(treedef, flat) - assert rm.field1 == 1 - assert rm.field2 == 2 - assert rm.field3 == 3 - - -# TODO: Wrap methods with a Partial like Equinox does in future. -# def test_wrap_method(): -# @dataclass -# class MyModule(Module): -# a: int = param(Identity) - -# def f(self, b): -# return self.a + b - -# m = MyModule(13) -# assert isinstance(m.f, jtu.Partial) -# flat, treedef = jtu.tree_flatten(m.f) -# assert len(flat) == 1 -# assert flat[0] == 13 -# assert jtu.tree_unflatten(treedef, flat)(2) == 15 - - -def test_init_subclass(): - ran = [] - - @dataclass - class MyModule(Module): - def __init_subclass__(cls, **kwargs): - super().__init_subclass__(**kwargs) - ran.append(True) - - @dataclass - class AnotherModule(MyModule): - pass - - assert ran == [True] diff --git a/tests/test_objective.py b/tests/test_objective.py deleted file mode 100644 index 28a75bc..0000000 --- a/tests/test_objective.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright 2022 The JaxGaussianProcesses Contributors. 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 -# -# 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 jax.numpy as jnp -import pytest -from jaxutils.objective import Objective -from jaxutils.module import Module -from jaxutils.dataset import Dataset - -def test_objective() -> None: - with pytest.raises(TypeError): - Objective() - - with pytest.raises(TypeError): - Objective(negative=False) - - with pytest.raises(TypeError): - Objective(negative=True) - - class DummyModel(Module): - def __call__(self, x: jnp.ndarray) -> jnp.ndarray: - return x - - class DummyObjective(Objective): - def evaluate(self, model: Module, train_data: Dataset) -> float: - return jnp.sum((model(train_data.X) - train_data.y) ** 2) - - - # Test intialisation - objective = DummyObjective() - model = DummyModel() - data = Dataset(jnp.ones((10, 1)), jnp.ones((10, 1))) - assert objective(model, data) == 0.0 - - # Test negative - data_new = Dataset(jnp.linspace(0, 1, 10).reshape(-1, 1), jnp.linspace(2, 5, 10).reshape(-1, 1)) - objective_negative = DummyObjective(negative=True) - assert objective(model, data_new) + objective_negative(model, data_new) == 0.0 - - # Test non-bool negative - with pytest.raises(TypeError): - objective_negative = DummyObjective(negative=123) \ No newline at end of file From 7b63890774bce45468ac5cdd7073003cce172fb0 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Mar 2023 14:44:46 +0000 Subject: [PATCH 59/81] Update fit tests. --- setup.py | 1 + tests/test_fit.py | 31 +++++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/setup.py b/setup.py index 4ca6b40..70c7f26 100644 --- a/setup.py +++ b/setup.py @@ -44,6 +44,7 @@ def get_versions(): "jaxtyping", "optax", "tqdm", + "simple-pytree", ] EXTRAS = { diff --git a/tests/test_fit.py b/tests/test_fit.py index 2ea8a7d..585267f 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -19,7 +19,21 @@ import jax.numpy as jnp import jax.random as jr import optax as ox -from simple_pytree import Pytree +import abc +from dataclasses import dataclass +from simple_pytree import Pytree, static_field +from jaxtyping import Array, Float +from typing import Any + + +### Base class for objective functions: +@dataclass +class Objective(Pytree): + model: Any = static_field() + + @abc.abstractmethod + def __call__(self, params: Parameters, train_data: Dataset) -> Float[Array, "1"]: + raise NotImplementedError def test_simple_linear_model(): @@ -30,22 +44,27 @@ def test_simple_linear_model(): # (2) Define your model: class LinearModel(Pytree): - def predict(self, params: Parameters, x): + def __call__(self, params: Parameters, x): return params["weight"] * x + params["bias"] def init_params(self): return Parameters({"weight": 1.0, "bias": 1.0}) - def objective(self, params: Parameters, train_data: Dataset) -> float: - return jnp.mean((train_data.y - self.predict(params, train_data.X)) ** 2) + # (3) Define your objective: + class MeanSquaredError(Objective): + def __call__( + self, params: Parameters, train_data: Dataset + ) -> Float[Array, "1"]: + return jnp.mean((train_data.y - self.model(params, train_data.X)) ** 2) model = LinearModel() + objective = MeanSquaredError(model) params = model.init_params() # (4) Train! trained_params = fit( params=params, - objective=model.objective, + objective=objective, train_data=D, optim=ox.sgd(0.001), num_iters=100, @@ -53,4 +72,4 @@ def objective(self, params: Parameters, train_data: Dataset) -> float: assert len(trained_params.training_history) == 100 assert isinstance(trained_params, Parameters) - assert model.objective(trained_params, D) < model.objective(params, D) + assert objective(trained_params, D) < objective(params, D) From c95114e855854a4879fa72e6c7417ee03d8ae009 Mon Sep 17 00:00:00 2001 From: Daniel Dodd Date: Thu, 9 Mar 2023 14:47:55 +0000 Subject: [PATCH 60/81] Update setup.py --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 70c7f26..3911d14 100644 --- a/setup.py +++ b/setup.py @@ -45,6 +45,7 @@ def get_versions(): "optax", "tqdm", "simple-pytree", + "distrax", ] EXTRAS = { From 2a67a507738f8fff3ccf56d953ea51c17fb1cd2f Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Thu, 9 Mar 2023 17:15:24 +0000 Subject: [PATCH 61/81] Add basic dict methods --- jaxutils/parameters.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index 1153166..ea42fc8 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -67,21 +67,27 @@ def params(self) -> Dict: return self._param_dict def update_params(self, value: Dict) -> Parameters: - return Parameters(value, self.bijectors, self.trainables, self.training_history) + return Parameters( + value, self.bijectors, self.trainables, self.training_history + ) @property def bijectors(self) -> Dict: return self._bijector_dict def update_bijectors(self, value: Dict) -> Parameters: - return Parameters(self.params, value, self.trainables, self.training_history) + return Parameters( + self.params, value, self.trainables, self.training_history + ) @property def trainables(self) -> Dict: return self._trainable_dict def update_trainables(self, value: Dict) -> Parameters: - return Parameters(self.params, self.bijectors, value, self.training_history) + return Parameters( + self.params, self.bijectors, value, self.training_history + ) @property def training_history(self) -> list: @@ -106,20 +112,26 @@ def unpack(self): def constrain(self): return self.update_params( jtu.tree_map( - lambda param, trans: trans.forward(param), self.params, self.bijectors + lambda param, trans: trans.forward(param), + self.params, + self.bijectors, ) ) def unconstrain(self): return self.update_params( jtu.tree_map( - lambda param, trans: trans.inverse(param), self.params, self.bijectors + lambda param, trans: trans.inverse(param), + self.params, + self.bijectors, ) ) def stop_gradients(self): def _stop_grad(param: Dict, trainable: Dict) -> Dict: - return jax.lax.cond(trainable, lambda x: x, jax.lax.stop_gradient, param) + return jax.lax.cond( + trainable, lambda x: x, jax.lax.stop_gradient, param + ) return self.update_params( jtu.tree_map( @@ -129,5 +141,14 @@ def _stop_grad(param: Dict, trainable: Dict) -> Dict: ) ) + def items(self): + return self.params.items() + + def keys(self): + return self.params.keys() + + def values(self): + return self.params.values() + __all__ = ["Parameters"] From 49559a4fe560928ee41446b3c56b3991889900be Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Fri, 10 Mar 2023 09:19:07 +0000 Subject: [PATCH 62/81] Add priors --- .pre-commit-config.yaml | 19 ++++++++++++------- jaxutils/parameters.py | 41 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b73828e..9b7406d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,12 @@ repos: + - repo: https://github.com/PyCQA/autoflake + rev: v2.0.0 + hooks: + - id: autoflake + args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports", "--recursive"] + name: AutoFlake + description: "Format with AutoFlake" + stages: [commit] - repo: https://github.com/psf/black rev: 22.3.0 hooks: @@ -20,11 +28,8 @@ repos: args: [--py37-plus] - id: nbqa-flake8 args: ['--ignore=E501,E203,E302,E402,E731,W503'] - - repo: https://github.com/PyCQA/autoflake - rev: v2.0.0 + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: 'v0.0.254' hooks: - - id: autoflake - args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports", "--recursive"] - name: AutoFlake - description: "Format with AutoFlake" - stages: [commit] \ No newline at end of file + - id: ruff + args: ['--fix'] \ No newline at end of file diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index ea42fc8..4934337 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -39,6 +39,7 @@ def __init__( params: Dict, bijectors: Dict = None, trainables: Dict = None, + priors: Dict = None, training_history=None, ): @@ -48,9 +49,13 @@ def __init__( if trainables is None: trainables = jtu.tree_map(lambda _: True, params) + if priors is None: + priors = jtu.tree_map(lambda _: None, params) + self._param_dict = params self._trainable_dict = trainables self._bijector_dict = bijectors + self._prior_dict = priors self._training_history = training_history def __repr__(self) -> str: @@ -68,7 +73,11 @@ def params(self) -> Dict: def update_params(self, value: Dict) -> Parameters: return Parameters( - value, self.bijectors, self.trainables, self.training_history + value, + self.bijectors, + self.trainables, + self.priors, + self.training_history, ) @property @@ -77,7 +86,11 @@ def bijectors(self) -> Dict: def update_bijectors(self, value: Dict) -> Parameters: return Parameters( - self.params, value, self.trainables, self.training_history + self.params, + value, + self.trainables, + self.priors, + self.training_history, ) @property @@ -86,7 +99,24 @@ def trainables(self) -> Dict: def update_trainables(self, value: Dict) -> Parameters: return Parameters( - self.params, self.bijectors, value, self.training_history + self.params, + self.bijectors, + value, + self.priors, + self.training_history, + ) + + @property + def priors(self) -> Dict: + return self._prior_dict + + def update_priors(self, value: Dict) -> Parameters: + return Parameters( + self.params, + self.bijectors, + self.trainables, + value, + self.training_history, ) @property @@ -98,6 +128,7 @@ def update_training_history(self, value: list) -> Parameters: self.params, self.bijectors, self.trainables, + self.priors, value, ) @@ -109,7 +140,7 @@ def unpack(self): """ return self.params, self.trainables, self.bijectors - def constrain(self): + def constrain(self) -> Parameters: return self.update_params( jtu.tree_map( lambda param, trans: trans.forward(param), @@ -118,7 +149,7 @@ def constrain(self): ) ) - def unconstrain(self): + def unconstrain(self) -> Parameters: return self.update_params( jtu.tree_map( lambda param, trans: trans.inverse(param), From fd97b43a60b26b832ab9e8e54586ab7171de9a64 Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Fri, 10 Mar 2023 10:04:13 +0000 Subject: [PATCH 63/81] Add log prior density fn --- jaxutils/parameters.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index 4934337..574aa59 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -17,9 +17,12 @@ import jax.tree_util as jtu import jax +import jax.numpy as jnp from typing import Dict, Any from .bijectors import Identity from simple_pytree import Pytree, static_field +from jax.tree_util import tree_flatten +from jaxtyping import Float, Array class Parameters(Pytree, dict): @@ -181,5 +184,33 @@ def keys(self): def values(self): return self.params.values() + def log_prior_density(self) -> Array[Float, "1"]: + """ + Recursive loop over pair of dictionaries that correspond to a parameter's + current value and the parameter's respective prior distribution. For + parameters where a prior distribution is specified, the log-prior density is + evaluated at the parameter's current value. + + Args: params (Dict): Dictionary containing the current set of parameter + estimates. priors (Dict): Dictionary specifying the parameters' prior + distributions. + + Returns: + Dict: The log-prior density, summed over all parameters. + """ + + def log_density(param, prior): + # TODO: Should a jax.lax.cond be used here? The method does jit-compile right now. + if prior is not None: + return jnp.sum(prior.log_prob(param)) + else: + return jnp.array(0.0) + + log_prior_density_dict = jtu.tree_map( + log_density, self.params, self.priors + ) + leaves, _ = tree_flatten(log_prior_density_dict) + return sum(leaves) + __all__ = ["Parameters"] From 37bb0eecf9ebb5bd7334440b0a485e0c13a93a52 Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Fri, 10 Mar 2023 11:21:39 +0000 Subject: [PATCH 64/81] Add unit test --- tests/test_parameters.py | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/test_parameters.py diff --git a/tests/test_parameters.py b/tests/test_parameters.py new file mode 100644 index 0000000..c3a9d9b --- /dev/null +++ b/tests/test_parameters.py @@ -0,0 +1,53 @@ +from jaxutils.parameters import Parameters +import jax +import pytest +import jax.numpy as jnp +import distrax as dx + + +@pytest.mark.parametrize("jit_compile", [False, True]) +def test_priors(jit_compile): + # Vanilla test for case where every parameter has a defined prior + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + priors = {"a": dx.Normal(0.0, 1.0), "b": dx.Normal(0.0, 1.0)} + + params = Parameters(params=param_vals, priors=priors) + if jit_compile: + lpd = jax.jit(params.log_prior_density)() + else: + lpd = params.log_prior_density() + assert pytest.approx(lpd, 0.00001) == -4.3378773 + assert isinstance(lpd, jax.Array) + + # Check fn. works for no priors + priors = {"a": None, "b": None} + params = Parameters(params=param_vals, priors=priors) + if jit_compile: + lpd = jax.jit(params.log_prior_density)() + else: + lpd = params.log_prior_density() + assert pytest.approx(lpd, 0.00001) == 0.0 + assert isinstance(lpd, jax.Array) + + # Check the fn. works for nested structures with incomplete priors + param_vals = { + "a": jnp.array([1.0]), + "b": {"a": jnp.array([10.0]), "b": jnp.array([3.0])}, + } + priors = {"a": None, "b": {"a": dx.Normal(0, 1.0), "b": dx.Gamma(2.0, 2.0)}} + params = Parameters(params=param_vals, priors=priors) + if jit_compile: + lpd = jax.jit(params.log_prior_density)() + else: + lpd = params.log_prior_density() + assert pytest.approx(lpd, 0.00001) == -54.434032 + assert isinstance(lpd, jax.Array) + + # Check the prior initialising works - by default, there are no priors + params = Parameters(param_vals) + if jit_compile: + lpd = jax.jit(params.log_prior_density)() + else: + lpd = params.log_prior_density() + assert pytest.approx(lpd, 0.00001) == 0.0 + assert isinstance(lpd, jax.Array) From 9f7a32a85506839c1787d7302f6e64f67440aaea Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Mon, 13 Mar 2023 08:46:10 +0000 Subject: [PATCH 65/81] Parameters unit tests --- jaxutils/parameters.py | 32 +++++++- tests/test_parameters.py | 170 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+), 4 deletions(-) diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index 574aa59..1e15286 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -18,10 +18,10 @@ import jax.tree_util as jtu import jax import jax.numpy as jnp -from typing import Dict, Any +from typing import Dict, Any, Tuple from .bijectors import Identity from simple_pytree import Pytree, static_field -from jax.tree_util import tree_flatten +from jax.tree_util import tree_flatten, tree_structure from jaxtyping import Float, Array @@ -39,7 +39,7 @@ class Parameters(Pytree, dict): def __init__( self, - params: Dict, + params: Dict, # TODO: Should we block inplace updates of this dict e.g., `params.params['a'] = jnp.array([2.])` would raise an issue. bijectors: Dict = None, trainables: Dict = None, priors: Dict = None, @@ -70,11 +70,17 @@ def __getitem__(self, __name: str) -> Any: def __setitem__(self, __name: str, __value: Any) -> None: return self._param_dict.__setitem__(__name, __value) + def __eq__(self, other: Parameters) -> bool: + return self.params == other.params # TODO: Should priors be included? + @property def params(self) -> Dict: return self._param_dict + # TODO: Benedict would make this awesome: `update_params(self, key, value)` e.g., `update_params('a.b.c', 1)` + # TODO: This should throw an error if the key-structure changes def update_params(self, value: Dict) -> Parameters: + self._validate_update(value, self.params, "params") return Parameters( value, self.bijectors, @@ -83,11 +89,23 @@ def update_params(self, value: Dict) -> Parameters: self.training_history, ) + @staticmethod + def _validate_update(value: dict, comparison: dict, name: str): + if tree_structure(comparison) != tree_structure(value): + print(tree_structure(comparison)) + print(tree_structure(value)) + raise ValueError( + f"The structure of the {name} has changed. Please ensure" + f" updates to {name} do not alter the strcuture." + ) + @property def bijectors(self) -> Dict: return self._bijector_dict def update_bijectors(self, value: Dict) -> Parameters: + # TODO: Traversal doesn't work for nested dicts where the value is a distrax object + # self._validate_update(value, self.bijectors, "bijectors") return Parameters( self.params, value, @@ -101,6 +119,7 @@ def trainables(self) -> Dict: return self._trainable_dict def update_trainables(self, value: Dict) -> Parameters: + self._validate_update(value, self.trainables, "trainables") return Parameters( self.params, self.bijectors, @@ -114,6 +133,8 @@ def priors(self) -> Dict: return self._prior_dict def update_priors(self, value: Dict) -> Parameters: + # TODO: Traversal doesn't work for nested dicts where the value is a distrax object + # self._validate_update(value, self.priors, "priors") return Parameters( self.params, self.bijectors, @@ -135,12 +156,15 @@ def update_training_history(self, value: list) -> Parameters: value, ) - def unpack(self): + def unpack( + self, + ) -> Tuple[Dict[str, jax.Array], Dict[str, bool], Dict[str, Any]]: """Unpack the state into a tuple of parameters, trainables and bijectors. Returns: Tuple[Dict, Dict, Dict]: The parameters, trainables and bijectors. """ + # TODO: Should priors be returned here? return self.params, self.trainables, self.bijectors def constrain(self) -> Parameters: diff --git a/tests/test_parameters.py b/tests/test_parameters.py index c3a9d9b..a903432 100644 --- a/tests/test_parameters.py +++ b/tests/test_parameters.py @@ -1,8 +1,41 @@ from jaxutils.parameters import Parameters +from jaxutils.bijectors import Softplus, Identity import jax import pytest import jax.numpy as jnp import distrax as dx +from jax.config import config +import typing as tp + +config.update("jax_enable_x64", True) + + +def build_params( + param_vals: tp.Dict, + set_priors: bool, + set_trainables: bool, + set_bijectors: bool, +) -> tp.Tuple[Parameters, tp.Dict]: + priors = ( + {"a": dx.Normal(0.0, 1.0), "b": dx.Normal(0.0, 1.0)} + if set_priors + else None + ) + trainables = {"a": True, "b": True} if set_trainables else None + bijections = {"a": Identity, "b": Identity} if set_bijectors else None + params = Parameters( + params=param_vals, + priors=priors, + bijectors=bijections, + trainables=trainables, + ) + truth = { + "params": param_vals, + "priors": priors, + "trainables": trainables, + "bijectors": bijections, + } + return params, truth @pytest.mark.parametrize("jit_compile", [False, True]) @@ -51,3 +84,140 @@ def test_priors(jit_compile): lpd = params.log_prior_density() assert pytest.approx(lpd, 0.00001) == 0.0 assert isinstance(lpd, jax.Array) + + +@pytest.mark.parametrize("jit_compile", [False, True]) +def test_constrain_unconstrain(jit_compile): + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + bijections = {"a": Softplus, "b": Softplus} + params = Parameters(params=param_vals, bijectors=bijections) + + unconstrain_fn = ( + jax.jit(params.unconstrain) if jit_compile else params.unconstrain + ) + + unconstrained_params = unconstrain_fn() + + assert isinstance(unconstrained_params, Parameters) + assert isinstance(unconstrained_params.params, dict) + + constrain_fn = ( + jax.jit(unconstrained_params.constrain) + if jit_compile + else unconstrained_params.constrain + ) + constrained_params = constrain_fn() + assert isinstance(unconstrained_params, Parameters) + assert isinstance(unconstrained_params.params, dict) + + assert constrained_params == params + + +def test_update_param(): + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + bijections = {"a": Softplus, "b": Softplus} + params = Parameters(params=param_vals, bijectors=bijections) + + updated_param_vals = {"a": jnp.array([2.0]), "b": jnp.array([3.0])} + updated_params = params.update_params(updated_param_vals) + + # Check the updated params are correct + assert updated_params.params == updated_param_vals + # Check that nothing else has changed + assert updated_params.bijectors == params.bijectors + assert updated_params.priors == params.priors + assert updated_params.trainables == params.trainables + + # Check that a key structure raises an error + with pytest.raises(ValueError): + updated_params = params.update_params({"a": jnp.array([2.0])}) + + +def test_bijector_update(): + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + bijections = {"a": Softplus, "b": Softplus} + params = Parameters(params=param_vals, bijectors=bijections) + + updated_bijections = {"a": Softplus, "b": Identity} + updated_params = params.update_bijectors(updated_bijections) + + # Check that bijections have been updated + assert updated_params.bijectors == updated_bijections + # Check all else is equal + assert updated_params == params + assert updated_params.trainables == params.trainables + assert updated_params.priors == params.priors + + # Check that a key structure raises an error + # with pytest.raises(ValueError): + # updated_params = params.update_params({"a": Identity}) + + +def test_trainables_update(): + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + trainables = {"a": True, "b": True} + params = Parameters(params=param_vals, trainables=trainables) + + updated_trainables = {"a": True, "b": False} + updated_params = params.update_trainables(updated_trainables) + + # Check that bijections have been updated + assert updated_params.trainables == updated_trainables + # Check all else is equal + assert updated_params == params + assert updated_params.bijectors == params.bijectors + assert updated_params.priors == params.priors + + # Check that a key structure raises an error + with pytest.raises(ValueError): + updated_params = params.update_trainables({"a": True}) + + +def test_priors_update(): + param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + priors = {"a": dx.Normal(0.0, 1.0), "b": dx.Normal(0.0, 1.0)} + params = Parameters(params=param_vals, priors=priors) + + updated_priors = {"a": dx.Normal(0.0, 1.0), "b": dx.Gamma(3.0, 3.0)} + updated_params = params.update_priors(updated_priors) + + # Check that bijections have been updated + assert updated_params.priors == updated_priors + # Check all else is equal + assert updated_params == params + assert updated_params.trainables == params.trainables + assert updated_params.bijectors == params.bijectors + + # Check that a key structure raises an error + # with pytest.raises(ValueError): + # updated_params = params.update_priors({"a": dx.Gamma(3.0, 3.0)}) + + +@pytest.mark.parametrize("set_priors", [True, False]) +@pytest.mark.parametrize("set_trainables", [True, False]) +@pytest.mark.parametrize("set_bijectors", [True, False]) +def test_unpack(set_priors, set_trainables, set_bijectors): + init_param_vals = {"a": jnp.array([1.0]), "b": jnp.array([2.0])} + params, truth = build_params( + init_param_vals, + set_priors, + set_trainables, + set_bijectors, + ) + param_vals, trainables, bijectors = params.unpack() + + assert param_vals == truth["params"] + + if set_trainables: + assert trainables == truth["trainables"] + else: + assert trainables == {"a": True, "b": True} + + if set_bijectors: + assert bijectors == truth["bijectors"] + else: + assert bijectors == {"a": Identity, "b": Identity} + + assert isinstance(param_vals, dict) + assert isinstance(trainables, dict) + assert isinstance(bijectors, dict) From 33a7c6ae3448d944b6b020db125e8c5be322b1af Mon Sep 17 00:00:00 2001 From: Thomas Pinder Date: Mon, 13 Mar 2023 21:49:35 +0000 Subject: [PATCH 66/81] Test key-structure for bijectors and distributions --- jaxutils/parameters.py | 37 +- node_modules/.bin/cdl | 1 + node_modules/.bin/esparse | 1 + node_modules/.bin/esvalidate | 1 + node_modules/.bin/github-copilot-cli | 1 + node_modules/.bin/highlight | 1 + node_modules/.bin/is-ci | 1 + node_modules/.bin/loose-envify | 1 + node_modules/.bin/marked | 1 + node_modules/.bin/rimraf | 1 + node_modules/.bin/semver | 1 + node_modules/.bin/uuid | 1 + node_modules/.package-lock.json | 2318 ++ .../@azure/abort-controller/CHANGELOG.md | 34 + node_modules/@azure/abort-controller/LICENSE | 21 + .../@azure/abort-controller/README.md | 110 + .../dist-esm/src/AbortController.js | 118 + .../dist-esm/src/AbortController.js.map | 1 + .../dist-esm/src/AbortSignal.js | 115 + .../dist-esm/src/AbortSignal.js.map | 1 + .../abort-controller/dist-esm/src/index.js | 12 + .../dist-esm/src/index.js.map | 1 + .../@azure/abort-controller/package.json | 104 + .../@azure/abort-controller/shims-public.d.ts | 5 + .../types/3.1/AbortController.d.ts | 85 + .../types/3.1/AbortSignal.d.ts | 80 + .../abort-controller/types/3.1/index.d.ts | 3 + .../types/src/AbortController.d.ts | 85 + .../types/src/AbortController.d.ts.map | 1 + .../types/src/AbortSignal.d.ts | 80 + .../types/src/AbortSignal.d.ts.map | 1 + .../abort-controller/types/src/index.d.ts | 3 + .../abort-controller/types/src/index.d.ts.map | 1 + .../types/src/tsdoc-metadata.json | 11 + node_modules/@azure/core-auth/LICENSE | 21 + node_modules/@azure/core-auth/README.md | 78 + .../dist-esm/src/azureKeyCredential.js | 38 + .../dist-esm/src/azureKeyCredential.js.map | 1 + .../dist-esm/src/azureNamedKeyCredential.js | 62 + .../src/azureNamedKeyCredential.js.map | 1 + .../dist-esm/src/azureSASCredential.js | 50 + .../dist-esm/src/azureSASCredential.js.map | 1 + .../@azure/core-auth/dist-esm/src/index.js | 7 + .../core-auth/dist-esm/src/index.js.map | 1 + .../core-auth/dist-esm/src/tokenCredential.js | 19 + .../dist-esm/src/tokenCredential.js.map | 1 + .../@azure/core-auth/dist-esm/src/tracing.js | 4 + .../core-auth/dist-esm/src/tracing.js.map | 1 + .../core-auth/dist-esm/src/typeguards.js | 39 + .../core-auth/dist-esm/src/typeguards.js.map | 1 + node_modules/@azure/core-auth/package.json | 87 + .../@azure/core-auth/types/3.1/core-auth.d.ts | 229 + .../core-auth/types/latest/core-auth.d.ts | 243 + .../@azure/core-rest-pipeline/LICENSE | 21 + .../@azure/core-rest-pipeline/README.md | 159 + .../core-rest-pipeline.shims-3_1.d.ts | 12 + .../core-rest-pipeline.shims.d.ts | 12 + .../dist-esm/src/accessTokenCache.js | 32 + .../dist-esm/src/accessTokenCache.js.map | 1 + .../dist-esm/src/constants.js | 5 + .../dist-esm/src/constants.js.map | 1 + .../dist-esm/src/createPipelineFromOptions.js | 41 + .../src/createPipelineFromOptions.js.map | 1 + .../dist-esm/src/defaultHttpClient.browser.js | 10 + .../src/defaultHttpClient.browser.js.map | 1 + .../dist-esm/src/defaultHttpClient.js | 10 + .../dist-esm/src/defaultHttpClient.js.map | 1 + .../dist-esm/src/defaultHttpClient.native.js | 10 + .../src/defaultHttpClient.native.js.map | 1 + .../dist-esm/src/fetchHttpClient.js | 251 + .../dist-esm/src/fetchHttpClient.js.map | 1 + .../dist-esm/src/httpHeaders.js | 89 + .../dist-esm/src/httpHeaders.js.map | 1 + .../core-rest-pipeline/dist-esm/src/index.js | 25 + .../dist-esm/src/index.js.map | 1 + .../dist-esm/src/interfaces.js | 4 + .../dist-esm/src/interfaces.js.map | 1 + .../core-rest-pipeline/dist-esm/src/log.js | 5 + .../dist-esm/src/log.js.map | 1 + .../dist-esm/src/nodeHttpClient.js | 332 + .../dist-esm/src/nodeHttpClient.js.map | 1 + .../dist-esm/src/pipeline.js | 262 + .../dist-esm/src/pipeline.js.map | 1 + .../dist-esm/src/pipelineRequest.js | 35 + .../dist-esm/src/pipelineRequest.js.map | 1 + .../bearerTokenAuthenticationPolicy.js | 108 + .../bearerTokenAuthenticationPolicy.js.map | 1 + .../decompressResponsePolicy.browser.js | 15 + .../decompressResponsePolicy.browser.js.map | 1 + .../src/policies/decompressResponsePolicy.js | 23 + .../policies/decompressResponsePolicy.js.map | 1 + .../src/policies/defaultRetryPolicy.js | 26 + .../src/policies/defaultRetryPolicy.js.map | 1 + .../src/policies/exponentialRetryPolicy.js | 22 + .../policies/exponentialRetryPolicy.js.map | 1 + .../src/policies/formDataPolicy.browser.js | 43 + .../policies/formDataPolicy.browser.js.map | 1 + .../dist-esm/src/policies/formDataPolicy.js | 79 + .../src/policies/formDataPolicy.js.map | 1 + .../dist-esm/src/policies/logPolicy.js | 34 + .../dist-esm/src/policies/logPolicy.js.map | 1 + .../dist-esm/src/policies/ndJsonPolicy.js | 25 + .../dist-esm/src/policies/ndJsonPolicy.js.map | 1 + .../src/policies/proxyPolicy.browser.js | 27 + .../src/policies/proxyPolicy.browser.js.map | 1 + .../dist-esm/src/policies/proxyPolicy.js | 190 + .../dist-esm/src/policies/proxyPolicy.js.map | 1 + .../dist-esm/src/policies/redirectPolicy.js | 52 + .../src/policies/redirectPolicy.js.map | 1 + .../dist-esm/src/policies/retryPolicy.js | 106 + .../dist-esm/src/policies/retryPolicy.js.map | 1 + .../src/policies/setClientRequestIdPolicy.js | 24 + .../policies/setClientRequestIdPolicy.js.map | 1 + .../src/policies/systemErrorRetryPolicy.js | 27 + .../policies/systemErrorRetryPolicy.js.map | 1 + .../src/policies/throttlingRetryPolicy.js | 29 + .../src/policies/throttlingRetryPolicy.js.map | 1 + .../dist-esm/src/policies/tlsPolicy.js | 22 + .../dist-esm/src/policies/tlsPolicy.js.map | 1 + .../dist-esm/src/policies/tracingPolicy.js | 120 + .../src/policies/tracingPolicy.js.map | 1 + .../dist-esm/src/policies/userAgentPolicy.js | 26 + .../src/policies/userAgentPolicy.js.map | 1 + .../dist-esm/src/restError.js | 48 + .../dist-esm/src/restError.js.map | 1 + .../exponentialRetryStrategy.js | 69 + .../exponentialRetryStrategy.js.map | 1 + .../src/retryStrategies/retryStrategy.js | 4 + .../src/retryStrategies/retryStrategy.js.map | 1 + .../throttlingRetryStrategy.js | 74 + .../throttlingRetryStrategy.js.map | 1 + .../dist-esm/src/util/helpers.js | 58 + .../dist-esm/src/util/helpers.js.map | 1 + .../dist-esm/src/util/inspect.browser.js | 4 + .../dist-esm/src/util/inspect.browser.js.map | 1 + .../dist-esm/src/util/inspect.js | 5 + .../dist-esm/src/util/inspect.js.map | 1 + .../dist-esm/src/util/sanitizer.js | 139 + .../dist-esm/src/util/sanitizer.js.map | 1 + .../dist-esm/src/util/tokenCycler.js | 149 + .../dist-esm/src/util/tokenCycler.js.map | 1 + .../dist-esm/src/util/userAgent.js | 30 + .../dist-esm/src/util/userAgent.js.map | 1 + .../src/util/userAgentPlatform.browser.js | 20 + .../src/util/userAgentPlatform.browser.js.map | 1 + .../dist-esm/src/util/userAgentPlatform.js | 17 + .../src/util/userAgentPlatform.js.map | 1 + .../src/util/userAgentPlatform.native.js | 21 + .../src/util/userAgentPlatform.native.js.map | 1 + .../dist-esm/src/util/uuid.js | 13 + .../dist-esm/src/util/uuid.js.map | 1 + .../dist-esm/src/xhrHttpClient.js | 177 + .../dist-esm/src/xhrHttpClient.js.map | 1 + .../core-rest-pipeline/node_modules/.bin/uuid | 1 + .../node_modules/uuid/CHANGELOG.md | 229 + .../node_modules/uuid/CONTRIBUTING.md | 18 + .../node_modules/uuid/LICENSE.md | 9 + .../node_modules/uuid/README.md | 505 + .../node_modules/uuid/package.json | 135 + .../node_modules/uuid/wrapper.mjs | 10 + .../@azure/core-rest-pipeline/package.json | 145 + .../types/3.1/core-rest-pipeline.d.ts | 1085 + .../types/latest/core-rest-pipeline.d.ts | 1164 + node_modules/@azure/core-tracing/CHANGELOG.md | 105 + node_modules/@azure/core-tracing/LICENSE | 21 + node_modules/@azure/core-tracing/README.md | 37 + .../@azure/core-tracing/dist-esm/src/index.js | 5 + .../core-tracing/dist-esm/src/index.js.map | 1 + .../core-tracing/dist-esm/src/instrumenter.js | 61 + .../dist-esm/src/instrumenter.js.map | 1 + .../core-tracing/dist-esm/src/interfaces.js | 4 + .../dist-esm/src/interfaces.js.map | 1 + .../dist-esm/src/tracingClient.js | 74 + .../dist-esm/src/tracingClient.js.map | 1 + .../dist-esm/src/tracingContext.js | 47 + .../dist-esm/src/tracingContext.js.map | 1 + node_modules/@azure/core-tracing/package.json | 101 + .../core-tracing/types/core-tracing.d.ts | 284 + node_modules/@azure/core-util/LICENSE | 21 + node_modules/@azure/core-util/README.md | 40 + .../core-util/dist-esm/src/base64.browser.js | 35 + .../dist-esm/src/base64.browser.js.map | 1 + .../dist-esm/src/createAbortablePromise.js | 42 + .../src/createAbortablePromise.js.map | 1 + .../@azure/core-util/dist-esm/src/delay.js | 22 + .../core-util/dist-esm/src/delay.js.map | 1 + .../@azure/core-util/dist-esm/src/error.js | 42 + .../core-util/dist-esm/src/error.js.map | 1 + .../@azure/core-util/dist-esm/src/hex.js | 21 + .../@azure/core-util/dist-esm/src/hex.js.map | 1 + .../@azure/core-util/dist-esm/src/index.js | 11 + .../core-util/dist-esm/src/index.js.map | 1 + .../core-util/dist-esm/src/isNode.browser.js | 7 + .../dist-esm/src/isNode.browser.js.map | 1 + .../@azure/core-util/dist-esm/src/isNode.js | 8 + .../core-util/dist-esm/src/isNode.js.map | 1 + .../@azure/core-util/dist-esm/src/object.js | 14 + .../core-util/dist-esm/src/object.js.map | 1 + .../@azure/core-util/dist-esm/src/random.js | 21 + .../core-util/dist-esm/src/random.js.map | 1 + .../core-util/dist-esm/src/sha256.browser.js | 61 + .../dist-esm/src/sha256.browser.js.map | 1 + .../@azure/core-util/dist-esm/src/sha256.js | 22 + .../core-util/dist-esm/src/sha256.js.map | 1 + .../core-util/dist-esm/src/typeGuards.js | 34 + .../core-util/dist-esm/src/typeGuards.js.map | 1 + .../core-util/dist-esm/src/utf8.browser.js | 26 + .../dist-esm/src/utf8.browser.js.map | 1 + node_modules/@azure/core-util/package.json | 109 + .../@azure/core-util/types/3.1/core-util.d.ts | 106 + .../core-util/types/latest/core-util.d.ts | 122 + node_modules/@azure/logger/LICENSE | 21 + node_modules/@azure/logger/README.md | 132 + .../@azure/logger/dist-esm/src/debug.js | 93 + .../@azure/logger/dist-esm/src/debug.js.map | 1 + .../@azure/logger/dist-esm/src/index.js | 98 + .../@azure/logger/dist-esm/src/index.js.map | 1 + .../@azure/logger/dist-esm/src/log.browser.js | 23 + .../logger/dist-esm/src/log.browser.js.map | 1 + .../@azure/logger/dist-esm/src/log.js | 8 + .../@azure/logger/dist-esm/src/log.js.map | 1 + node_modules/@azure/logger/package.json | 105 + node_modules/@azure/logger/types/logger.d.ts | 104 + node_modules/@babel/runtime/LICENSE | 22 + node_modules/@babel/runtime/README.md | 19 + .../@babel/runtime/helpers/AsyncGenerator.js | 64 + .../@babel/runtime/helpers/AwaitValue.js | 4 + .../@babel/runtime/helpers/OverloadYield.js | 4 + .../helpers/applyDecoratedDescriptor.js | 24 + .../@babel/runtime/helpers/applyDecs.js | 236 + .../@babel/runtime/helpers/applyDecs2203.js | 187 + .../@babel/runtime/helpers/applyDecs2203R.js | 191 + .../@babel/runtime/helpers/applyDecs2301.js | 221 + .../runtime/helpers/arrayLikeToArray.js | 6 + .../@babel/runtime/helpers/arrayWithHoles.js | 4 + .../runtime/helpers/arrayWithoutHoles.js | 5 + .../runtime/helpers/assertThisInitialized.js | 7 + .../runtime/helpers/asyncGeneratorDelegate.js | 24 + .../@babel/runtime/helpers/asyncIterator.js | 45 + .../runtime/helpers/asyncToGenerator.js | 31 + .../runtime/helpers/awaitAsyncGenerator.js | 5 + .../@babel/runtime/helpers/checkInRHS.js | 6 + .../helpers/checkPrivateRedeclaration.js | 6 + .../classApplyDescriptorDestructureSet.js | 18 + .../helpers/classApplyDescriptorGet.js | 7 + .../helpers/classApplyDescriptorSet.js | 11 + .../@babel/runtime/helpers/classCallCheck.js | 6 + .../helpers/classCheckPrivateStaticAccess.js | 6 + .../classCheckPrivateStaticFieldDescriptor.js | 6 + .../helpers/classExtractFieldDescriptor.js | 7 + .../runtime/helpers/classNameTDZError.js | 4 + .../classPrivateFieldDestructureSet.js | 7 + .../runtime/helpers/classPrivateFieldGet.js | 7 + .../helpers/classPrivateFieldInitSpec.js | 6 + .../helpers/classPrivateFieldLooseBase.js | 7 + .../helpers/classPrivateFieldLooseKey.js | 5 + .../runtime/helpers/classPrivateFieldSet.js | 8 + .../runtime/helpers/classPrivateMethodGet.js | 7 + .../helpers/classPrivateMethodInitSpec.js | 6 + .../runtime/helpers/classPrivateMethodSet.js | 4 + .../classStaticPrivateFieldDestructureSet.js | 9 + .../helpers/classStaticPrivateFieldSpecGet.js | 9 + .../helpers/classStaticPrivateFieldSpecSet.js | 10 + .../helpers/classStaticPrivateMethodGet.js | 6 + .../helpers/classStaticPrivateMethodSet.js | 4 + .../@babel/runtime/helpers/construct.js | 18 + .../@babel/runtime/helpers/createClass.js | 19 + .../helpers/createForOfIteratorHelper.js | 53 + .../helpers/createForOfIteratorHelperLoose.js | 20 + .../@babel/runtime/helpers/createSuper.js | 18 + .../@babel/runtime/helpers/decorate.js | 343 + .../@babel/runtime/helpers/defaults.js | 12 + .../@babel/runtime/helpers/defineAccessor.js | 8 + .../helpers/defineEnumerableProperties.js | 20 + .../@babel/runtime/helpers/defineProperty.js | 16 + .../runtime/helpers/esm/AsyncGenerator.js | 63 + .../@babel/runtime/helpers/esm/AwaitValue.js | 3 + .../runtime/helpers/esm/OverloadYield.js | 3 + .../helpers/esm/applyDecoratedDescriptor.js | 23 + .../@babel/runtime/helpers/esm/applyDecs.js | 235 + .../runtime/helpers/esm/applyDecs2203.js | 186 + .../runtime/helpers/esm/applyDecs2203R.js | 190 + .../runtime/helpers/esm/applyDecs2301.js | 220 + .../runtime/helpers/esm/arrayLikeToArray.js | 5 + .../runtime/helpers/esm/arrayWithHoles.js | 3 + .../runtime/helpers/esm/arrayWithoutHoles.js | 4 + .../helpers/esm/assertThisInitialized.js | 6 + .../helpers/esm/asyncGeneratorDelegate.js | 23 + .../runtime/helpers/esm/asyncIterator.js | 44 + .../runtime/helpers/esm/asyncToGenerator.js | 30 + .../helpers/esm/awaitAsyncGenerator.js | 4 + .../@babel/runtime/helpers/esm/checkInRHS.js | 5 + .../helpers/esm/checkPrivateRedeclaration.js | 5 + .../esm/classApplyDescriptorDestructureSet.js | 17 + .../helpers/esm/classApplyDescriptorGet.js | 6 + .../helpers/esm/classApplyDescriptorSet.js | 10 + .../runtime/helpers/esm/classCallCheck.js | 5 + .../esm/classCheckPrivateStaticAccess.js | 5 + .../classCheckPrivateStaticFieldDescriptor.js | 5 + .../esm/classExtractFieldDescriptor.js | 6 + .../runtime/helpers/esm/classNameTDZError.js | 3 + .../esm/classPrivateFieldDestructureSet.js | 6 + .../helpers/esm/classPrivateFieldGet.js | 6 + .../helpers/esm/classPrivateFieldInitSpec.js | 5 + .../helpers/esm/classPrivateFieldLooseBase.js | 6 + .../helpers/esm/classPrivateFieldLooseKey.js | 4 + .../helpers/esm/classPrivateFieldSet.js | 7 + .../helpers/esm/classPrivateMethodGet.js | 6 + .../helpers/esm/classPrivateMethodInitSpec.js | 5 + .../helpers/esm/classPrivateMethodSet.js | 3 + .../classStaticPrivateFieldDestructureSet.js | 8 + .../esm/classStaticPrivateFieldSpecGet.js | 8 + .../esm/classStaticPrivateFieldSpecSet.js | 9 + .../esm/classStaticPrivateMethodGet.js | 5 + .../esm/classStaticPrivateMethodSet.js | 3 + .../@babel/runtime/helpers/esm/construct.js | 17 + .../@babel/runtime/helpers/esm/createClass.js | 18 + .../helpers/esm/createForOfIteratorHelper.js | 52 + .../esm/createForOfIteratorHelperLoose.js | 19 + .../@babel/runtime/helpers/esm/createSuper.js | 17 + .../@babel/runtime/helpers/esm/decorate.js | 342 + .../@babel/runtime/helpers/esm/defaults.js | 11 + .../runtime/helpers/esm/defineAccessor.js | 7 + .../helpers/esm/defineEnumerableProperties.js | 19 + .../runtime/helpers/esm/defineProperty.js | 15 + .../@babel/runtime/helpers/esm/extends.js | 14 + .../@babel/runtime/helpers/esm/get.js | 17 + .../runtime/helpers/esm/getPrototypeOf.js | 6 + .../@babel/runtime/helpers/esm/identity.js | 3 + .../@babel/runtime/helpers/esm/inherits.js | 17 + .../runtime/helpers/esm/inheritsLoose.js | 6 + .../helpers/esm/initializerDefineProperty.js | 9 + .../helpers/esm/initializerWarningHelper.js | 3 + .../@babel/runtime/helpers/esm/instanceof.js | 7 + .../helpers/esm/interopRequireDefault.js | 5 + .../helpers/esm/interopRequireWildcard.js | 40 + .../runtime/helpers/esm/isNativeFunction.js | 3 + .../helpers/esm/isNativeReflectConstruct.js | 11 + .../runtime/helpers/esm/iterableToArray.js | 3 + .../helpers/esm/iterableToArrayLimit.js | 27 + .../helpers/esm/iterableToArrayLimitLoose.js | 9 + .../@babel/runtime/helpers/esm/jsx.js | 21 + .../runtime/helpers/esm/maybeArrayLike.js | 8 + .../runtime/helpers/esm/newArrowCheck.js | 5 + .../runtime/helpers/esm/nonIterableRest.js | 3 + .../runtime/helpers/esm/nonIterableSpread.js | 3 + .../helpers/esm/objectDestructuringEmpty.js | 3 + .../runtime/helpers/esm/objectSpread.js | 16 + .../runtime/helpers/esm/objectSpread2.js | 22 + .../helpers/esm/objectWithoutProperties.js | 16 + .../esm/objectWithoutPropertiesLoose.js | 12 + .../@babel/runtime/helpers/esm/package.json | 3 + .../helpers/esm/possibleConstructorReturn.js | 10 + .../runtime/helpers/esm/readOnlyError.js | 3 + .../runtime/helpers/esm/regeneratorRuntime.js | 303 + .../@babel/runtime/helpers/esm/set.js | 40 + .../runtime/helpers/esm/setPrototypeOf.js | 7 + .../helpers/esm/skipFirstGeneratorNext.js | 7 + .../runtime/helpers/esm/slicedToArray.js | 7 + .../runtime/helpers/esm/slicedToArrayLoose.js | 7 + .../runtime/helpers/esm/superPropBase.js | 8 + .../helpers/esm/taggedTemplateLiteral.js | 10 + .../helpers/esm/taggedTemplateLiteralLoose.js | 7 + .../@babel/runtime/helpers/esm/tdz.js | 3 + .../@babel/runtime/helpers/esm/temporalRef.js | 5 + .../runtime/helpers/esm/temporalUndefined.js | 1 + .../@babel/runtime/helpers/esm/toArray.js | 7 + .../runtime/helpers/esm/toConsumableArray.js | 7 + .../@babel/runtime/helpers/esm/toPrimitive.js | 11 + .../runtime/helpers/esm/toPropertyKey.js | 6 + .../@babel/runtime/helpers/esm/typeof.js | 9 + .../helpers/esm/unsupportedIterableToArray.js | 9 + .../runtime/helpers/esm/wrapAsyncGenerator.js | 6 + .../runtime/helpers/esm/wrapNativeSuper.js | 30 + .../@babel/runtime/helpers/esm/wrapRegExp.js | 50 + .../runtime/helpers/esm/writeOnlyError.js | 3 + .../@babel/runtime/helpers/extends.js | 15 + node_modules/@babel/runtime/helpers/get.js | 18 + .../@babel/runtime/helpers/getPrototypeOf.js | 7 + .../@babel/runtime/helpers/identity.js | 4 + .../@babel/runtime/helpers/inherits.js | 18 + .../@babel/runtime/helpers/inheritsLoose.js | 7 + .../helpers/initializerDefineProperty.js | 10 + .../helpers/initializerWarningHelper.js | 4 + .../@babel/runtime/helpers/instanceof.js | 8 + .../runtime/helpers/interopRequireDefault.js | 6 + .../runtime/helpers/interopRequireWildcard.js | 41 + .../runtime/helpers/isNativeFunction.js | 4 + .../helpers/isNativeReflectConstruct.js | 12 + .../@babel/runtime/helpers/iterableToArray.js | 4 + .../runtime/helpers/iterableToArrayLimit.js | 28 + .../helpers/iterableToArrayLimitLoose.js | 10 + node_modules/@babel/runtime/helpers/jsx.js | 22 + .../@babel/runtime/helpers/maybeArrayLike.js | 9 + .../@babel/runtime/helpers/newArrowCheck.js | 6 + .../@babel/runtime/helpers/nonIterableRest.js | 4 + .../runtime/helpers/nonIterableSpread.js | 4 + .../helpers/objectDestructuringEmpty.js | 4 + .../@babel/runtime/helpers/objectSpread.js | 17 + .../@babel/runtime/helpers/objectSpread2.js | 23 + .../helpers/objectWithoutProperties.js | 17 + .../helpers/objectWithoutPropertiesLoose.js | 13 + .../helpers/possibleConstructorReturn.js | 11 + .../@babel/runtime/helpers/readOnlyError.js | 4 + .../runtime/helpers/regeneratorRuntime.js | 304 + node_modules/@babel/runtime/helpers/set.js | 41 + .../@babel/runtime/helpers/setPrototypeOf.js | 8 + .../runtime/helpers/skipFirstGeneratorNext.js | 8 + .../@babel/runtime/helpers/slicedToArray.js | 8 + .../runtime/helpers/slicedToArrayLoose.js | 8 + .../@babel/runtime/helpers/superPropBase.js | 9 + .../runtime/helpers/taggedTemplateLiteral.js | 11 + .../helpers/taggedTemplateLiteralLoose.js | 8 + node_modules/@babel/runtime/helpers/tdz.js | 4 + .../@babel/runtime/helpers/temporalRef.js | 6 + .../runtime/helpers/temporalUndefined.js | 2 + .../@babel/runtime/helpers/toArray.js | 8 + .../runtime/helpers/toConsumableArray.js | 8 + .../@babel/runtime/helpers/toPrimitive.js | 12 + .../@babel/runtime/helpers/toPropertyKey.js | 7 + node_modules/@babel/runtime/helpers/typeof.js | 10 + .../helpers/unsupportedIterableToArray.js | 10 + .../runtime/helpers/wrapAsyncGenerator.js | 7 + .../@babel/runtime/helpers/wrapNativeSuper.js | 31 + .../@babel/runtime/helpers/wrapRegExp.js | 51 + .../@babel/runtime/helpers/writeOnlyError.js | 4 + node_modules/@babel/runtime/package.json | 930 + .../@babel/runtime/regenerator/index.js | 15 + node_modules/@colors/colors/LICENSE | 26 + node_modules/@colors/colors/README.md | 219 + .../@colors/colors/examples/normal-usage.js | 83 + .../@colors/colors/examples/safe-string.js | 80 + node_modules/@colors/colors/index.d.ts | 136 + node_modules/@colors/colors/package.json | 45 + node_modules/@colors/colors/safe.d.ts | 48 + node_modules/@colors/colors/safe.js | 10 + .../@colors/colors/themes/generic-logging.js | 12 + .../@githubnext/github-copilot-cli/README.md | 162 + .../@githubnext/github-copilot-cli/cli.js | 2 + .../github-copilot-cli/package.json | 57 + .../applicationinsights-web-snippet/LICENSE | 21 + .../applicationinsights-web-snippet/README.md | 54 + .../dest/applicationinsights-web-snippet.ts | 1 + .../package.json | 41 + .../src/applicationinsights-web-snippet.ts | 1 + .../tsconfig.json | 26 + .../applicationinsights-web-snippet.d.ts | 1 + node_modules/@opentelemetry/api/LICENSE | 201 + node_modules/@opentelemetry/api/README.md | 117 + node_modules/@opentelemetry/api/package.json | 91 + node_modules/@opentelemetry/core/LICENSE | 201 + node_modules/@opentelemetry/core/README.md | 73 + node_modules/@opentelemetry/core/package.json | 99 + node_modules/@opentelemetry/resources/LICENSE | 201 + .../@opentelemetry/resources/README.md | 49 + .../@opentelemetry/resources/package.json | 99 + .../@opentelemetry/sdk-trace-base/LICENSE | 201 + .../@opentelemetry/sdk-trace-base/README.md | 178 + .../sdk-trace-base/package.json | 102 + .../semantic-conventions/LICENSE | 201 + .../semantic-conventions/README.md | 41 + .../semantic-conventions/package.json | 67 + node_modules/@tootallnate/once/LICENSE | 21 + node_modules/@tootallnate/once/README.md | 93 + node_modules/@tootallnate/once/package.json | 52 + node_modules/@types/yoga-layout/LICENSE | 21 + node_modules/@types/yoga-layout/README.md | 16 + node_modules/@types/yoga-layout/index.d.ts | 413 + node_modules/@types/yoga-layout/package.json | 24 + node_modules/agent-base/README.md | 145 + node_modules/agent-base/package.json | 64 + node_modules/agent-base/src/index.ts | 345 + node_modules/agent-base/src/promisify.ts | 33 + node_modules/ansi-escapes/index.d.ts | 248 + node_modules/ansi-escapes/index.js | 157 + node_modules/ansi-escapes/license | 9 + .../node_modules/type-fest/base.d.ts | 39 + .../node_modules/type-fest/index.d.ts | 2 + .../node_modules/type-fest/license | 9 + .../node_modules/type-fest/package.json | 58 + .../node_modules/type-fest/readme.md | 760 + .../type-fest/source/async-return-type.d.ts | 23 + .../type-fest/source/asyncify.d.ts | 31 + .../node_modules/type-fest/source/basic.d.ts | 51 + .../type-fest/source/conditional-except.d.ts | 43 + .../type-fest/source/conditional-keys.d.ts | 43 + .../type-fest/source/conditional-pick.d.ts | 42 + .../type-fest/source/entries.d.ts | 57 + .../node_modules/type-fest/source/entry.d.ts | 60 + .../node_modules/type-fest/source/except.d.ts | 22 + .../type-fest/source/fixed-length-array.d.ts | 38 + .../type-fest/source/iterable-element.d.ts | 46 + .../type-fest/source/literal-union.d.ts | 33 + .../type-fest/source/merge-exclusive.d.ts | 39 + .../node_modules/type-fest/source/merge.d.ts | 25 + .../type-fest/source/mutable.d.ts | 38 + .../node_modules/type-fest/source/opaque.d.ts | 65 + .../type-fest/source/package-json.d.ts | 611 + .../type-fest/source/partial-deep.d.ts | 72 + .../type-fest/source/promisable.d.ts | 23 + .../type-fest/source/promise-value.d.ts | 27 + .../type-fest/source/readonly-deep.d.ts | 59 + .../source/require-at-least-one.d.ts | 33 + .../type-fest/source/require-exactly-one.d.ts | 35 + .../type-fest/source/set-optional.d.ts | 33 + .../type-fest/source/set-required.d.ts | 33 + .../type-fest/source/set-return-type.d.ts | 29 + .../type-fest/source/simplify.d.ts | 4 + .../type-fest/source/stringified.d.ts | 21 + .../type-fest/source/tsconfig-json.d.ts | 870 + .../type-fest/source/typed-array.d.ts | 15 + .../source/union-to-intersection.d.ts | 58 + .../type-fest/source/utilities.d.ts | 5 + .../type-fest/source/value-of.d.ts | 40 + .../type-fest/ts41/camel-case.d.ts | 64 + .../type-fest/ts41/delimiter-case.d.ts | 85 + .../node_modules/type-fest/ts41/get.d.ts | 131 + .../node_modules/type-fest/ts41/index.d.ts | 10 + .../type-fest/ts41/kebab-case.d.ts | 36 + .../type-fest/ts41/pascal-case.d.ts | 36 + .../type-fest/ts41/snake-case.d.ts | 35 + .../type-fest/ts41/utilities.d.ts | 8 + node_modules/ansi-escapes/package.json | 57 + node_modules/ansi-escapes/readme.md | 245 + node_modules/ansi-regex/index.d.ts | 33 + node_modules/ansi-regex/index.js | 8 + node_modules/ansi-regex/license | 9 + node_modules/ansi-regex/package.json | 58 + node_modules/ansi-regex/readme.md | 72 + node_modules/ansi-styles/index.d.ts | 345 + node_modules/ansi-styles/index.js | 163 + node_modules/ansi-styles/license | 9 + node_modules/ansi-styles/package.json | 56 + node_modules/ansi-styles/readme.md | 152 + node_modules/ansicolors/LICENSE | 23 + node_modules/ansicolors/README.md | 62 + node_modules/ansicolors/ansicolors.js | 65 + node_modules/ansicolors/package.json | 23 + node_modules/ansicolors/test/ansicolors.js | 71 + node_modules/any-promise/.jshintrc | 4 + node_modules/any-promise/.npmignore | 7 + node_modules/any-promise/LICENSE | 19 + node_modules/any-promise/README.md | 161 + node_modules/any-promise/implementation.d.ts | 3 + node_modules/any-promise/implementation.js | 1 + node_modules/any-promise/index.d.ts | 73 + node_modules/any-promise/index.js | 1 + node_modules/any-promise/loader.js | 78 + node_modules/any-promise/optional.js | 6 + node_modules/any-promise/package.json | 45 + node_modules/any-promise/register-shim.js | 18 + node_modules/any-promise/register.d.ts | 17 + node_modules/any-promise/register.js | 94 + .../any-promise/register/bluebird.d.ts | 1 + node_modules/any-promise/register/bluebird.js | 2 + .../any-promise/register/es6-promise.d.ts | 1 + .../any-promise/register/es6-promise.js | 2 + node_modules/any-promise/register/lie.d.ts | 1 + node_modules/any-promise/register/lie.js | 2 + .../register/native-promise-only.d.ts | 1 + .../register/native-promise-only.js | 2 + node_modules/any-promise/register/pinkie.d.ts | 1 + node_modules/any-promise/register/pinkie.js | 2 + .../any-promise/register/promise.d.ts | 1 + node_modules/any-promise/register/promise.js | 2 + node_modules/any-promise/register/q.d.ts | 1 + node_modules/any-promise/register/q.js | 2 + node_modules/any-promise/register/rsvp.d.ts | 1 + node_modules/any-promise/register/rsvp.js | 2 + node_modules/any-promise/register/vow.d.ts | 1 + node_modules/any-promise/register/vow.js | 2 + node_modules/any-promise/register/when.d.ts | 1 + node_modules/any-promise/register/when.js | 2 + .../applicationinsights/.eslintignore | 4 + node_modules/applicationinsights/.eslintrc | 41 + .../applicationinsights/CODE_OF_CONDUCT.md | 9 + .../applicationinsights/CONTRIBUTING.md | 40 + node_modules/applicationinsights/LICENSE | 21 + node_modules/applicationinsights/NOTICE | 17 + node_modules/applicationinsights/PRIVACY | 3 + node_modules/applicationinsights/README.md | 603 + node_modules/applicationinsights/SECURITY.md | 41 + node_modules/applicationinsights/SUPPORT.md | 14 + .../applicationinsights.json | 4 + .../AsyncHooksScopeManager.d.ts | 11 + .../AutoCollection/AsyncHooksScopeManager.js | 77 + .../AsyncHooksScopeManager.js.map | 1 + .../AutoCollection/AzureFunctionsHook.d.ts | 21 + .../out/AutoCollection/AzureFunctionsHook.js | 198 + .../AutoCollection/AzureFunctionsHook.js.map | 1 + .../out/AutoCollection/Console.d.ts | 15 + .../out/AutoCollection/Console.js | 29 + .../out/AutoCollection/Console.js.map | 1 + .../CorrelationContextManager.d.ts | 105 + .../CorrelationContextManager.js | 296 + .../CorrelationContextManager.js.map | 1 + .../out/AutoCollection/Exceptions.d.ts | 19 + .../out/AutoCollection/Exceptions.js | 81 + .../out/AutoCollection/Exceptions.js.map | 1 + .../out/AutoCollection/HeartBeat.d.ts | 18 + .../out/AutoCollection/HeartBeat.js | 83 + .../out/AutoCollection/HeartBeat.js.map | 1 + .../out/AutoCollection/HttpDependencies.d.ts | 22 + .../out/AutoCollection/HttpDependencies.js | 267 + .../AutoCollection/HttpDependencies.js.map | 1 + .../AutoCollection/HttpDependencyParser.d.ts | 30 + .../AutoCollection/HttpDependencyParser.js | 211 + .../HttpDependencyParser.js.map | 1 + .../out/AutoCollection/HttpRequestParser.d.ts | 59 + .../out/AutoCollection/HttpRequestParser.js | 292 + .../AutoCollection/HttpRequestParser.js.map | 1 + .../out/AutoCollection/HttpRequests.d.ts | 35 + .../out/AutoCollection/HttpRequests.js | 262 + .../out/AutoCollection/HttpRequests.js.map | 1 + .../out/AutoCollection/NativePerformance.d.ts | 83 + .../out/AutoCollection/NativePerformance.js | 247 + .../AutoCollection/NativePerformance.js.map | 1 + .../out/AutoCollection/NetworkStatsbeat.d.ts | 28 + .../out/AutoCollection/NetworkStatsbeat.js | 22 + .../AutoCollection/NetworkStatsbeat.js.map | 1 + .../out/AutoCollection/Performance.d.ts | 43 + .../out/AutoCollection/Performance.js | 279 + .../out/AutoCollection/Performance.js.map | 1 + .../AutoCollection/PreAggregatedMetrics.d.ts | 35 + .../AutoCollection/PreAggregatedMetrics.js | 259 + .../PreAggregatedMetrics.js.map | 1 + .../out/AutoCollection/RequestParser.d.ts | 22 + .../out/AutoCollection/RequestParser.js | 44 + .../out/AutoCollection/RequestParser.js.map | 1 + .../out/AutoCollection/Statsbeat.d.ts | 56 + .../out/AutoCollection/Statsbeat.js | 501 + .../out/AutoCollection/Statsbeat.js.map | 1 + .../out/AutoCollection/WebSnippet.d.ts | 35 + .../out/AutoCollection/WebSnippet.js | 362 + .../out/AutoCollection/WebSnippet.js.map | 1 + .../diagnostic-channel/Azure/EventHub.d.ts | 8 + .../diagnostic-channel/Azure/EventHub.js | 67 + .../diagnostic-channel/Azure/EventHub.js.map | 1 + .../diagnostic-channel/SpanParser.d.ts | 3 + .../diagnostic-channel/SpanParser.js | 287 + .../diagnostic-channel/SpanParser.js.map | 1 + .../azure-coretracing.sub.d.ts | 5 + .../azure-coretracing.sub.js | 54 + .../azure-coretracing.sub.js.map | 1 + .../diagnostic-channel/bunyan.sub.d.ts | 3 + .../diagnostic-channel/bunyan.sub.js | 67 + .../diagnostic-channel/bunyan.sub.js.map | 1 + .../diagnostic-channel/console.sub.d.ts | 3 + .../diagnostic-channel/console.sub.js | 52 + .../diagnostic-channel/console.sub.js.map | 1 + .../diagnostic-channel/initialization.d.ts | 2 + .../diagnostic-channel/initialization.js | 47 + .../diagnostic-channel/initialization.js.map | 1 + .../diagnostic-channel/mongodb.sub.d.ts | 5 + .../diagnostic-channel/mongodb.sub.js | 52 + .../diagnostic-channel/mongodb.sub.js.map | 1 + .../diagnostic-channel/mysql.sub.d.ts | 5 + .../diagnostic-channel/mysql.sub.js | 53 + .../diagnostic-channel/mysql.sub.js.map | 1 + .../diagnostic-channel/postgres.sub.d.ts | 5 + .../diagnostic-channel/postgres.sub.js | 50 + .../diagnostic-channel/postgres.sub.js.map | 1 + .../diagnostic-channel/redis.sub.d.ts | 5 + .../diagnostic-channel/redis.sub.js | 51 + .../diagnostic-channel/redis.sub.js.map | 1 + .../diagnostic-channel/winston.sub.d.ts | 3 + .../diagnostic-channel/winston.sub.js | 85 + .../diagnostic-channel/winston.sub.js.map | 1 + .../out/Bootstrap/DataModel.d.ts | 47 + .../out/Bootstrap/DataModel.js | 13 + .../out/Bootstrap/DataModel.js.map | 1 + .../out/Bootstrap/Default.d.ts | 22 + .../out/Bootstrap/Default.js | 179 + .../out/Bootstrap/Default.js.map | 1 + .../out/Bootstrap/DiagnosticLogger.d.ts | 10 + .../out/Bootstrap/DiagnosticLogger.js | 56 + .../out/Bootstrap/DiagnosticLogger.js.map | 1 + .../out/Bootstrap/FileWriter.d.ts | 27 + .../out/Bootstrap/FileWriter.js | 140 + .../out/Bootstrap/FileWriter.js.map | 1 + .../out/Bootstrap/Helpers.d.ts | 2 + .../out/Bootstrap/Helpers.js | 39 + .../out/Bootstrap/Helpers.js.map | 1 + .../out/Bootstrap/Helpers/FileHelpers.d.ts | 3 + .../out/Bootstrap/Helpers/FileHelpers.js | 71 + .../out/Bootstrap/Helpers/FileHelpers.js.map | 1 + .../out/Bootstrap/NoopLogger.d.ts | 5 + .../out/Bootstrap/NoopLogger.js | 22 + .../out/Bootstrap/NoopLogger.js.map | 1 + .../out/Bootstrap/Oryx.d.ts | 3 + .../applicationinsights/out/Bootstrap/Oryx.js | 14 + .../out/Bootstrap/Oryx.js.map | 1 + .../out/Bootstrap/StatusLogger.d.ts | 19 + .../out/Bootstrap/StatusLogger.js | 35 + .../out/Bootstrap/StatusLogger.js.map | 1 + .../out/Declarations/Constants.d.ts | 119 + .../out/Declarations/Constants.js | 174 + .../out/Declarations/Constants.js.map | 1 + .../out/Declarations/Contracts/Constants.d.ts | 38 + .../out/Declarations/Contracts/Constants.js | 24 + .../Declarations/Contracts/Constants.js.map | 1 + .../Contracts/Generated/AvailabilityData.d.ts | 44 + .../Contracts/Generated/AvailabilityData.js | 33 + .../Generated/AvailabilityData.js.map | 1 + .../Contracts/Generated/Base.d.ts | 11 + .../Declarations/Contracts/Generated/Base.js | 12 + .../Contracts/Generated/Base.js.map | 1 + .../Contracts/Generated/ContextTagKeys.d.ts | 104 + .../Contracts/Generated/ContextTagKeys.js | 32 + .../Contracts/Generated/ContextTagKeys.js.map | 1 + .../Contracts/Generated/Data.d.ts | 16 + .../Declarations/Contracts/Generated/Data.js | 29 + .../Contracts/Generated/Data.js.map | 1 + .../Contracts/Generated/DataPoint.d.ts | 40 + .../Contracts/Generated/DataPoint.js | 15 + .../Contracts/Generated/DataPoint.js.map | 1 + .../Contracts/Generated/DataPointType.d.ts | 8 + .../Contracts/Generated/DataPointType.js | 12 + .../Contracts/Generated/DataPointType.js.map | 1 + .../Contracts/Generated/Domain.d.ts | 7 + .../Contracts/Generated/Domain.js | 12 + .../Contracts/Generated/Domain.js.map | 1 + .../Contracts/Generated/Envelope.d.ts | 40 + .../Contracts/Generated/Envelope.js | 14 + .../Contracts/Generated/Envelope.js.map | 1 + .../Contracts/Generated/EventData.d.ts | 24 + .../Contracts/Generated/EventData.js | 33 + .../Contracts/Generated/EventData.js.map | 1 + .../Contracts/Generated/ExceptionData.d.ts | 34 + .../Contracts/Generated/ExceptionData.js | 34 + .../Contracts/Generated/ExceptionData.js.map | 1 + .../Contracts/Generated/ExceptionDetails.d.ts | 36 + .../Contracts/Generated/ExceptionDetails.js | 13 + .../Generated/ExceptionDetails.js.map | 1 + .../Contracts/Generated/MessageData.d.ts | 25 + .../Contracts/Generated/MessageData.js | 32 + .../Contracts/Generated/MessageData.js.map | 1 + .../Contracts/Generated/MetricData.d.ts | 21 + .../Contracts/Generated/MetricData.js | 33 + .../Contracts/Generated/MetricData.js.map | 1 + .../Contracts/Generated/PageViewData.d.ts | 32 + .../Contracts/Generated/PageViewData.js | 33 + .../Contracts/Generated/PageViewData.js.map | 1 + .../Generated/RemoteDependencyData.d.ts | 52 + .../Generated/RemoteDependencyData.js | 34 + .../Generated/RemoteDependencyData.js.map | 1 + .../Contracts/Generated/RequestData.d.ts | 48 + .../Contracts/Generated/RequestData.js | 33 + .../Contracts/Generated/RequestData.js.map | 1 + .../Contracts/Generated/SeverityLevel.d.ts | 11 + .../Contracts/Generated/SeverityLevel.js | 15 + .../Contracts/Generated/SeverityLevel.js.map | 1 + .../Contracts/Generated/StackFrame.d.ts | 27 + .../Contracts/Generated/StackFrame.js | 12 + .../Contracts/Generated/StackFrame.js.map | 1 + .../Contracts/Generated/index.d.ts | 18 + .../Declarations/Contracts/Generated/index.js | 22 + .../Contracts/Generated/index.js.map | 1 + .../DependencyDocumentQuickPulse.d.ts | 11 + .../DependencyDocumentQuickPulse.js | 3 + .../DependencyDocumentQuickPulse.js.map | 1 + .../QuickPulseTypes/DocumentQuickPulse.d.ts | 11 + .../QuickPulseTypes/DocumentQuickPulse.js | 3 + .../QuickPulseTypes/DocumentQuickPulse.js.map | 1 + .../QuickPulseTypes/EnvelopeQuickPulse.d.ts | 14 + .../QuickPulseTypes/EnvelopeQuickPulse.js | 3 + .../QuickPulseTypes/EnvelopeQuickPulse.js.map | 1 + .../EventDocumentQuickPulse.d.ts | 4 + .../EventDocumentQuickPulse.js | 3 + .../EventDocumentQuickPulse.js.map | 1 + .../ExceptionDocumentQuickPulse.d.ts | 6 + .../ExceptionDocumentQuickPulse.js | 3 + .../ExceptionDocumentQuickPulse.js.map | 1 + .../MessageDocumentQuickPulse.d.ts | 5 + .../MessageDocumentQuickPulse.js | 3 + .../MessageDocumentQuickPulse.js.map | 1 + .../QuickPulseTypes/MetricQuickPulse.d.ts | 5 + .../QuickPulseTypes/MetricQuickPulse.js | 3 + .../QuickPulseTypes/MetricQuickPulse.js.map | 1 + .../RequestDocumentQuickPulse.d.ts | 8 + .../RequestDocumentQuickPulse.js | 3 + .../RequestDocumentQuickPulse.js.map | 1 + .../Contracts/QuickPulseTypes/index.d.ts | 8 + .../Contracts/QuickPulseTypes/index.js | 21 + .../Contracts/QuickPulseTypes/index.js.map | 1 + .../TelemetryTypes/AvailabilityTelemetry.d.ts | 36 + .../TelemetryTypes/AvailabilityTelemetry.js | 3 + .../AvailabilityTelemetry.js.map | 1 + .../TelemetryTypes/DependencyTelemetry.d.ts | 36 + .../TelemetryTypes/DependencyTelemetry.js | 3 + .../TelemetryTypes/DependencyTelemetry.js.map | 1 + .../TelemetryTypes/EnvelopeTelemetry.d.ts | 58 + .../TelemetryTypes/EnvelopeTelemetry.js | 3 + .../TelemetryTypes/EnvelopeTelemetry.js.map | 1 + .../TelemetryTypes/EventTelemetry.d.ts | 17 + .../TelemetryTypes/EventTelemetry.js | 3 + .../TelemetryTypes/EventTelemetry.js.map | 1 + .../TelemetryTypes/ExceptionTelemetry.d.ts | 21 + .../TelemetryTypes/ExceptionTelemetry.js | 3 + .../TelemetryTypes/ExceptionTelemetry.js.map | 1 + .../TelemetryTypes/MetricTelemetry.d.ts | 39 + .../TelemetryTypes/MetricTelemetry.js | 3 + .../TelemetryTypes/MetricTelemetry.js.map | 1 + .../NodeHttpDependencyTelemetry.d.ts | 21 + .../NodeHttpDependencyTelemetry.js | 3 + .../NodeHttpDependencyTelemetry.js.map | 1 + .../NodeHttpRequestTelemetry.d.ts | 28 + .../NodeHttpRequestTelemetry.js | 3 + .../NodeHttpRequestTelemetry.js.map | 1 + .../TelemetryTypes/PageViewTelemetry.d.ts | 24 + .../TelemetryTypes/PageViewTelemetry.js | 3 + .../TelemetryTypes/PageViewTelemetry.js.map | 1 + .../TelemetryTypes/RequestTelemetry.d.ts | 36 + .../TelemetryTypes/RequestTelemetry.js | 3 + .../TelemetryTypes/RequestTelemetry.js.map | 1 + .../Contracts/TelemetryTypes/Telemetry.d.ts | 27 + .../Contracts/TelemetryTypes/Telemetry.js | 3 + .../Contracts/TelemetryTypes/Telemetry.js.map | 1 + .../TelemetryTypes/TelemetryType.d.ts | 31 + .../Contracts/TelemetryTypes/TelemetryType.js | 80 + .../TelemetryTypes/TelemetryType.js.map | 1 + .../TelemetryTypes/TraceTelemetry.d.ts | 16 + .../TelemetryTypes/TraceTelemetry.js | 3 + .../TelemetryTypes/TraceTelemetry.js.map | 1 + .../Contracts/TelemetryTypes/index.d.ts | 13 + .../Contracts/TelemetryTypes/index.js | 26 + .../Contracts/TelemetryTypes/index.js.map | 1 + .../out/Declarations/Contracts/index.d.ts | 4 + .../out/Declarations/Contracts/index.js | 17 + .../out/Declarations/Contracts/index.js.map | 1 + .../out/Declarations/Interfaces.d.ts | 220 + .../out/Declarations/Interfaces.js | 3 + .../out/Declarations/Interfaces.js.map | 1 + .../Metrics/AggregatedMetric.d.ts | 11 + .../Declarations/Metrics/AggregatedMetric.js | 10 + .../Metrics/AggregatedMetric.js.map | 1 + .../Metrics/AggregatedMetricCounters.d.ts | 11 + .../Metrics/AggregatedMetricCounters.js | 16 + .../Metrics/AggregatedMetricCounters.js.map | 1 + .../Metrics/AggregatedMetricDimensions.d.ts | 25 + .../Metrics/AggregatedMetricDimensions.js | 17 + .../Metrics/AggregatedMetricDimensions.js.map | 1 + .../out/Library/AuthorizationHandler.d.ts | 13 + .../out/Library/AuthorizationHandler.js | 71 + .../out/Library/AuthorizationHandler.js.map | 1 + .../out/Library/AzureVirtualMachine.d.ts | 13 + .../out/Library/AzureVirtualMachine.js | 84 + .../out/Library/AzureVirtualMachine.js.map | 1 + .../out/Library/Channel.d.ts | 30 + .../out/Library/Channel.js | 84 + .../out/Library/Channel.js.map | 1 + .../out/Library/Config.d.ts | 86 + .../applicationinsights/out/Library/Config.js | 168 + .../out/Library/Config.js.map | 1 + .../out/Library/ConnectionStringParser.d.ts | 8 + .../out/Library/ConnectionStringParser.js | 46 + .../out/Library/ConnectionStringParser.js.map | 1 + .../out/Library/Context.d.ts | 17 + .../out/Library/Context.js | 52 + .../out/Library/Context.js.map | 1 + .../out/Library/CorrelationIdManager.d.ts | 24 + .../out/Library/CorrelationIdManager.js | 79 + .../out/Library/CorrelationIdManager.js.map | 1 + .../out/Library/EnvelopeFactory.d.ts | 31 + .../out/Library/EnvelopeFactory.js | 361 + .../out/Library/EnvelopeFactory.js.map | 1 + .../out/Library/FileAccessControl.d.ts | 18 + .../out/Library/FileAccessControl.js | 216 + .../out/Library/FileAccessControl.js.map | 1 + .../out/Library/FileSystemHelper.d.ts | 27 + .../out/Library/FileSystemHelper.js | 152 + .../out/Library/FileSystemHelper.js.map | 1 + .../out/Library/FlushOptions.d.ts | 16 + .../out/Library/FlushOptions.js | 3 + .../out/Library/FlushOptions.js.map | 1 + .../out/Library/Functions.d.ts | 48 + .../out/Library/Functions.js | 3 + .../out/Library/Functions.js.map | 1 + .../out/Library/InternalAzureLogger.d.ts | 22 + .../out/Library/InternalAzureLogger.js | 263 + .../out/Library/InternalAzureLogger.js.map | 1 + .../out/Library/JsonConfig.d.ts | 53 + .../out/Library/JsonConfig.js | 168 + .../out/Library/JsonConfig.js.map | 1 + .../out/Library/Logging.d.ts | 8 + .../out/Library/Logging.js | 30 + .../out/Library/Logging.js.map | 1 + .../out/Library/NodeClient.d.ts | 30 + .../out/Library/NodeClient.js | 76 + .../out/Library/NodeClient.js.map | 1 + .../out/Library/PrefixHelper.d.ts | 19 + .../out/Library/PrefixHelper.js | 41 + .../out/Library/PrefixHelper.js.map | 1 + .../Library/QuickPulseEnvelopeFactory.d.ts | 17 + .../out/Library/QuickPulseEnvelopeFactory.js | 169 + .../Library/QuickPulseEnvelopeFactory.js.map | 1 + .../out/Library/QuickPulseSender.d.ts | 18 + .../out/Library/QuickPulseSender.js | 189 + .../out/Library/QuickPulseSender.js.map | 1 + .../out/Library/QuickPulseStateManager.d.ts | 65 + .../out/Library/QuickPulseStateManager.js | 226 + .../out/Library/QuickPulseStateManager.js.map | 1 + .../out/Library/QuickPulseUtil.d.ts | 4 + .../out/Library/QuickPulseUtil.js | 15 + .../out/Library/QuickPulseUtil.js.map | 1 + .../out/Library/RequestResponseHeaders.d.ts | 44 + .../out/Library/RequestResponseHeaders.js | 45 + .../out/Library/RequestResponseHeaders.js.map | 1 + .../out/Library/Sender.d.ts | 61 + .../applicationinsights/out/Library/Sender.js | 581 + .../out/Library/Sender.js.map | 1 + .../out/Library/SnippetInjectionHelper.d.ts | 24 + .../out/Library/SnippetInjectionHelper.js | 136 + .../out/Library/SnippetInjectionHelper.js.map | 1 + .../out/Library/TelemetryClient.d.ts | 111 + .../out/Library/TelemetryClient.js | 237 + .../out/Library/TelemetryClient.js.map | 1 + .../out/Library/Traceparent.d.ts | 23 + .../out/Library/Traceparent.js | 112 + .../out/Library/Traceparent.js.map | 1 + .../out/Library/Tracestate.d.ts | 14 + .../out/Library/Tracestate.js | 76 + .../out/Library/Tracestate.js.map | 1 + .../applicationinsights/out/Library/Util.d.ts | 112 + .../applicationinsights/out/Library/Util.js | 413 + .../out/Library/Util.js.map | 1 + ...reRoleEnvironmentTelemetryInitializer.d.ts | 6 + ...zureRoleEnvironmentTelemetryInitializer.js | 16 + ...RoleEnvironmentTelemetryInitializer.js.map | 1 + .../PerformanceMetricsTelemetryProcessor.d.ts | 3 + .../PerformanceMetricsTelemetryProcessor.js | 28 + ...erformanceMetricsTelemetryProcessor.js.map | 1 + ...reAggregatedMetricsTelemetryProcessor.d.ts | 3 + .../PreAggregatedMetricsTelemetryProcessor.js | 72 + ...AggregatedMetricsTelemetryProcessor.js.map | 1 + .../SamplingTelemetryProcessor.d.ts | 10 + .../SamplingTelemetryProcessor.js | 48 + .../SamplingTelemetryProcessor.js.map | 1 + .../out/TelemetryProcessors/index.d.ts | 4 + .../out/TelemetryProcessors/index.js | 17 + .../out/TelemetryProcessors/index.js.map | 1 + .../out/applicationinsights.d.ts | 185 + .../out/applicationinsights.js | 474 + .../out/applicationinsights.js.map | 1 + node_modules/applicationinsights/package.json | 89 + .../policheck-exclusions.xml | 11 + .../types/@azure_functions-core/index.d.ts | 515 + node_modules/arr-rotate/index.js | 11 + node_modules/arr-rotate/license | 9 + node_modules/arr-rotate/package.json | 32 + node_modules/arr-rotate/readme.md | 49 + node_modules/astral-regex/index.d.ts | 28 + node_modules/astral-regex/index.js | 6 + node_modules/astral-regex/license | 9 + node_modules/astral-regex/package.json | 33 + node_modules/astral-regex/readme.md | 46 + node_modules/async-hook-jl/.eslintrc | 21 + node_modules/async-hook-jl/.npmignore | 2 + node_modules/async-hook-jl/.travis.yml | 11 + node_modules/async-hook-jl/LICENSE.md | 19 + node_modules/async-hook-jl/README.md | 63 + node_modules/async-hook-jl/async-hook.js | 134 + node_modules/async-hook-jl/index.js | 31 + node_modules/async-hook-jl/package.json | 33 + .../async-hook-jl/patches/next-tick.js | 57 + node_modules/async-hook-jl/patches/promise.js | 64 + node_modules/async-hook-jl/patches/timers.js | 117 + node_modules/async-hook-jl/test/runner.js | 55 + .../async-hook-jl/test/test-conflict-match.js | 11 + .../test/test-conflict-mismatch.js | 13 + .../test/test-fsaccess-disabled.js | 33 + .../test/test-fsaccess-enabled.js | 75 + .../async-hook-jl/test/test-hooks-remove.js | 48 + .../async-hook-jl/test/test-hooks-twice.js | 47 + .../test/test-immediate-clear-in-callback.js | 38 + .../test/test-immediate-clear.js | 59 + .../test/test-immediate-didthrow.js | 46 + .../test/test-immediate-disabled.js | 42 + .../test/test-immediate-enabled.js | 76 + .../test/test-immediate-exception.js | 32 + .../test/test-immediate-non-function.js | 21 + .../test/test-interval-clear-in-callback.js | 38 + .../async-hook-jl/test/test-interval-clear.js | 59 + .../test/test-interval-didthrow.js | 46 + .../test/test-interval-disabled.js | 42 + .../test/test-interval-enabled.js | 86 + .../test/test-interval-exception.js | 32 + .../test/test-interval-non-function.js | 21 + .../test/test-nexttick-didthrow.js | 46 + .../test/test-nexttick-disabled.js | 34 + .../test/test-nexttick-enabled.js | 76 + .../test/test-nexttick-exception.js | 32 + .../test/test-nexttick-non-function.js | 21 + .../async-hook-jl/test/test-parent.js | 58 + .../test/test-promise-catch-enabled.js | 75 + ...mise-catch-then-chain-fulfilled-enabled.js | 80 + .../test/test-promise-disabled.js | 72 + ...omise-then-catch-chain-rejected-enabled.js | 81 + ...-promise-then-fulfilled-chained-enabled.js | 80 + .../test-promise-then-fulfilled-enabled.js | 79 + ...promise-then-fulfilled-multiple-enabled.js | 75 + .../test-promise-then-rejected-enabled.js | 75 + .../async-hook-jl/test/test-promise-timing.js | 75 + .../test/test-stackfilter-eval.js | 9 + .../test/test-timeout-clear-in-callback.js | 38 + .../async-hook-jl/test/test-timeout-clear.js | 59 + .../test/test-timeout-didthrow.js | 46 + .../test/test-timeout-disabled.js | 42 + .../test/test-timeout-enabled.js | 72 + .../test/test-timeout-exception.js | 32 + .../test/test-timeout-non-function.js | 21 + node_modules/async-hook-jl/yarn.lock | 900 + node_modules/async-listener/.travis.yml | 23 + node_modules/async-listener/LICENSE | 25 + node_modules/async-listener/README.md | 55 + .../async-listener/es6-wrapped-promise.js | 37 + node_modules/async-listener/glue.js | 488 + node_modules/async-listener/index.js | 674 + node_modules/async-listener/package.json | 39 + .../async-listener/test/add-remove.tap.js | 39 + .../connection-handler-disconnects.tap.js | 74 + ...clistener-error-multiple-handled.simple.js | 78 + ...asynclistener-error-multiple-mix.simple.js | 67 + ...istener-error-multiple-unhandled.simple.js | 80 + .../core-asynclistener-error-net.simple.js | 110 + ...ynclistener-error-throw-in-after.simple.js | 56 + ...r-error-throw-in-before-multiple.simple.js | 79 + ...nclistener-error-throw-in-before.simple.js | 56 + ...ynclistener-error-throw-in-error.simple.js | 72 + .../test/core-asynclistener-error.simple.js | 229 + ...re-asynclistener-nexttick-remove.simple.js | 137 + .../core-asynclistener-only-add.simple.js | 133 + ...core-asynclistener-remove-before.simple.js | 55 + ...nclistener-remove-inflight-error.simple.js | 50 + ...re-asynclistener-remove-inflight.simple.js | 53 + .../test/core-asynclistener.simple.js | 191 + .../core/core-asynclistener-add-inflight.js | 58 + ...listener-error-throw-in-before-inflight.js | 59 + .../test/errors-this-tick.tap.js | 70 + .../test/fork-listen2-problem.tap.js | 33 + .../async-listener/test/fork-listener.js | 31 + .../test/function-length-preserved.tap.js | 24 + .../async-listener/test/handle.tap.js | 34 + .../async-listener/test/http-request.tap.js | 307 + .../test/native-promises.tap.js | 2236 ++ .../test/no-after-following-error.tap.js | 31 + .../test/overlapping-nexttick.tap.js | 192 + .../async-listener/test/promise-subclass.js | 22 + .../test/simple-counter-with-io.tap.js | 28 + .../async-listener/test/simple-counter.tap.js | 29 + .../test/simplified-error.simple.js | 67 + node_modules/async-listener/test/spawn.tap.js | 100 + .../async-listener/test/timers.tap.js | 159 + node_modules/async-listener/test/zlib.tap.js | 214 + node_modules/asynckit/LICENSE | 21 + node_modules/asynckit/README.md | 233 + node_modules/asynckit/bench.js | 76 + node_modules/asynckit/index.js | 6 + node_modules/asynckit/package.json | 63 + node_modules/asynckit/parallel.js | 43 + node_modules/asynckit/serial.js | 17 + node_modules/asynckit/serialOrdered.js | 75 + node_modules/asynckit/stream.js | 21 + node_modules/auto-bind/index.d.ts | 54 + node_modules/auto-bind/index.js | 43 + node_modules/auto-bind/license | 9 + node_modules/auto-bind/package.json | 46 + node_modules/auto-bind/react.d.ts | 28 + node_modules/auto-bind/react.js | 29 + node_modules/auto-bind/readme.md | 92 + node_modules/axios/CHANGELOG.md | 492 + node_modules/axios/LICENSE | 7 + node_modules/axios/MIGRATION_GUIDE.md | 3 + node_modules/axios/README.md | 1313 + node_modules/axios/SECURITY.md | 6 + node_modules/axios/index.d.cts | 528 + node_modules/axios/index.d.ts | 543 + node_modules/axios/index.js | 41 + node_modules/axios/package.json | 206 + .../balanced-match/.github/FUNDING.yml | 2 + node_modules/balanced-match/LICENSE.md | 21 + node_modules/balanced-match/README.md | 97 + node_modules/balanced-match/index.js | 62 + node_modules/balanced-match/package.json | 48 + node_modules/base64-js/LICENSE | 21 + node_modules/base64-js/README.md | 34 + node_modules/base64-js/base64js.min.js | 1 + node_modules/base64-js/index.d.ts | 3 + node_modules/base64-js/index.js | 150 + node_modules/base64-js/package.json | 47 + node_modules/big-integer/BigInteger.d.ts | 2393 ++ node_modules/big-integer/BigInteger.js | 1453 + node_modules/big-integer/BigInteger.min.js | 1 + node_modules/big-integer/LICENSE | 24 + node_modules/big-integer/README.md | 589 + node_modules/big-integer/bower.json | 29 + node_modules/big-integer/package.json | 48 + node_modules/big-integer/tsconfig.json | 26 + node_modules/bl/.github/dependabot.yml | 16 + .../bl/.github/workflows/test-and-release.yml | 61 + node_modules/bl/BufferList.d.ts | 382 + node_modules/bl/BufferList.js | 396 + node_modules/bl/CHANGELOG.md | 17 + node_modules/bl/LICENSE.md | 13 + node_modules/bl/README.md | 247 + node_modules/bl/bl.js | 84 + node_modules/bl/index.d.ts | 88 + node_modules/bl/package.json | 123 + node_modules/bl/test/convert.js | 21 + node_modules/bl/test/indexOf.js | 492 + node_modules/bl/test/isBufferList.js | 32 + node_modules/bl/test/test.js | 914 + node_modules/brace-expansion/LICENSE | 21 + node_modules/brace-expansion/README.md | 129 + node_modules/brace-expansion/index.js | 201 + node_modules/brace-expansion/package.json | 47 + .../broadcast-channel/.github/FUNDING.yml | 3 + .../broadcast-channel/.github/README.md | 262 + .../.github/workflows/main.yml | 91 + node_modules/broadcast-channel/CHANGELOG.md | 41 + node_modules/broadcast-channel/LICENSE | 21 + node_modules/broadcast-channel/README.md | 36 + node_modules/broadcast-channel/package.json | 131 + .../src/broadcast-channel.js | 272 + .../broadcast-channel/src/browserify.index.js | 6 + .../broadcast-channel/src/index.es5.js | 24 + node_modules/broadcast-channel/src/index.js | 9 + .../broadcast-channel/src/leader-election.js | 230 + .../broadcast-channel/src/method-chooser.js | 72 + .../broadcast-channel/src/methods/cookies.js | 4 + .../src/methods/indexed-db.js | 332 + .../src/methods/localstorage.js | 185 + .../broadcast-channel/src/methods/native.js | 76 + .../broadcast-channel/src/methods/node.js | 694 + .../broadcast-channel/src/methods/simulate.js | 59 + node_modules/broadcast-channel/src/options.js | 30 + node_modules/broadcast-channel/src/util.js | 57 + .../types/broadcast-channel.d.ts | 65 + .../broadcast-channel/types/index.d.ts | 2 + .../types/leader-election.d.ts | 44 + node_modules/buffer/AUTHORS.md | 73 + node_modules/buffer/LICENSE | 21 + node_modules/buffer/README.md | 410 + node_modules/buffer/index.d.ts | 194 + node_modules/buffer/index.js | 2106 ++ node_modules/buffer/package.json | 93 + node_modules/cardinal/.npmignore | 1 + node_modules/cardinal/.travis.yml | 6 + node_modules/cardinal/LICENSE | 23 + node_modules/cardinal/README.md | 131 + node_modules/cardinal/bin/cdl.js | 78 + node_modules/cardinal/cardinal.js | 7 + node_modules/cardinal/examples/.cardinalrc | 3 + node_modules/cardinal/examples/README.md | 7 + node_modules/cardinal/examples/git-diff.txt | 78 + .../cardinal/examples/highlight-diff.js | 90 + .../cardinal/examples/highlight-json.js | 11 + .../highlight-self-hide-semicolons.js | 22 + .../cardinal/examples/highlight-self.js | 16 + .../cardinal/examples/highlight-string.js | 15 + node_modules/cardinal/package.json | 47 + node_modules/cardinal/settings.js | 53 + .../test/cardinal-highlight-block-comment.js | 22 + .../test/cardinal-highlight-file-async.js | 42 + .../test/cardinal-highlight-file-sync.js | 40 + .../cardinal-highlight-json-file-async.js | 15 + .../test/cardinal-highlight-json-file-sync.js | 14 + .../cardinal/test/cardinal-highlight-json.js | 32 + .../test/cardinal-highlight-string.js | 61 + node_modules/cardinal/test/cardinal-smoke.js | 37 + .../cardinal/test/fixtures/block-comment.js | 14 + node_modules/cardinal/test/fixtures/custom.js | 144 + .../cardinal/test/fixtures/foo-with-errors.js | 3 + node_modules/cardinal/test/fixtures/foo.js | 3 + node_modules/cardinal/test/fixtures/json.json | 1 + .../cardinal/test/fixtures/svn-diff.txt | 23 + node_modules/cardinal/test/settings.js | 77 + node_modules/cardinal/test/themes.js | 22 + node_modules/cardinal/themes/README.md | 31 + node_modules/cardinal/themes/default.js | 201 + node_modules/cardinal/themes/empty.js | 199 + .../cardinal/themes/hide-semicolons.js | 202 + node_modules/cardinal/themes/jq.js | 169 + .../cardinal/themes/tomorrow-night.js | 215 + node_modules/cardinal/utl.js | 12 + node_modules/chalk/license | 9 + node_modules/chalk/package.json | 81 + node_modules/chalk/readme.md | 325 + node_modules/chalk/source/index.d.ts | 320 + node_modules/chalk/source/index.js | 225 + node_modules/chalk/source/utilities.js | 33 + .../source/vendor/ansi-styles/index.d.ts | 236 + .../chalk/source/vendor/ansi-styles/index.js | 223 + .../source/vendor/supports-color/browser.d.ts | 1 + .../source/vendor/supports-color/browser.js | 30 + .../source/vendor/supports-color/index.d.ts | 55 + .../source/vendor/supports-color/index.js | 181 + node_modules/chardet/.travis.yml | 5 + node_modules/chardet/LICENSE | 19 + node_modules/chardet/README.md | 81 + node_modules/chardet/encoding/iso2022.js | 141 + node_modules/chardet/encoding/mbcs.js | 502 + node_modules/chardet/encoding/sbcs.js | 907 + node_modules/chardet/encoding/unicode.js | 112 + node_modules/chardet/encoding/utf8.js | 84 + node_modules/chardet/index.js | 151 + node_modules/chardet/match.js | 6 + node_modules/chardet/package.json | 47 + node_modules/ci-info/CHANGELOG.md | 78 + node_modules/ci-info/LICENSE | 21 + node_modules/ci-info/README.md | 108 + node_modules/ci-info/index.js | 66 + node_modules/ci-info/package.json | 36 + node_modules/ci-info/vendors.json | 153 + node_modules/cli-boxes/boxes.json | 58 + node_modules/cli-boxes/index.d.ts | 113 + node_modules/cli-boxes/index.js | 6 + node_modules/cli-boxes/license | 9 + node_modules/cli-boxes/package.json | 42 + node_modules/cli-boxes/readme.md | 105 + node_modules/cli-cursor/index.d.ts | 45 + node_modules/cli-cursor/index.js | 35 + node_modules/cli-cursor/license | 9 + node_modules/cli-cursor/package.json | 46 + node_modules/cli-cursor/readme.md | 55 + node_modules/cli-highlight/LICENSE.txt | 15 + node_modules/cli-highlight/README.md | 88 + node_modules/cli-highlight/bin/highlight | 2 + .../node_modules/chalk/index.d.ts | 415 + .../cli-highlight/node_modules/chalk/license | 9 + .../node_modules/chalk/package.json | 68 + .../node_modules/chalk/readme.md | 341 + .../node_modules/chalk/source/index.js | 229 + .../node_modules/chalk/source/templates.js | 134 + .../node_modules/chalk/source/util.js | 39 + node_modules/cli-highlight/package.json | 129 + node_modules/cli-spinners/index.d.ts | 125 + node_modules/cli-spinners/index.js | 15 + node_modules/cli-spinners/license | 9 + node_modules/cli-spinners/package.json | 49 + node_modules/cli-spinners/readme.md | 53 + node_modules/cli-spinners/spinners.json | 1468 + node_modules/cli-table3/CHANGELOG.md | 104 + node_modules/cli-table3/LICENSE | 21 + node_modules/cli-table3/README.md | 236 + node_modules/cli-table3/index.d.ts | 93 + node_modules/cli-table3/index.js | 1 + node_modules/cli-table3/package.json | 100 + node_modules/cli-table3/src/cell.js | 409 + node_modules/cli-table3/src/debug.js | 28 + node_modules/cli-table3/src/layout-manager.js | 254 + node_modules/cli-table3/src/table.js | 106 + node_modules/cli-table3/src/utils.js | 336 + node_modules/cli-truncate/index.d.ts | 96 + node_modules/cli-truncate/index.js | 106 + node_modules/cli-truncate/license | 9 + node_modules/cli-truncate/package.json | 46 + node_modules/cli-truncate/readme.md | 139 + node_modules/cli-width/.github/FUNDING.yml | 3 + .../cli-width/.github/workflows/node.js.yml | 31 + node_modules/cli-width/.prettierrc | 3 + node_modules/cli-width/LICENSE | 13 + node_modules/cli-width/README.md | 70 + node_modules/cli-width/index.js | 49 + node_modules/cli-width/package.json | 36 + node_modules/cliui/CHANGELOG.md | 121 + node_modules/cliui/LICENSE.txt | 14 + node_modules/cliui/README.md | 141 + node_modules/cliui/index.mjs | 13 + .../cliui/node_modules/ansi-regex/index.d.ts | 37 + .../cliui/node_modules/ansi-regex/index.js | 10 + .../cliui/node_modules/ansi-regex/license | 9 + .../node_modules/ansi-regex/package.json | 55 + .../cliui/node_modules/ansi-regex/readme.md | 78 + .../cliui/node_modules/strip-ansi/index.d.ts | 17 + .../cliui/node_modules/strip-ansi/index.js | 4 + .../cliui/node_modules/strip-ansi/license | 9 + .../node_modules/strip-ansi/package.json | 54 + .../cliui/node_modules/strip-ansi/readme.md | 46 + .../cliui/node_modules/wrap-ansi/index.js | 216 + .../cliui/node_modules/wrap-ansi/license | 9 + .../cliui/node_modules/wrap-ansi/package.json | 62 + .../cliui/node_modules/wrap-ansi/readme.md | 91 + node_modules/cliui/package.json | 83 + node_modules/clone/.npmignore | 4 + node_modules/clone/LICENSE | 18 + node_modules/clone/README.md | 126 + node_modules/clone/clone.iml | 10 + node_modules/clone/clone.js | 166 + node_modules/clone/package.json | 51 + node_modules/cls-hooked/CHANGELOG.md | 214 + node_modules/cls-hooked/LICENSE | 22 + node_modules/cls-hooked/README.md | 293 + node_modules/cls-hooked/context-legacy.js | 420 + node_modules/cls-hooked/context.js | 477 + node_modules/cls-hooked/index.js | 15 + node_modules/cls-hooked/package.json | 52 + node_modules/code-excerpt/index.d.ts | 44 + node_modules/code-excerpt/index.js | 40 + node_modules/code-excerpt/license | 21 + node_modules/code-excerpt/package.json | 30 + node_modules/code-excerpt/readme.md | 65 + node_modules/color-convert/CHANGELOG.md | 54 + node_modules/color-convert/LICENSE | 21 + node_modules/color-convert/README.md | 68 + node_modules/color-convert/conversions.js | 839 + node_modules/color-convert/index.js | 81 + node_modules/color-convert/package.json | 48 + node_modules/color-convert/route.js | 97 + node_modules/color-name/LICENSE | 8 + node_modules/color-name/README.md | 11 + node_modules/color-name/index.js | 152 + node_modules/color-name/package.json | 28 + node_modules/combined-stream/License | 19 + node_modules/combined-stream/Readme.md | 138 + node_modules/combined-stream/package.json | 25 + node_modules/combined-stream/yarn.lock | 17 + node_modules/commander/LICENSE | 22 + node_modules/commander/Readme.md | 1129 + node_modules/commander/esm.mjs | 16 + node_modules/commander/index.js | 27 + node_modules/commander/package-support.json | 16 + node_modules/commander/package.json | 80 + node_modules/commander/typings/index.d.ts | 891 + node_modules/concat-map/.travis.yml | 4 + node_modules/concat-map/LICENSE | 18 + node_modules/concat-map/README.markdown | 62 + node_modules/concat-map/example/map.js | 6 + node_modules/concat-map/index.js | 13 + node_modules/concat-map/package.json | 43 + node_modules/concat-map/test/map.js | 39 + .../continuation-local-storage/.eslintrc | 19 + .../continuation-local-storage/.travis.yml | 14 + .../continuation-local-storage/CHANGELOG.md | 168 + .../continuation-local-storage/LICENSE | 22 + .../continuation-local-storage/README.md | 273 + .../continuation-local-storage/context.js | 212 + .../continuation-local-storage/package.json | 38 + .../test/async-context.tap.js | 18 + .../test/async-no-run-queue-multiple.tap.js | 23 + .../test/bind-emitter.tap.js | 378 + .../test/bind.tap.js | 45 + .../test/crypto.tap.js | 82 + .../test/dns.tap.js | 206 + .../test/error-handling.tap.js | 144 + .../continuation-local-storage/test/fs.tap.js | 892 + .../test/interleave-contexts.tap.js | 58 + .../test/monkeypatching.tap.js | 55 + .../test/namespaces.tap.js | 29 + .../test/nesting.tap.js | 73 + .../test/net-events.tap.js | 45 + .../test/promises.tap.js | 121 + .../test/proper-exit.tap.js | 17 + .../test/run-and-return.tap.js | 40 + .../test/simple.tap.js | 42 + .../test/timers.tap.js | 76 + .../test/tracer-scenarios.tap.js | 338 + .../test/zlib.tap.js | 28 + node_modules/convert-to-spaces/index.js | 5 + node_modules/convert-to-spaces/license | 21 + node_modules/convert-to-spaces/package.json | 25 + node_modules/convert-to-spaces/readme.md | 48 + node_modules/debug/LICENSE | 20 + node_modules/debug/README.md | 481 + node_modules/debug/package.json | 59 + node_modules/debug/src/browser.js | 269 + node_modules/debug/src/common.js | 274 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/node.js | 263 + node_modules/defaults/LICENSE | 22 + node_modules/defaults/README.md | 39 + node_modules/defaults/index.js | 13 + node_modules/defaults/package.json | 33 + node_modules/defaults/test.js | 34 + node_modules/delayed-stream/.npmignore | 1 + node_modules/delayed-stream/License | 19 + node_modules/delayed-stream/Makefile | 7 + node_modules/delayed-stream/Readme.md | 141 + node_modules/delayed-stream/package.json | 27 + node_modules/detect-node/LICENSE | 21 + node_modules/detect-node/Readme.md | 30 + node_modules/detect-node/browser.js | 2 + node_modules/detect-node/index.esm.js | 2 + node_modules/detect-node/index.js | 2 + node_modules/detect-node/package.json | 25 + .../diagnostic-channel-publishers/LICENSE | 21 + .../diagnostic-channel-publishers/README.md | 14 + .../package.json | 57 + node_modules/diagnostic-channel/LICENSE | 21 + node_modules/diagnostic-channel/README.md | 161 + node_modules/diagnostic-channel/package.json | 42 + node_modules/eastasianwidth/README.md | 32 + node_modules/eastasianwidth/eastasianwidth.js | 311 + node_modules/eastasianwidth/package.json | 18 + node_modules/emitter-listener/.travis.yml | 7 + node_modules/emitter-listener/README.md | 44 + node_modules/emitter-listener/listener.js | 172 + node_modules/emitter-listener/package.json | 37 + .../emitter-listener/test/basic.tap.js | 193 + node_modules/emoji-regex/LICENSE-MIT.txt | 20 + node_modules/emoji-regex/README.md | 73 + node_modules/emoji-regex/es2015/index.js | 6 + node_modules/emoji-regex/es2015/text.js | 6 + node_modules/emoji-regex/index.d.ts | 23 + node_modules/emoji-regex/index.js | 6 + node_modules/emoji-regex/package.json | 50 + node_modules/emoji-regex/text.js | 6 + node_modules/escalade/index.d.ts | 3 + node_modules/escalade/license | 9 + node_modules/escalade/package.json | 61 + node_modules/escalade/readme.md | 211 + node_modules/escalade/sync/index.d.ts | 2 + node_modules/escalade/sync/index.js | 18 + node_modules/escalade/sync/index.mjs | 18 + node_modules/escape-string-regexp/index.js | 11 + node_modules/escape-string-regexp/license | 21 + .../escape-string-regexp/package.json | 41 + node_modules/escape-string-regexp/readme.md | 27 + node_modules/esprima/ChangeLog | 235 + node_modules/esprima/LICENSE.BSD | 21 + node_modules/esprima/README.md | 46 + node_modules/esprima/bin/esparse.js | 139 + node_modules/esprima/bin/esvalidate.js | 236 + node_modules/esprima/package.json | 112 + node_modules/external-editor/LICENSE | 21 + node_modules/external-editor/README.md | 171 + node_modules/external-editor/example_async.js | 40 + node_modules/external-editor/example_sync.js | 38 + .../main/errors/CreateFileError.d.ts | 10 + .../main/errors/CreateFileError.js | 39 + .../main/errors/LaunchEditorError.d.ts | 10 + .../main/errors/LaunchEditorError.js | 39 + .../main/errors/ReadFileError.d.ts | 10 + .../main/errors/ReadFileError.js | 39 + .../main/errors/RemoveFileError.d.ts | 10 + .../main/errors/RemoveFileError.js | 39 + node_modules/external-editor/main/index.d.ts | 46 + node_modules/external-editor/main/index.js | 193 + node_modules/external-editor/package.json | 61 + node_modules/figures/index.d.ts | 96 + node_modules/figures/index.js | 151 + node_modules/figures/license | 9 + node_modules/figures/package.json | 45 + node_modules/figures/readme.md | 139 + node_modules/follow-redirects/LICENSE | 18 + node_modules/follow-redirects/README.md | 155 + node_modules/follow-redirects/debug.js | 15 + node_modules/follow-redirects/http.js | 1 + node_modules/follow-redirects/https.js | 1 + node_modules/follow-redirects/index.js | 621 + node_modules/follow-redirects/package.json | 59 + node_modules/form-data/License | 19 + node_modules/form-data/README.md.bak | 358 + node_modules/form-data/Readme.md | 358 + node_modules/form-data/index.d.ts | 62 + node_modules/form-data/package.json | 68 + node_modules/fs.realpath/LICENSE | 43 + node_modules/fs.realpath/README.md | 33 + node_modules/fs.realpath/index.js | 66 + node_modules/fs.realpath/old.js | 303 + node_modules/fs.realpath/package.json | 26 + node_modules/get-caller-file/LICENSE.md | 6 + node_modules/get-caller-file/README.md | 41 + node_modules/get-caller-file/index.d.ts | 2 + node_modules/get-caller-file/index.js | 22 + node_modules/get-caller-file/index.js.map | 1 + node_modules/get-caller-file/package.json | 42 + node_modules/get-stream/buffer-stream.js | 52 + node_modules/get-stream/index.d.ts | 105 + node_modules/get-stream/index.js | 61 + node_modules/get-stream/license | 9 + node_modules/get-stream/package.json | 47 + node_modules/get-stream/readme.md | 124 + node_modules/glob/LICENSE | 21 + node_modules/glob/README.md | 378 + node_modules/glob/common.js | 238 + node_modules/glob/glob.js | 790 + node_modules/glob/package.json | 55 + node_modules/glob/sync.js | 486 + node_modules/has-flag/index.d.ts | 39 + node_modules/has-flag/index.js | 8 + node_modules/has-flag/license | 9 + node_modules/has-flag/package.json | 46 + node_modules/has-flag/readme.md | 89 + node_modules/highlight.js/LICENSE | 29 + node_modules/highlight.js/README.md | 371 + node_modules/highlight.js/package.json | 86 + node_modules/highlight.js/scss/a11y-dark.scss | 99 + .../highlight.js/scss/a11y-light.scss | 99 + node_modules/highlight.js/scss/agate.scss | 108 + .../highlight.js/scss/an-old-hope.scss | 89 + .../highlight.js/scss/androidstudio.scss | 66 + .../highlight.js/scss/arduino-light.scss | 87 + node_modules/highlight.js/scss/arta.scss | 73 + node_modules/highlight.js/scss/ascetic.scss | 45 + .../highlight.js/scss/atelier-cave-dark.scss | 83 + .../highlight.js/scss/atelier-cave-light.scss | 85 + .../highlight.js/scss/atelier-dune-dark.scss | 69 + .../highlight.js/scss/atelier-dune-light.scss | 69 + .../scss/atelier-estuary-dark.scss | 84 + .../scss/atelier-estuary-light.scss | 84 + .../scss/atelier-forest-dark.scss | 69 + .../scss/atelier-forest-light.scss | 69 + .../highlight.js/scss/atelier-heath-dark.scss | 69 + .../scss/atelier-heath-light.scss | 69 + .../scss/atelier-lakeside-dark.scss | 69 + .../scss/atelier-lakeside-light.scss | 69 + .../scss/atelier-plateau-dark.scss | 84 + .../scss/atelier-plateau-light.scss | 84 + .../scss/atelier-savanna-dark.scss | 84 + .../scss/atelier-savanna-light.scss | 84 + .../scss/atelier-seaside-dark.scss | 69 + .../scss/atelier-seaside-light.scss | 69 + .../scss/atelier-sulphurpool-dark.scss | 69 + .../scss/atelier-sulphurpool-light.scss | 69 + .../scss/atom-one-dark-reasonable.scss | 75 + .../highlight.js/scss/atom-one-dark.scss | 96 + .../highlight.js/scss/atom-one-light.scss | 96 + .../highlight.js/scss/brown-paper.scss | 64 + .../highlight.js/scss/brown-papersq.png | Bin 0 -> 18198 bytes .../highlight.js/scss/codepen-embed.scss | 60 + .../highlight.js/scss/color-brewer.scss | 71 + node_modules/highlight.js/scss/darcula.scss | 74 + node_modules/highlight.js/scss/dark.scss | 63 + node_modules/highlight.js/scss/default.scss | 99 + node_modules/highlight.js/scss/docco.scss | 97 + node_modules/highlight.js/scss/dracula.scss | 76 + node_modules/highlight.js/scss/far.scss | 71 + .../highlight.js/scss/foundation.scss | 89 + .../highlight.js/scss/github-gist.scss | 79 + node_modules/highlight.js/scss/github.scss | 99 + node_modules/highlight.js/scss/gml.scss | 78 + .../highlight.js/scss/googlecode.scss | 89 + .../highlight.js/scss/gradient-dark.scss | 122 + .../highlight.js/scss/gradient-light.scss | 130 + node_modules/highlight.js/scss/grayscale.scss | 101 + .../highlight.js/scss/gruvbox-dark.scss | 108 + .../highlight.js/scss/gruvbox-light.scss | 108 + node_modules/highlight.js/scss/hopscotch.scss | 84 + node_modules/highlight.js/scss/hybrid.scss | 102 + node_modules/highlight.js/scss/idea.scss | 97 + node_modules/highlight.js/scss/ir-black.scss | 73 + .../highlight.js/scss/isbl-editor-dark.scss | 112 + .../highlight.js/scss/isbl-editor-light.scss | 111 + .../highlight.js/scss/kimbie.dark.scss | 74 + .../highlight.js/scss/kimbie.light.scss | 74 + node_modules/highlight.js/scss/lightfair.scss | 88 + node_modules/highlight.js/scss/lioshi.scss | 88 + node_modules/highlight.js/scss/magula.scss | 70 + node_modules/highlight.js/scss/mono-blue.scss | 56 + .../highlight.js/scss/monokai-sublime.scss | 83 + node_modules/highlight.js/scss/monokai.scss | 71 + node_modules/highlight.js/scss/night-owl.scss | 182 + node_modules/highlight.js/scss/nnfx-dark.scss | 106 + node_modules/highlight.js/scss/nnfx.scss | 106 + node_modules/highlight.js/scss/nord.scss | 309 + node_modules/highlight.js/scss/obsidian.scss | 88 + node_modules/highlight.js/scss/ocean.scss | 74 + .../highlight.js/scss/paraiso-dark.scss | 72 + .../highlight.js/scss/paraiso-light.scss | 72 + node_modules/highlight.js/scss/pojoaque.jpg | Bin 0 -> 1186 bytes node_modules/highlight.js/scss/pojoaque.scss | 83 + node_modules/highlight.js/scss/purebasic.scss | 96 + .../highlight.js/scss/qtcreator_dark.scss | 83 + .../highlight.js/scss/qtcreator_light.scss | 83 + .../highlight.js/scss/railscasts.scss | 106 + node_modules/highlight.js/scss/rainbow.scss | 85 + node_modules/highlight.js/scss/routeros.scss | 108 + .../highlight.js/scss/school-book.png | Bin 0 -> 486 bytes .../highlight.js/scss/school-book.scss | 69 + .../highlight.js/scss/shades-of-purple.scss | 96 + .../highlight.js/scss/solarized-dark.scss | 84 + .../highlight.js/scss/solarized-light.scss | 84 + node_modules/highlight.js/scss/srcery.scss | 78 + .../highlight.js/scss/stackoverflow-dark.scss | 78 + .../scss/stackoverflow-light.scss | 78 + node_modules/highlight.js/scss/sunburst.scss | 102 + .../scss/tomorrow-night-blue.scss | 75 + .../scss/tomorrow-night-bright.scss | 74 + .../scss/tomorrow-night-eighties.scss | 74 + .../highlight.js/scss/tomorrow-night.scss | 75 + node_modules/highlight.js/scss/tomorrow.scss | 72 + node_modules/highlight.js/scss/vs.scss | 68 + node_modules/highlight.js/scss/vs2015.scss | 115 + node_modules/highlight.js/scss/xcode.scss | 104 + node_modules/highlight.js/scss/xt256.scss | 92 + node_modules/highlight.js/scss/zenburn.scss | 80 + .../highlight.js/styles/a11y-dark.css | 99 + .../highlight.js/styles/a11y-light.css | 99 + node_modules/highlight.js/styles/agate.css | 108 + .../highlight.js/styles/an-old-hope.css | 89 + .../highlight.js/styles/androidstudio.css | 66 + .../highlight.js/styles/arduino-light.css | 87 + node_modules/highlight.js/styles/arta.css | 73 + node_modules/highlight.js/styles/ascetic.css | 45 + .../highlight.js/styles/atelier-cave-dark.css | 83 + .../styles/atelier-cave-light.css | 85 + .../highlight.js/styles/atelier-dune-dark.css | 69 + .../styles/atelier-dune-light.css | 69 + .../styles/atelier-estuary-dark.css | 84 + .../styles/atelier-estuary-light.css | 84 + .../styles/atelier-forest-dark.css | 69 + .../styles/atelier-forest-light.css | 69 + .../styles/atelier-heath-dark.css | 69 + .../styles/atelier-heath-light.css | 69 + .../styles/atelier-lakeside-dark.css | 69 + .../styles/atelier-lakeside-light.css | 69 + .../styles/atelier-plateau-dark.css | 84 + .../styles/atelier-plateau-light.css | 84 + .../styles/atelier-savanna-dark.css | 84 + .../styles/atelier-savanna-light.css | 84 + .../styles/atelier-seaside-dark.css | 69 + .../styles/atelier-seaside-light.css | 69 + .../styles/atelier-sulphurpool-dark.css | 69 + .../styles/atelier-sulphurpool-light.css | 69 + .../styles/atom-one-dark-reasonable.css | 75 + .../highlight.js/styles/atom-one-dark.css | 96 + .../highlight.js/styles/atom-one-light.css | 96 + .../highlight.js/styles/brown-paper.css | 64 + .../highlight.js/styles/brown-papersq.png | Bin 0 -> 18198 bytes .../highlight.js/styles/codepen-embed.css | 60 + .../highlight.js/styles/color-brewer.css | 71 + node_modules/highlight.js/styles/darcula.css | 74 + node_modules/highlight.js/styles/dark.css | 63 + node_modules/highlight.js/styles/default.css | 99 + node_modules/highlight.js/styles/docco.css | 97 + node_modules/highlight.js/styles/dracula.css | 76 + node_modules/highlight.js/styles/far.css | 71 + .../highlight.js/styles/foundation.css | 89 + .../highlight.js/styles/github-gist.css | 79 + node_modules/highlight.js/styles/github.css | 99 + node_modules/highlight.js/styles/gml.css | 78 + .../highlight.js/styles/googlecode.css | 89 + .../highlight.js/styles/gradient-dark.css | 122 + .../highlight.js/styles/gradient-light.css | 130 + .../highlight.js/styles/grayscale.css | 101 + .../highlight.js/styles/gruvbox-dark.css | 108 + .../highlight.js/styles/gruvbox-light.css | 108 + .../highlight.js/styles/hopscotch.css | 84 + node_modules/highlight.js/styles/hybrid.css | 102 + node_modules/highlight.js/styles/idea.css | 97 + node_modules/highlight.js/styles/ir-black.css | 73 + .../highlight.js/styles/isbl-editor-dark.css | 112 + .../highlight.js/styles/isbl-editor-light.css | 111 + .../highlight.js/styles/kimbie.dark.css | 74 + .../highlight.js/styles/kimbie.light.css | 74 + .../highlight.js/styles/lightfair.css | 88 + node_modules/highlight.js/styles/lioshi.css | 88 + node_modules/highlight.js/styles/magula.css | 70 + .../highlight.js/styles/mono-blue.css | 56 + .../highlight.js/styles/monokai-sublime.css | 83 + node_modules/highlight.js/styles/monokai.css | 71 + .../highlight.js/styles/night-owl.css | 182 + .../highlight.js/styles/nnfx-dark.css | 106 + node_modules/highlight.js/styles/nnfx.css | 106 + node_modules/highlight.js/styles/nord.css | 309 + node_modules/highlight.js/styles/obsidian.css | 88 + node_modules/highlight.js/styles/ocean.css | 74 + .../highlight.js/styles/paraiso-dark.css | 72 + .../highlight.js/styles/paraiso-light.css | 72 + node_modules/highlight.js/styles/pojoaque.css | 83 + node_modules/highlight.js/styles/pojoaque.jpg | Bin 0 -> 1186 bytes .../highlight.js/styles/purebasic.css | 96 + .../highlight.js/styles/qtcreator_dark.css | 83 + .../highlight.js/styles/qtcreator_light.css | 83 + .../highlight.js/styles/railscasts.css | 106 + node_modules/highlight.js/styles/rainbow.css | 85 + node_modules/highlight.js/styles/routeros.css | 108 + .../highlight.js/styles/school-book.css | 69 + .../highlight.js/styles/school-book.png | Bin 0 -> 486 bytes .../highlight.js/styles/shades-of-purple.css | 96 + .../highlight.js/styles/solarized-dark.css | 84 + .../highlight.js/styles/solarized-light.css | 84 + node_modules/highlight.js/styles/srcery.css | 78 + .../styles/stackoverflow-dark.css | 78 + .../styles/stackoverflow-light.css | 78 + node_modules/highlight.js/styles/sunburst.css | 102 + .../styles/tomorrow-night-blue.css | 75 + .../styles/tomorrow-night-bright.css | 74 + .../styles/tomorrow-night-eighties.css | 74 + .../highlight.js/styles/tomorrow-night.css | 75 + node_modules/highlight.js/styles/tomorrow.css | 72 + node_modules/highlight.js/styles/vs.css | 68 + node_modules/highlight.js/styles/vs2015.css | 115 + node_modules/highlight.js/styles/xcode.css | 104 + node_modules/highlight.js/styles/xt256.css | 92 + node_modules/highlight.js/styles/zenburn.css | 80 + node_modules/highlight.js/types/index.d.ts | 261 + node_modules/http-proxy-agent/README.md | 74 + node_modules/http-proxy-agent/package.json | 57 + node_modules/https-proxy-agent/README.md | 137 + node_modules/https-proxy-agent/package.json | 56 + node_modules/iconv-lite/Changelog.md | 162 + node_modules/iconv-lite/LICENSE | 21 + node_modules/iconv-lite/README.md | 156 + .../iconv-lite/encodings/dbcs-codec.js | 555 + .../iconv-lite/encodings/dbcs-data.js | 176 + node_modules/iconv-lite/encodings/index.js | 22 + node_modules/iconv-lite/encodings/internal.js | 188 + .../iconv-lite/encodings/sbcs-codec.js | 72 + .../encodings/sbcs-data-generated.js | 451 + .../iconv-lite/encodings/sbcs-data.js | 174 + .../encodings/tables/big5-added.json | 122 + .../iconv-lite/encodings/tables/cp936.json | 264 + .../iconv-lite/encodings/tables/cp949.json | 273 + .../iconv-lite/encodings/tables/cp950.json | 177 + .../iconv-lite/encodings/tables/eucjp.json | 182 + .../encodings/tables/gb18030-ranges.json | 1 + .../encodings/tables/gbk-added.json | 55 + .../iconv-lite/encodings/tables/shiftjis.json | 125 + node_modules/iconv-lite/encodings/utf16.js | 177 + node_modules/iconv-lite/encodings/utf7.js | 290 + node_modules/iconv-lite/package.json | 46 + node_modules/ieee754/LICENSE | 11 + node_modules/ieee754/README.md | 51 + node_modules/ieee754/index.d.ts | 10 + node_modules/ieee754/index.js | 85 + node_modules/ieee754/package.json | 52 + node_modules/immer/LICENSE | 21 + node_modules/immer/package.json | 104 + node_modules/immer/readme.md | 33 + node_modules/immer/src/core/current.ts | 60 + node_modules/immer/src/core/finalize.ts | 168 + node_modules/immer/src/core/immerClass.ts | 241 + node_modules/immer/src/core/proxy.ts | 280 + node_modules/immer/src/core/scope.ts | 85 + node_modules/immer/src/immer.ts | 117 + node_modules/immer/src/internal.ts | 11 + node_modules/immer/src/plugins/all.ts | 9 + node_modules/immer/src/plugins/es5.ts | 277 + node_modules/immer/src/plugins/mapset.ts | 348 + node_modules/immer/src/plugins/patches.ts | 301 + node_modules/immer/src/types/globals.d.ts | 1 + node_modules/immer/src/types/index.js.flow | 113 + .../immer/src/types/types-external.ts | 262 + .../immer/src/types/types-internal.ts | 55 + node_modules/immer/src/utils/common.ts | 216 + node_modules/immer/src/utils/env.ts | 47 + node_modules/immer/src/utils/errors.ts | 60 + node_modules/immer/src/utils/plugins.ts | 109 + node_modules/indent-string/index.d.ts | 42 + node_modules/indent-string/index.js | 35 + node_modules/indent-string/license | 9 + node_modules/indent-string/package.json | 37 + node_modules/indent-string/readme.md | 70 + node_modules/inflight/LICENSE | 15 + node_modules/inflight/README.md | 37 + node_modules/inflight/inflight.js | 54 + node_modules/inflight/package.json | 29 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 9 + node_modules/inherits/inherits_browser.js | 27 + node_modules/inherits/package.json | 29 + node_modules/ink-divider/license | 21 + node_modules/ink-divider/package.json | 79 + node_modules/ink-divider/readme.md | 78 + node_modules/ink-select-input/license | 9 + node_modules/ink-select-input/package.json | 83 + node_modules/ink-select-input/readme.md | 100 + node_modules/ink-spinner/license | 9 + node_modules/ink-spinner/package.json | 83 + node_modules/ink-spinner/readme.md | 39 + node_modules/ink-text-input/license | 9 + .../node_modules/chalk/index.d.ts | 415 + .../ink-text-input/node_modules/chalk/license | 9 + .../node_modules/chalk/package.json | 68 + .../node_modules/chalk/readme.md | 341 + .../node_modules/chalk/source/index.js | 229 + .../node_modules/chalk/source/templates.js | 134 + .../node_modules/chalk/source/util.js | 39 + .../node_modules/type-fest/index.d.ts | 30 + .../node_modules/type-fest/license | 9 + .../node_modules/type-fest/package.json | 45 + .../node_modules/type-fest/readme.md | 643 + .../type-fest/source/async-return-type.d.ts | 23 + .../node_modules/type-fest/source/basic.d.ts | 67 + .../type-fest/source/conditional-except.d.ts | 43 + .../type-fest/source/conditional-keys.d.ts | 43 + .../type-fest/source/conditional-pick.d.ts | 42 + .../node_modules/type-fest/source/except.d.ts | 22 + .../type-fest/source/fixed-length-array.d.ts | 38 + .../type-fest/source/literal-union.d.ts | 33 + .../type-fest/source/merge-exclusive.d.ts | 39 + .../node_modules/type-fest/source/merge.d.ts | 22 + .../type-fest/source/mutable.d.ts | 22 + .../node_modules/type-fest/source/opaque.d.ts | 65 + .../type-fest/source/package-json.d.ts | 622 + .../type-fest/source/partial-deep.d.ts | 72 + .../type-fest/source/promisable.d.ts | 23 + .../type-fest/source/promise-value.d.ts | 20 + .../type-fest/source/readonly-deep.d.ts | 59 + .../source/require-at-least-one.d.ts | 32 + .../type-fest/source/require-exactly-one.d.ts | 35 + .../type-fest/source/set-optional.d.ts | 34 + .../type-fest/source/set-required.d.ts | 34 + .../type-fest/source/stringified.d.ts | 21 + .../type-fest/source/tsconfig-json.d.ts | 872 + .../source/union-to-intersection.d.ts | 58 + .../type-fest/source/value-of.d.ts | 40 + node_modules/ink-text-input/package.json | 96 + node_modules/ink-text-input/readme.md | 124 + node_modules/ink/license | 9 + .../ink/node_modules/chalk/index.d.ts | 415 + node_modules/ink/node_modules/chalk/license | 9 + .../ink/node_modules/chalk/package.json | 68 + node_modules/ink/node_modules/chalk/readme.md | 341 + .../ink/node_modules/chalk/source/index.js | 229 + .../node_modules/chalk/source/templates.js | 134 + .../ink/node_modules/chalk/source/util.js | 39 + node_modules/ink/package.json | 172 + node_modules/ink/readme.md | 1810 ++ node_modules/inquirer/LICENSE | 22 + node_modules/inquirer/README.md | 521 + .../node_modules/ansi-escapes/index.d.ts | 247 + .../node_modules/ansi-escapes/index.js | 158 + .../node_modules/ansi-escapes/license | 9 + .../node_modules/ansi-escapes/package.json | 60 + .../node_modules/ansi-escapes/readme.md | 233 + .../node_modules/ansi-styles/index.d.ts | 236 + .../node_modules/ansi-styles/index.js | 223 + .../inquirer/node_modules/ansi-styles/license | 9 + .../node_modules/ansi-styles/package.json | 54 + .../node_modules/ansi-styles/readme.md | 173 + .../node_modules/cli-cursor/index.d.ts | 47 + .../inquirer/node_modules/cli-cursor/index.js | 39 + .../inquirer/node_modules/cli-cursor/license | 9 + .../node_modules/cli-cursor/package.json | 49 + .../node_modules/cli-cursor/readme.md | 51 + .../node_modules/emoji-regex/LICENSE-MIT.txt | 20 + .../node_modules/emoji-regex/README.md | 137 + .../node_modules/emoji-regex/RGI_Emoji.d.ts | 5 + .../node_modules/emoji-regex/RGI_Emoji.js | 6 + .../emoji-regex/es2015/RGI_Emoji.d.ts | 5 + .../emoji-regex/es2015/RGI_Emoji.js | 6 + .../emoji-regex/es2015/index.d.ts | 5 + .../node_modules/emoji-regex/es2015/index.js | 6 + .../node_modules/emoji-regex/es2015/text.d.ts | 5 + .../node_modules/emoji-regex/es2015/text.js | 6 + .../node_modules/emoji-regex/index.d.ts | 5 + .../node_modules/emoji-regex/index.js | 6 + .../node_modules/emoji-regex/package.json | 52 + .../node_modules/emoji-regex/text.d.ts | 5 + .../inquirer/node_modules/emoji-regex/text.js | 6 + .../escape-string-regexp/index.d.ts | 16 + .../escape-string-regexp/index.js | 11 + .../node_modules/escape-string-regexp/license | 9 + .../escape-string-regexp/package.json | 40 + .../escape-string-regexp/readme.md | 34 + .../inquirer/node_modules/figures/index.d.ts | 269 + .../inquirer/node_modules/figures/index.js | 322 + .../inquirer/node_modules/figures/license | 9 + .../node_modules/figures/package.json | 46 + .../inquirer/node_modules/figures/readme.md | 328 + .../node_modules/restore-cursor/index.d.ts | 11 + .../node_modules/restore-cursor/index.js | 11 + .../node_modules/restore-cursor/license | 9 + .../node_modules/restore-cursor/package.json | 55 + .../node_modules/restore-cursor/readme.md | 31 + .../node_modules/string-width/index.d.ts | 29 + .../node_modules/string-width/index.js | 54 + .../node_modules/string-width/license | 9 + .../node_modules/string-width/package.json | 59 + .../node_modules/string-width/readme.md | 67 + .../node_modules/type-fest/index.d.ts | 108 + .../node_modules/type-fest/package.json | 53 + .../inquirer/node_modules/type-fest/readme.md | 905 + .../type-fest/source/async-return-type.d.ts | 23 + .../type-fest/source/asyncify.d.ts | 32 + .../node_modules/type-fest/source/basic.d.ts | 45 + .../type-fest/source/camel-case.d.ts | 80 + .../source/camel-cased-properties-deep.d.ts | 54 + .../source/camel-cased-properties.d.ts | 36 + .../type-fest/source/conditional-except.d.ts | 45 + .../type-fest/source/conditional-keys.d.ts | 47 + .../source/conditional-pick-deep.d.ts | 102 + .../type-fest/source/conditional-pick.d.ts | 44 + .../source/conditional-simplify.d.ts | 32 + .../type-fest/source/delimiter-case.d.ts | 99 + .../delimiter-cased-properties-deep.d.ts | 60 + .../source/delimiter-cased-properties.d.ts | 37 + .../type-fest/source/empty-object.d.ts | 46 + .../type-fest/source/enforce-optional.d.ts | 47 + .../type-fest/source/entries.d.ts | 62 + .../node_modules/type-fest/source/entry.d.ts | 65 + .../node_modules/type-fest/source/exact.d.ts | 62 + .../node_modules/type-fest/source/except.d.ts | 57 + .../type-fest/source/fixed-length-array.d.ts | 43 + .../node_modules/type-fest/source/get.d.ts | 191 + .../type-fest/source/global-this.d.ts | 21 + .../type-fest/source/has-optional-keys.d.ts | 21 + .../type-fest/source/has-required-keys.d.ts | 59 + .../type-fest/source/includes.d.ts | 22 + .../type-fest/source/internal.d.ts | 259 + .../type-fest/source/invariant-of.d.ts | 76 + .../type-fest/source/is-equal.d.ts | 30 + .../type-fest/source/iterable-element.d.ts | 54 + .../node_modules/type-fest/source/join.d.ts | 35 + .../type-fest/source/jsonifiable.d.ts | 37 + .../type-fest/source/jsonify.d.ts | 114 + .../type-fest/source/kebab-case.d.ts | 38 + .../source/kebab-cased-properties-deep.d.ts | 47 + .../source/kebab-cased-properties.d.ts | 30 + .../type-fest/source/last-array-element.d.ts | 28 + .../source/literal-to-primitive.d.ts | 36 + .../type-fest/source/literal-union.d.ts | 35 + .../type-fest/source/merge-deep.d.ts | 470 + .../type-fest/source/merge-exclusive.d.ts | 41 + .../node_modules/type-fest/source/merge.d.ts | 50 + .../source/multidimensional-array.d.ts | 44 + .../multidimensional-readonly-array.d.ts | 48 + .../type-fest/source/numeric.d.ts | 170 + .../type-fest/source/observable-like.d.ts | 63 + .../source/omit-index-signature.d.ts | 107 + .../node_modules/type-fest/source/opaque.d.ts | 107 + .../type-fest/source/optional-keys-of.d.ts | 38 + .../type-fest/source/package-json.d.ts | 690 + .../type-fest/source/partial-deep.d.ts | 111 + .../source/partial-on-undefined-deep.d.ts | 70 + .../type-fest/source/pascal-case.d.ts | 38 + .../source/pascal-cased-properties-deep.d.ts | 54 + .../source/pascal-cased-properties.d.ts | 34 + .../source/pick-index-signature.d.ts | 102 + .../type-fest/source/primitive.d.ts | 13 + .../type-fest/source/promisable.d.ts | 25 + .../type-fest/source/readonly-deep.d.ts | 70 + .../type-fest/source/readonly-tuple.d.ts | 41 + .../type-fest/source/replace.d.ts | 67 + .../type-fest/source/require-all-or-none.d.ts | 36 + .../source/require-at-least-one.d.ts | 34 + .../type-fest/source/require-exactly-one.d.ts | 34 + .../type-fest/source/required-keys-of.d.ts | 29 + .../node_modules/type-fest/source/schema.d.ts | 71 + .../source/screaming-snake-case.d.ts | 33 + .../type-fest/source/set-non-nullable.d.ts | 39 + .../type-fest/source/set-optional.d.ts | 35 + .../type-fest/source/set-required.d.ts | 35 + .../type-fest/source/set-return-type.d.ts | 29 + .../type-fest/source/simplify.d.ts | 58 + .../type-fest/source/snake-case.d.ts | 38 + .../source/snake-cased-properties-deep.d.ts | 47 + .../source/snake-cased-properties.d.ts | 30 + .../type-fest/source/split-words.d.ts | 57 + .../node_modules/type-fest/source/split.d.ts | 29 + .../node_modules/type-fest/source/spread.d.ts | 85 + .../type-fest/source/string-key-of.d.ts | 25 + .../type-fest/source/stringified.d.ts | 23 + .../node_modules/type-fest/source/trim.d.ts | 27 + .../type-fest/source/tsconfig-json.d.ts | 1119 + .../type-fest/source/tuple-to-union.d.ts | 51 + .../type-fest/source/typed-array.d.ts | 17 + .../source/union-to-intersection.d.ts | 60 + .../type-fest/source/value-of.d.ts | 42 + .../type-fest/source/writable-deep.d.ts | 64 + .../type-fest/source/writable.d.ts | 40 + .../node_modules/wrap-ansi/index.d.ts | 41 + .../inquirer/node_modules/wrap-ansi/index.js | 214 + .../inquirer/node_modules/wrap-ansi/license | 9 + .../node_modules/wrap-ansi/package.json | 69 + .../inquirer/node_modules/wrap-ansi/readme.md | 91 + node_modules/inquirer/package.json | 92 + node_modules/is-ci/CHANGELOG.md | 14 + node_modules/is-ci/LICENSE | 21 + node_modules/is-ci/README.md | 50 + node_modules/is-ci/bin.js | 4 + node_modules/is-ci/index.js | 3 + node_modules/is-ci/package.json | 38 + .../is-fullwidth-code-point/index.d.ts | 17 + node_modules/is-fullwidth-code-point/index.js | 50 + node_modules/is-fullwidth-code-point/license | 9 + .../is-fullwidth-code-point/package.json | 42 + .../is-fullwidth-code-point/readme.md | 39 + node_modules/is-interactive/index.d.ts | 25 + node_modules/is-interactive/index.js | 7 + node_modules/is-interactive/license | 9 + node_modules/is-interactive/package.json | 41 + node_modules/is-interactive/readme.md | 52 + node_modules/is-unicode-supported/index.d.ts | 12 + node_modules/is-unicode-supported/index.js | 17 + node_modules/is-unicode-supported/license | 9 + .../is-unicode-supported/package.json | 43 + node_modules/is-unicode-supported/readme.md | 35 + node_modules/js-sha3/CHANGELOG.md | 106 + node_modules/js-sha3/LICENSE.txt | 20 + node_modules/js-sha3/README.md | 241 + node_modules/js-sha3/index.d.ts | 317 + node_modules/js-sha3/package.json | 45 + node_modules/js-sha3/src/sha3.js | 656 + node_modules/js-tokens/CHANGELOG.md | 151 + node_modules/js-tokens/LICENSE | 21 + node_modules/js-tokens/README.md | 240 + node_modules/js-tokens/index.js | 23 + node_modules/js-tokens/package.json | 30 + node_modules/lodash.isequal/LICENSE | 47 + node_modules/lodash.isequal/README.md | 18 + node_modules/lodash.isequal/index.js | 1848 ++ node_modules/lodash.isequal/package.json | 16 + node_modules/lodash/LICENSE | 47 + node_modules/lodash/README.md | 39 + node_modules/lodash/_DataView.js | 7 + node_modules/lodash/_Hash.js | 32 + node_modules/lodash/_LazyWrapper.js | 28 + node_modules/lodash/_ListCache.js | 32 + node_modules/lodash/_LodashWrapper.js | 22 + node_modules/lodash/_Map.js | 7 + node_modules/lodash/_MapCache.js | 32 + node_modules/lodash/_Promise.js | 7 + node_modules/lodash/_Set.js | 7 + node_modules/lodash/_SetCache.js | 27 + node_modules/lodash/_Stack.js | 27 + node_modules/lodash/_Symbol.js | 6 + node_modules/lodash/_Uint8Array.js | 6 + node_modules/lodash/_WeakMap.js | 7 + node_modules/lodash/_apply.js | 21 + node_modules/lodash/_arrayAggregator.js | 22 + node_modules/lodash/_arrayEach.js | 22 + node_modules/lodash/_arrayEachRight.js | 21 + node_modules/lodash/_arrayEvery.js | 23 + node_modules/lodash/_arrayFilter.js | 25 + node_modules/lodash/_arrayIncludes.js | 17 + node_modules/lodash/_arrayIncludesWith.js | 22 + node_modules/lodash/_arrayLikeKeys.js | 49 + node_modules/lodash/_arrayMap.js | 21 + node_modules/lodash/_arrayPush.js | 20 + node_modules/lodash/_arrayReduce.js | 26 + node_modules/lodash/_arrayReduceRight.js | 24 + node_modules/lodash/_arraySample.js | 15 + node_modules/lodash/_arraySampleSize.js | 17 + node_modules/lodash/_arrayShuffle.js | 15 + node_modules/lodash/_arraySome.js | 23 + node_modules/lodash/_asciiSize.js | 12 + node_modules/lodash/_asciiToArray.js | 12 + node_modules/lodash/_asciiWords.js | 15 + node_modules/lodash/_assignMergeValue.js | 20 + node_modules/lodash/_assignValue.js | 28 + node_modules/lodash/_assocIndexOf.js | 21 + node_modules/lodash/_baseAggregator.js | 21 + node_modules/lodash/_baseAssign.js | 17 + node_modules/lodash/_baseAssignIn.js | 17 + node_modules/lodash/_baseAssignValue.js | 25 + node_modules/lodash/_baseAt.js | 23 + node_modules/lodash/_baseClamp.js | 22 + node_modules/lodash/_baseClone.js | 166 + node_modules/lodash/_baseConforms.js | 18 + node_modules/lodash/_baseConformsTo.js | 27 + node_modules/lodash/_baseCreate.js | 30 + node_modules/lodash/_baseDelay.js | 21 + node_modules/lodash/_baseDifference.js | 67 + node_modules/lodash/_baseEach.js | 14 + node_modules/lodash/_baseEachRight.js | 14 + node_modules/lodash/_baseEvery.js | 21 + node_modules/lodash/_baseExtremum.js | 32 + node_modules/lodash/_baseFill.js | 32 + node_modules/lodash/_baseFilter.js | 21 + node_modules/lodash/_baseFindIndex.js | 24 + node_modules/lodash/_baseFindKey.js | 23 + node_modules/lodash/_baseFlatten.js | 38 + node_modules/lodash/_baseFor.js | 16 + node_modules/lodash/_baseForOwn.js | 16 + node_modules/lodash/_baseForOwnRight.js | 16 + node_modules/lodash/_baseForRight.js | 15 + node_modules/lodash/_baseFunctions.js | 19 + node_modules/lodash/_baseGet.js | 24 + node_modules/lodash/_baseGetAllKeys.js | 20 + node_modules/lodash/_baseGetTag.js | 28 + node_modules/lodash/_baseGt.js | 14 + node_modules/lodash/_baseHas.js | 19 + node_modules/lodash/_baseHasIn.js | 13 + node_modules/lodash/_baseInRange.js | 18 + node_modules/lodash/_baseIndexOf.js | 20 + node_modules/lodash/_baseIndexOfWith.js | 23 + node_modules/lodash/_baseIntersection.js | 74 + node_modules/lodash/_baseInverter.js | 21 + node_modules/lodash/_baseInvoke.js | 24 + node_modules/lodash/_baseIsArguments.js | 18 + node_modules/lodash/_baseIsArrayBuffer.js | 17 + node_modules/lodash/_baseIsDate.js | 18 + node_modules/lodash/_baseIsEqual.js | 28 + node_modules/lodash/_baseIsEqualDeep.js | 83 + node_modules/lodash/_baseIsMap.js | 18 + node_modules/lodash/_baseIsMatch.js | 62 + node_modules/lodash/_baseIsNaN.js | 12 + node_modules/lodash/_baseIsNative.js | 47 + node_modules/lodash/_baseIsRegExp.js | 18 + node_modules/lodash/_baseIsSet.js | 18 + node_modules/lodash/_baseIsTypedArray.js | 60 + node_modules/lodash/_baseIteratee.js | 31 + node_modules/lodash/_baseKeys.js | 30 + node_modules/lodash/_baseKeysIn.js | 33 + node_modules/lodash/_baseLodash.js | 10 + node_modules/lodash/_baseLt.js | 14 + node_modules/lodash/_baseMap.js | 22 + node_modules/lodash/_baseMatches.js | 22 + node_modules/lodash/_baseMatchesProperty.js | 33 + node_modules/lodash/_baseMean.js | 20 + node_modules/lodash/_baseMerge.js | 42 + node_modules/lodash/_baseMergeDeep.js | 94 + node_modules/lodash/_baseNth.js | 20 + node_modules/lodash/_baseOrderBy.js | 49 + node_modules/lodash/_basePick.js | 19 + node_modules/lodash/_basePickBy.js | 30 + node_modules/lodash/_baseProperty.js | 14 + node_modules/lodash/_basePropertyDeep.js | 16 + node_modules/lodash/_basePropertyOf.js | 14 + node_modules/lodash/_basePullAll.js | 51 + node_modules/lodash/_basePullAt.js | 37 + node_modules/lodash/_baseRandom.js | 18 + node_modules/lodash/_baseRange.js | 28 + node_modules/lodash/_baseReduce.js | 23 + node_modules/lodash/_baseRepeat.js | 35 + node_modules/lodash/_baseRest.js | 17 + node_modules/lodash/_baseSample.js | 15 + node_modules/lodash/_baseSampleSize.js | 18 + node_modules/lodash/_baseSet.js | 51 + node_modules/lodash/_baseSetData.js | 17 + node_modules/lodash/_baseSetToString.js | 22 + node_modules/lodash/_baseShuffle.js | 15 + node_modules/lodash/_baseSlice.js | 31 + node_modules/lodash/_baseSome.js | 22 + node_modules/lodash/_baseSortBy.js | 21 + node_modules/lodash/_baseSortedIndex.js | 42 + node_modules/lodash/_baseSortedIndexBy.js | 67 + node_modules/lodash/_baseSortedUniq.js | 30 + node_modules/lodash/_baseSum.js | 24 + node_modules/lodash/_baseTimes.js | 20 + node_modules/lodash/_baseToNumber.js | 24 + node_modules/lodash/_baseToPairs.js | 18 + node_modules/lodash/_baseToString.js | 37 + node_modules/lodash/_baseTrim.js | 19 + node_modules/lodash/_baseUnary.js | 14 + node_modules/lodash/_baseUniq.js | 72 + node_modules/lodash/_baseUnset.js | 20 + node_modules/lodash/_baseUpdate.js | 18 + node_modules/lodash/_baseValues.js | 19 + node_modules/lodash/_baseWhile.js | 26 + node_modules/lodash/_baseWrapperValue.js | 25 + node_modules/lodash/_baseXor.js | 36 + node_modules/lodash/_baseZipObject.js | 23 + node_modules/lodash/_cacheHas.js | 13 + node_modules/lodash/_castArrayLikeObject.js | 14 + node_modules/lodash/_castFunction.js | 14 + node_modules/lodash/_castPath.js | 21 + node_modules/lodash/_castRest.js | 14 + node_modules/lodash/_castSlice.js | 18 + node_modules/lodash/_charsEndIndex.js | 19 + node_modules/lodash/_charsStartIndex.js | 20 + node_modules/lodash/_cloneArrayBuffer.js | 16 + node_modules/lodash/_cloneBuffer.js | 35 + node_modules/lodash/_cloneDataView.js | 16 + node_modules/lodash/_cloneRegExp.js | 17 + node_modules/lodash/_cloneSymbol.js | 18 + node_modules/lodash/_cloneTypedArray.js | 16 + node_modules/lodash/_compareAscending.js | 41 + node_modules/lodash/_compareMultiple.js | 44 + node_modules/lodash/_composeArgs.js | 39 + node_modules/lodash/_composeArgsRight.js | 41 + node_modules/lodash/_copyArray.js | 20 + node_modules/lodash/_copyObject.js | 40 + node_modules/lodash/_copySymbols.js | 16 + node_modules/lodash/_copySymbolsIn.js | 16 + node_modules/lodash/_coreJsData.js | 6 + node_modules/lodash/_countHolders.js | 21 + node_modules/lodash/_createAggregator.js | 23 + node_modules/lodash/_createAssigner.js | 37 + node_modules/lodash/_createBaseEach.js | 32 + node_modules/lodash/_createBaseFor.js | 25 + node_modules/lodash/_createBind.js | 28 + node_modules/lodash/_createCaseFirst.js | 33 + node_modules/lodash/_createCompounder.js | 24 + node_modules/lodash/_createCtor.js | 37 + node_modules/lodash/_createCurry.js | 46 + node_modules/lodash/_createFind.js | 25 + node_modules/lodash/_createFlow.js | 78 + node_modules/lodash/_createHybrid.js | 92 + node_modules/lodash/_createInverter.js | 17 + node_modules/lodash/_createMathOperation.js | 38 + node_modules/lodash/_createOver.js | 27 + node_modules/lodash/_createPadding.js | 33 + node_modules/lodash/_createPartial.js | 43 + node_modules/lodash/_createRange.js | 30 + node_modules/lodash/_createRecurry.js | 56 + .../lodash/_createRelationalOperation.js | 20 + node_modules/lodash/_createRound.js | 35 + node_modules/lodash/_createSet.js | 19 + node_modules/lodash/_createToPairs.js | 30 + node_modules/lodash/_createWrap.js | 106 + .../lodash/_customDefaultsAssignIn.js | 29 + node_modules/lodash/_customDefaultsMerge.js | 28 + node_modules/lodash/_customOmitClone.js | 16 + node_modules/lodash/_deburrLetter.js | 71 + node_modules/lodash/_defineProperty.js | 11 + node_modules/lodash/_equalArrays.js | 84 + node_modules/lodash/_equalByTag.js | 112 + node_modules/lodash/_equalObjects.js | 90 + node_modules/lodash/_escapeHtmlChar.js | 21 + node_modules/lodash/_escapeStringChar.js | 22 + node_modules/lodash/_flatRest.js | 16 + node_modules/lodash/_freeGlobal.js | 4 + node_modules/lodash/_getAllKeys.js | 16 + node_modules/lodash/_getAllKeysIn.js | 17 + node_modules/lodash/_getData.js | 15 + node_modules/lodash/_getFuncName.js | 31 + node_modules/lodash/_getHolder.js | 13 + node_modules/lodash/_getMapData.js | 18 + node_modules/lodash/_getMatchData.js | 24 + node_modules/lodash/_getNative.js | 17 + node_modules/lodash/_getPrototype.js | 6 + node_modules/lodash/_getRawTag.js | 46 + node_modules/lodash/_getSymbols.js | 30 + node_modules/lodash/_getSymbolsIn.js | 25 + node_modules/lodash/_getTag.js | 58 + node_modules/lodash/_getValue.js | 13 + node_modules/lodash/_getView.js | 33 + node_modules/lodash/_getWrapDetails.js | 17 + node_modules/lodash/_hasPath.js | 39 + node_modules/lodash/_hasUnicode.js | 26 + node_modules/lodash/_hasUnicodeWord.js | 15 + node_modules/lodash/_hashClear.js | 15 + node_modules/lodash/_hashDelete.js | 17 + node_modules/lodash/_hashGet.js | 30 + node_modules/lodash/_hashHas.js | 23 + node_modules/lodash/_hashSet.js | 23 + node_modules/lodash/_initCloneArray.js | 26 + node_modules/lodash/_initCloneByTag.js | 77 + node_modules/lodash/_initCloneObject.js | 18 + node_modules/lodash/_insertWrapDetails.js | 23 + node_modules/lodash/_isFlattenable.js | 20 + node_modules/lodash/_isIndex.js | 25 + node_modules/lodash/_isIterateeCall.js | 30 + node_modules/lodash/_isKey.js | 29 + node_modules/lodash/_isKeyable.js | 15 + node_modules/lodash/_isLaziable.js | 28 + node_modules/lodash/_isMaskable.js | 14 + node_modules/lodash/_isMasked.js | 20 + node_modules/lodash/_isPrototype.js | 18 + node_modules/lodash/_isStrictComparable.js | 15 + node_modules/lodash/_iteratorToArray.js | 18 + node_modules/lodash/_lazyClone.js | 23 + node_modules/lodash/_lazyReverse.js | 23 + node_modules/lodash/_lazyValue.js | 69 + node_modules/lodash/_listCacheClear.js | 13 + node_modules/lodash/_listCacheDelete.js | 35 + node_modules/lodash/_listCacheGet.js | 19 + node_modules/lodash/_listCacheHas.js | 16 + node_modules/lodash/_listCacheSet.js | 26 + node_modules/lodash/_mapCacheClear.js | 21 + node_modules/lodash/_mapCacheDelete.js | 18 + node_modules/lodash/_mapCacheGet.js | 16 + node_modules/lodash/_mapCacheHas.js | 16 + node_modules/lodash/_mapCacheSet.js | 22 + node_modules/lodash/_mapToArray.js | 18 + .../lodash/_matchesStrictComparable.js | 20 + node_modules/lodash/_memoizeCapped.js | 26 + node_modules/lodash/_mergeData.js | 90 + node_modules/lodash/_metaMap.js | 6 + node_modules/lodash/_nativeCreate.js | 6 + node_modules/lodash/_nativeKeys.js | 6 + node_modules/lodash/_nativeKeysIn.js | 20 + node_modules/lodash/_nodeUtil.js | 30 + node_modules/lodash/_objectToString.js | 22 + node_modules/lodash/_overArg.js | 15 + node_modules/lodash/_overRest.js | 36 + node_modules/lodash/_parent.js | 16 + node_modules/lodash/_reEscape.js | 4 + node_modules/lodash/_reEvaluate.js | 4 + node_modules/lodash/_reInterpolate.js | 4 + node_modules/lodash/_realNames.js | 4 + node_modules/lodash/_reorder.js | 29 + node_modules/lodash/_replaceHolders.js | 29 + node_modules/lodash/_root.js | 9 + node_modules/lodash/_safeGet.js | 21 + node_modules/lodash/_setCacheAdd.js | 19 + node_modules/lodash/_setCacheHas.js | 14 + node_modules/lodash/_setData.js | 20 + node_modules/lodash/_setToArray.js | 18 + node_modules/lodash/_setToPairs.js | 18 + node_modules/lodash/_setToString.js | 14 + node_modules/lodash/_setWrapToString.js | 21 + node_modules/lodash/_shortOut.js | 37 + node_modules/lodash/_shuffleSelf.js | 28 + node_modules/lodash/_stackClear.js | 15 + node_modules/lodash/_stackDelete.js | 18 + node_modules/lodash/_stackGet.js | 14 + node_modules/lodash/_stackHas.js | 14 + node_modules/lodash/_stackSet.js | 34 + node_modules/lodash/_strictIndexOf.js | 23 + node_modules/lodash/_strictLastIndexOf.js | 21 + node_modules/lodash/_stringSize.js | 18 + node_modules/lodash/_stringToArray.js | 18 + node_modules/lodash/_stringToPath.js | 27 + node_modules/lodash/_toKey.js | 21 + node_modules/lodash/_toSource.js | 26 + node_modules/lodash/_trimmedEndIndex.js | 19 + node_modules/lodash/_unescapeHtmlChar.js | 21 + node_modules/lodash/_unicodeSize.js | 44 + node_modules/lodash/_unicodeToArray.js | 40 + node_modules/lodash/_unicodeWords.js | 69 + node_modules/lodash/_updateWrapDetails.js | 46 + node_modules/lodash/_wrapperClone.js | 23 + node_modules/lodash/add.js | 22 + node_modules/lodash/after.js | 42 + node_modules/lodash/array.js | 67 + node_modules/lodash/ary.js | 29 + node_modules/lodash/assign.js | 58 + node_modules/lodash/assignIn.js | 40 + node_modules/lodash/assignInWith.js | 38 + node_modules/lodash/assignWith.js | 37 + node_modules/lodash/at.js | 23 + node_modules/lodash/attempt.js | 35 + node_modules/lodash/before.js | 40 + node_modules/lodash/bind.js | 57 + node_modules/lodash/bindAll.js | 41 + node_modules/lodash/bindKey.js | 68 + node_modules/lodash/camelCase.js | 29 + node_modules/lodash/capitalize.js | 23 + node_modules/lodash/castArray.js | 44 + node_modules/lodash/ceil.js | 26 + node_modules/lodash/chain.js | 38 + node_modules/lodash/chunk.js | 50 + node_modules/lodash/clamp.js | 39 + node_modules/lodash/clone.js | 36 + node_modules/lodash/cloneDeep.js | 29 + node_modules/lodash/cloneDeepWith.js | 40 + node_modules/lodash/cloneWith.js | 42 + node_modules/lodash/collection.js | 30 + node_modules/lodash/commit.js | 33 + node_modules/lodash/compact.js | 31 + node_modules/lodash/concat.js | 43 + node_modules/lodash/cond.js | 60 + node_modules/lodash/conforms.js | 35 + node_modules/lodash/conformsTo.js | 32 + node_modules/lodash/constant.js | 26 + node_modules/lodash/core.js | 3877 +++ node_modules/lodash/core.min.js | 29 + node_modules/lodash/countBy.js | 40 + node_modules/lodash/create.js | 43 + node_modules/lodash/curry.js | 57 + node_modules/lodash/curryRight.js | 54 + node_modules/lodash/date.js | 3 + node_modules/lodash/debounce.js | 191 + node_modules/lodash/deburr.js | 45 + node_modules/lodash/defaultTo.js | 25 + node_modules/lodash/defaults.js | 64 + node_modules/lodash/defaultsDeep.js | 30 + node_modules/lodash/defer.js | 26 + node_modules/lodash/delay.js | 28 + node_modules/lodash/difference.js | 33 + node_modules/lodash/differenceBy.js | 44 + node_modules/lodash/differenceWith.js | 40 + node_modules/lodash/divide.js | 22 + node_modules/lodash/drop.js | 38 + node_modules/lodash/dropRight.js | 39 + node_modules/lodash/dropRightWhile.js | 45 + node_modules/lodash/dropWhile.js | 45 + node_modules/lodash/each.js | 1 + node_modules/lodash/eachRight.js | 1 + node_modules/lodash/endsWith.js | 43 + node_modules/lodash/entries.js | 1 + node_modules/lodash/entriesIn.js | 1 + node_modules/lodash/eq.js | 37 + node_modules/lodash/escape.js | 43 + node_modules/lodash/escapeRegExp.js | 32 + node_modules/lodash/every.js | 56 + node_modules/lodash/extend.js | 1 + node_modules/lodash/extendWith.js | 1 + node_modules/lodash/fill.js | 45 + node_modules/lodash/filter.js | 52 + node_modules/lodash/find.js | 42 + node_modules/lodash/findIndex.js | 55 + node_modules/lodash/findKey.js | 44 + node_modules/lodash/findLast.js | 25 + node_modules/lodash/findLastIndex.js | 59 + node_modules/lodash/findLastKey.js | 44 + node_modules/lodash/first.js | 1 + node_modules/lodash/flake.lock | 40 + node_modules/lodash/flake.nix | 20 + node_modules/lodash/flatMap.js | 29 + node_modules/lodash/flatMapDeep.js | 31 + node_modules/lodash/flatMapDepth.js | 31 + node_modules/lodash/flatten.js | 22 + node_modules/lodash/flattenDeep.js | 25 + node_modules/lodash/flattenDepth.js | 33 + node_modules/lodash/flip.js | 28 + node_modules/lodash/floor.js | 26 + node_modules/lodash/flow.js | 27 + node_modules/lodash/flowRight.js | 26 + node_modules/lodash/forEach.js | 41 + node_modules/lodash/forEachRight.js | 31 + node_modules/lodash/forIn.js | 39 + node_modules/lodash/forInRight.js | 37 + node_modules/lodash/forOwn.js | 36 + node_modules/lodash/forOwnRight.js | 34 + node_modules/lodash/fp.js | 2 + node_modules/lodash/fp/F.js | 1 + node_modules/lodash/fp/T.js | 1 + node_modules/lodash/fp/__.js | 1 + node_modules/lodash/fp/_baseConvert.js | 569 + node_modules/lodash/fp/_convertBrowser.js | 18 + node_modules/lodash/fp/_falseOptions.js | 7 + node_modules/lodash/fp/_mapping.js | 358 + node_modules/lodash/fp/_util.js | 16 + node_modules/lodash/fp/add.js | 5 + node_modules/lodash/fp/after.js | 5 + node_modules/lodash/fp/all.js | 1 + node_modules/lodash/fp/allPass.js | 1 + node_modules/lodash/fp/always.js | 1 + node_modules/lodash/fp/any.js | 1 + node_modules/lodash/fp/anyPass.js | 1 + node_modules/lodash/fp/apply.js | 1 + node_modules/lodash/fp/array.js | 2 + node_modules/lodash/fp/ary.js | 5 + node_modules/lodash/fp/assign.js | 5 + node_modules/lodash/fp/assignAll.js | 5 + node_modules/lodash/fp/assignAllWith.js | 5 + node_modules/lodash/fp/assignIn.js | 5 + node_modules/lodash/fp/assignInAll.js | 5 + node_modules/lodash/fp/assignInAllWith.js | 5 + node_modules/lodash/fp/assignInWith.js | 5 + node_modules/lodash/fp/assignWith.js | 5 + node_modules/lodash/fp/assoc.js | 1 + node_modules/lodash/fp/assocPath.js | 1 + node_modules/lodash/fp/at.js | 5 + node_modules/lodash/fp/attempt.js | 5 + node_modules/lodash/fp/before.js | 5 + node_modules/lodash/fp/bind.js | 5 + node_modules/lodash/fp/bindAll.js | 5 + node_modules/lodash/fp/bindKey.js | 5 + node_modules/lodash/fp/camelCase.js | 5 + node_modules/lodash/fp/capitalize.js | 5 + node_modules/lodash/fp/castArray.js | 5 + node_modules/lodash/fp/ceil.js | 5 + node_modules/lodash/fp/chain.js | 5 + node_modules/lodash/fp/chunk.js | 5 + node_modules/lodash/fp/clamp.js | 5 + node_modules/lodash/fp/clone.js | 5 + node_modules/lodash/fp/cloneDeep.js | 5 + node_modules/lodash/fp/cloneDeepWith.js | 5 + node_modules/lodash/fp/cloneWith.js | 5 + node_modules/lodash/fp/collection.js | 2 + node_modules/lodash/fp/commit.js | 5 + node_modules/lodash/fp/compact.js | 5 + node_modules/lodash/fp/complement.js | 1 + node_modules/lodash/fp/compose.js | 1 + node_modules/lodash/fp/concat.js | 5 + node_modules/lodash/fp/cond.js | 5 + node_modules/lodash/fp/conforms.js | 1 + node_modules/lodash/fp/conformsTo.js | 5 + node_modules/lodash/fp/constant.js | 5 + node_modules/lodash/fp/contains.js | 1 + node_modules/lodash/fp/convert.js | 18 + node_modules/lodash/fp/countBy.js | 5 + node_modules/lodash/fp/create.js | 5 + node_modules/lodash/fp/curry.js | 5 + node_modules/lodash/fp/curryN.js | 5 + node_modules/lodash/fp/curryRight.js | 5 + node_modules/lodash/fp/curryRightN.js | 5 + node_modules/lodash/fp/date.js | 2 + node_modules/lodash/fp/debounce.js | 5 + node_modules/lodash/fp/deburr.js | 5 + node_modules/lodash/fp/defaultTo.js | 5 + node_modules/lodash/fp/defaults.js | 5 + node_modules/lodash/fp/defaultsAll.js | 5 + node_modules/lodash/fp/defaultsDeep.js | 5 + node_modules/lodash/fp/defaultsDeepAll.js | 5 + node_modules/lodash/fp/defer.js | 5 + node_modules/lodash/fp/delay.js | 5 + node_modules/lodash/fp/difference.js | 5 + node_modules/lodash/fp/differenceBy.js | 5 + node_modules/lodash/fp/differenceWith.js | 5 + node_modules/lodash/fp/dissoc.js | 1 + node_modules/lodash/fp/dissocPath.js | 1 + node_modules/lodash/fp/divide.js | 5 + node_modules/lodash/fp/drop.js | 5 + node_modules/lodash/fp/dropLast.js | 1 + node_modules/lodash/fp/dropLastWhile.js | 1 + node_modules/lodash/fp/dropRight.js | 5 + node_modules/lodash/fp/dropRightWhile.js | 5 + node_modules/lodash/fp/dropWhile.js | 5 + node_modules/lodash/fp/each.js | 1 + node_modules/lodash/fp/eachRight.js | 1 + node_modules/lodash/fp/endsWith.js | 5 + node_modules/lodash/fp/entries.js | 1 + node_modules/lodash/fp/entriesIn.js | 1 + node_modules/lodash/fp/eq.js | 5 + node_modules/lodash/fp/equals.js | 1 + node_modules/lodash/fp/escape.js | 5 + node_modules/lodash/fp/escapeRegExp.js | 5 + node_modules/lodash/fp/every.js | 5 + node_modules/lodash/fp/extend.js | 1 + node_modules/lodash/fp/extendAll.js | 1 + node_modules/lodash/fp/extendAllWith.js | 1 + node_modules/lodash/fp/extendWith.js | 1 + node_modules/lodash/fp/fill.js | 5 + node_modules/lodash/fp/filter.js | 5 + node_modules/lodash/fp/find.js | 5 + node_modules/lodash/fp/findFrom.js | 5 + node_modules/lodash/fp/findIndex.js | 5 + node_modules/lodash/fp/findIndexFrom.js | 5 + node_modules/lodash/fp/findKey.js | 5 + node_modules/lodash/fp/findLast.js | 5 + node_modules/lodash/fp/findLastFrom.js | 5 + node_modules/lodash/fp/findLastIndex.js | 5 + node_modules/lodash/fp/findLastIndexFrom.js | 5 + node_modules/lodash/fp/findLastKey.js | 5 + node_modules/lodash/fp/first.js | 1 + node_modules/lodash/fp/flatMap.js | 5 + node_modules/lodash/fp/flatMapDeep.js | 5 + node_modules/lodash/fp/flatMapDepth.js | 5 + node_modules/lodash/fp/flatten.js | 5 + node_modules/lodash/fp/flattenDeep.js | 5 + node_modules/lodash/fp/flattenDepth.js | 5 + node_modules/lodash/fp/flip.js | 5 + node_modules/lodash/fp/floor.js | 5 + node_modules/lodash/fp/flow.js | 5 + node_modules/lodash/fp/flowRight.js | 5 + node_modules/lodash/fp/forEach.js | 5 + node_modules/lodash/fp/forEachRight.js | 5 + node_modules/lodash/fp/forIn.js | 5 + node_modules/lodash/fp/forInRight.js | 5 + node_modules/lodash/fp/forOwn.js | 5 + node_modules/lodash/fp/forOwnRight.js | 5 + node_modules/lodash/fp/fromPairs.js | 5 + node_modules/lodash/fp/function.js | 2 + node_modules/lodash/fp/functions.js | 5 + node_modules/lodash/fp/functionsIn.js | 5 + node_modules/lodash/fp/get.js | 5 + node_modules/lodash/fp/getOr.js | 5 + node_modules/lodash/fp/groupBy.js | 5 + node_modules/lodash/fp/gt.js | 5 + node_modules/lodash/fp/gte.js | 5 + node_modules/lodash/fp/has.js | 5 + node_modules/lodash/fp/hasIn.js | 5 + node_modules/lodash/fp/head.js | 5 + node_modules/lodash/fp/identical.js | 1 + node_modules/lodash/fp/identity.js | 5 + node_modules/lodash/fp/inRange.js | 5 + node_modules/lodash/fp/includes.js | 5 + node_modules/lodash/fp/includesFrom.js | 5 + node_modules/lodash/fp/indexBy.js | 1 + node_modules/lodash/fp/indexOf.js | 5 + node_modules/lodash/fp/indexOfFrom.js | 5 + node_modules/lodash/fp/init.js | 1 + node_modules/lodash/fp/initial.js | 5 + node_modules/lodash/fp/intersection.js | 5 + node_modules/lodash/fp/intersectionBy.js | 5 + node_modules/lodash/fp/intersectionWith.js | 5 + node_modules/lodash/fp/invert.js | 5 + node_modules/lodash/fp/invertBy.js | 5 + node_modules/lodash/fp/invertObj.js | 1 + node_modules/lodash/fp/invoke.js | 5 + node_modules/lodash/fp/invokeArgs.js | 5 + node_modules/lodash/fp/invokeArgsMap.js | 5 + node_modules/lodash/fp/invokeMap.js | 5 + node_modules/lodash/fp/isArguments.js | 5 + node_modules/lodash/fp/isArray.js | 5 + node_modules/lodash/fp/isArrayBuffer.js | 5 + node_modules/lodash/fp/isArrayLike.js | 5 + node_modules/lodash/fp/isArrayLikeObject.js | 5 + node_modules/lodash/fp/isBoolean.js | 5 + node_modules/lodash/fp/isBuffer.js | 5 + node_modules/lodash/fp/isDate.js | 5 + node_modules/lodash/fp/isElement.js | 5 + node_modules/lodash/fp/isEmpty.js | 5 + node_modules/lodash/fp/isEqual.js | 5 + node_modules/lodash/fp/isEqualWith.js | 5 + node_modules/lodash/fp/isError.js | 5 + node_modules/lodash/fp/isFinite.js | 5 + node_modules/lodash/fp/isFunction.js | 5 + node_modules/lodash/fp/isInteger.js | 5 + node_modules/lodash/fp/isLength.js | 5 + node_modules/lodash/fp/isMap.js | 5 + node_modules/lodash/fp/isMatch.js | 5 + node_modules/lodash/fp/isMatchWith.js | 5 + node_modules/lodash/fp/isNaN.js | 5 + node_modules/lodash/fp/isNative.js | 5 + node_modules/lodash/fp/isNil.js | 5 + node_modules/lodash/fp/isNull.js | 5 + node_modules/lodash/fp/isNumber.js | 5 + node_modules/lodash/fp/isObject.js | 5 + node_modules/lodash/fp/isObjectLike.js | 5 + node_modules/lodash/fp/isPlainObject.js | 5 + node_modules/lodash/fp/isRegExp.js | 5 + node_modules/lodash/fp/isSafeInteger.js | 5 + node_modules/lodash/fp/isSet.js | 5 + node_modules/lodash/fp/isString.js | 5 + node_modules/lodash/fp/isSymbol.js | 5 + node_modules/lodash/fp/isTypedArray.js | 5 + node_modules/lodash/fp/isUndefined.js | 5 + node_modules/lodash/fp/isWeakMap.js | 5 + node_modules/lodash/fp/isWeakSet.js | 5 + node_modules/lodash/fp/iteratee.js | 5 + node_modules/lodash/fp/join.js | 5 + node_modules/lodash/fp/juxt.js | 1 + node_modules/lodash/fp/kebabCase.js | 5 + node_modules/lodash/fp/keyBy.js | 5 + node_modules/lodash/fp/keys.js | 5 + node_modules/lodash/fp/keysIn.js | 5 + node_modules/lodash/fp/lang.js | 2 + node_modules/lodash/fp/last.js | 5 + node_modules/lodash/fp/lastIndexOf.js | 5 + node_modules/lodash/fp/lastIndexOfFrom.js | 5 + node_modules/lodash/fp/lowerCase.js | 5 + node_modules/lodash/fp/lowerFirst.js | 5 + node_modules/lodash/fp/lt.js | 5 + node_modules/lodash/fp/lte.js | 5 + node_modules/lodash/fp/map.js | 5 + node_modules/lodash/fp/mapKeys.js | 5 + node_modules/lodash/fp/mapValues.js | 5 + node_modules/lodash/fp/matches.js | 1 + node_modules/lodash/fp/matchesProperty.js | 5 + node_modules/lodash/fp/math.js | 2 + node_modules/lodash/fp/max.js | 5 + node_modules/lodash/fp/maxBy.js | 5 + node_modules/lodash/fp/mean.js | 5 + node_modules/lodash/fp/meanBy.js | 5 + node_modules/lodash/fp/memoize.js | 5 + node_modules/lodash/fp/merge.js | 5 + node_modules/lodash/fp/mergeAll.js | 5 + node_modules/lodash/fp/mergeAllWith.js | 5 + node_modules/lodash/fp/mergeWith.js | 5 + node_modules/lodash/fp/method.js | 5 + node_modules/lodash/fp/methodOf.js | 5 + node_modules/lodash/fp/min.js | 5 + node_modules/lodash/fp/minBy.js | 5 + node_modules/lodash/fp/mixin.js | 5 + node_modules/lodash/fp/multiply.js | 5 + node_modules/lodash/fp/nAry.js | 1 + node_modules/lodash/fp/negate.js | 5 + node_modules/lodash/fp/next.js | 5 + node_modules/lodash/fp/noop.js | 5 + node_modules/lodash/fp/now.js | 5 + node_modules/lodash/fp/nth.js | 5 + node_modules/lodash/fp/nthArg.js | 5 + node_modules/lodash/fp/number.js | 2 + node_modules/lodash/fp/object.js | 2 + node_modules/lodash/fp/omit.js | 5 + node_modules/lodash/fp/omitAll.js | 1 + node_modules/lodash/fp/omitBy.js | 5 + node_modules/lodash/fp/once.js | 5 + node_modules/lodash/fp/orderBy.js | 5 + node_modules/lodash/fp/over.js | 5 + node_modules/lodash/fp/overArgs.js | 5 + node_modules/lodash/fp/overEvery.js | 5 + node_modules/lodash/fp/overSome.js | 5 + node_modules/lodash/fp/pad.js | 5 + node_modules/lodash/fp/padChars.js | 5 + node_modules/lodash/fp/padCharsEnd.js | 5 + node_modules/lodash/fp/padCharsStart.js | 5 + node_modules/lodash/fp/padEnd.js | 5 + node_modules/lodash/fp/padStart.js | 5 + node_modules/lodash/fp/parseInt.js | 5 + node_modules/lodash/fp/partial.js | 5 + node_modules/lodash/fp/partialRight.js | 5 + node_modules/lodash/fp/partition.js | 5 + node_modules/lodash/fp/path.js | 1 + node_modules/lodash/fp/pathEq.js | 1 + node_modules/lodash/fp/pathOr.js | 1 + node_modules/lodash/fp/paths.js | 1 + node_modules/lodash/fp/pick.js | 5 + node_modules/lodash/fp/pickAll.js | 1 + node_modules/lodash/fp/pickBy.js | 5 + node_modules/lodash/fp/pipe.js | 1 + node_modules/lodash/fp/placeholder.js | 6 + node_modules/lodash/fp/plant.js | 5 + node_modules/lodash/fp/pluck.js | 1 + node_modules/lodash/fp/prop.js | 1 + node_modules/lodash/fp/propEq.js | 1 + node_modules/lodash/fp/propOr.js | 1 + node_modules/lodash/fp/property.js | 1 + node_modules/lodash/fp/propertyOf.js | 5 + node_modules/lodash/fp/props.js | 1 + node_modules/lodash/fp/pull.js | 5 + node_modules/lodash/fp/pullAll.js | 5 + node_modules/lodash/fp/pullAllBy.js | 5 + node_modules/lodash/fp/pullAllWith.js | 5 + node_modules/lodash/fp/pullAt.js | 5 + node_modules/lodash/fp/random.js | 5 + node_modules/lodash/fp/range.js | 5 + node_modules/lodash/fp/rangeRight.js | 5 + node_modules/lodash/fp/rangeStep.js | 5 + node_modules/lodash/fp/rangeStepRight.js | 5 + node_modules/lodash/fp/rearg.js | 5 + node_modules/lodash/fp/reduce.js | 5 + node_modules/lodash/fp/reduceRight.js | 5 + node_modules/lodash/fp/reject.js | 5 + node_modules/lodash/fp/remove.js | 5 + node_modules/lodash/fp/repeat.js | 5 + node_modules/lodash/fp/replace.js | 5 + node_modules/lodash/fp/rest.js | 5 + node_modules/lodash/fp/restFrom.js | 5 + node_modules/lodash/fp/result.js | 5 + node_modules/lodash/fp/reverse.js | 5 + node_modules/lodash/fp/round.js | 5 + node_modules/lodash/fp/sample.js | 5 + node_modules/lodash/fp/sampleSize.js | 5 + node_modules/lodash/fp/seq.js | 2 + node_modules/lodash/fp/set.js | 5 + node_modules/lodash/fp/setWith.js | 5 + node_modules/lodash/fp/shuffle.js | 5 + node_modules/lodash/fp/size.js | 5 + node_modules/lodash/fp/slice.js | 5 + node_modules/lodash/fp/snakeCase.js | 5 + node_modules/lodash/fp/some.js | 5 + node_modules/lodash/fp/sortBy.js | 5 + node_modules/lodash/fp/sortedIndex.js | 5 + node_modules/lodash/fp/sortedIndexBy.js | 5 + node_modules/lodash/fp/sortedIndexOf.js | 5 + node_modules/lodash/fp/sortedLastIndex.js | 5 + node_modules/lodash/fp/sortedLastIndexBy.js | 5 + node_modules/lodash/fp/sortedLastIndexOf.js | 5 + node_modules/lodash/fp/sortedUniq.js | 5 + node_modules/lodash/fp/sortedUniqBy.js | 5 + node_modules/lodash/fp/split.js | 5 + node_modules/lodash/fp/spread.js | 5 + node_modules/lodash/fp/spreadFrom.js | 5 + node_modules/lodash/fp/startCase.js | 5 + node_modules/lodash/fp/startsWith.js | 5 + node_modules/lodash/fp/string.js | 2 + node_modules/lodash/fp/stubArray.js | 5 + node_modules/lodash/fp/stubFalse.js | 5 + node_modules/lodash/fp/stubObject.js | 5 + node_modules/lodash/fp/stubString.js | 5 + node_modules/lodash/fp/stubTrue.js | 5 + node_modules/lodash/fp/subtract.js | 5 + node_modules/lodash/fp/sum.js | 5 + node_modules/lodash/fp/sumBy.js | 5 + node_modules/lodash/fp/symmetricDifference.js | 1 + .../lodash/fp/symmetricDifferenceBy.js | 1 + .../lodash/fp/symmetricDifferenceWith.js | 1 + node_modules/lodash/fp/tail.js | 5 + node_modules/lodash/fp/take.js | 5 + node_modules/lodash/fp/takeLast.js | 1 + node_modules/lodash/fp/takeLastWhile.js | 1 + node_modules/lodash/fp/takeRight.js | 5 + node_modules/lodash/fp/takeRightWhile.js | 5 + node_modules/lodash/fp/takeWhile.js | 5 + node_modules/lodash/fp/tap.js | 5 + node_modules/lodash/fp/template.js | 5 + node_modules/lodash/fp/templateSettings.js | 5 + node_modules/lodash/fp/throttle.js | 5 + node_modules/lodash/fp/thru.js | 5 + node_modules/lodash/fp/times.js | 5 + node_modules/lodash/fp/toArray.js | 5 + node_modules/lodash/fp/toFinite.js | 5 + node_modules/lodash/fp/toInteger.js | 5 + node_modules/lodash/fp/toIterator.js | 5 + node_modules/lodash/fp/toJSON.js | 5 + node_modules/lodash/fp/toLength.js | 5 + node_modules/lodash/fp/toLower.js | 5 + node_modules/lodash/fp/toNumber.js | 5 + node_modules/lodash/fp/toPairs.js | 5 + node_modules/lodash/fp/toPairsIn.js | 5 + node_modules/lodash/fp/toPath.js | 5 + node_modules/lodash/fp/toPlainObject.js | 5 + node_modules/lodash/fp/toSafeInteger.js | 5 + node_modules/lodash/fp/toString.js | 5 + node_modules/lodash/fp/toUpper.js | 5 + node_modules/lodash/fp/transform.js | 5 + node_modules/lodash/fp/trim.js | 5 + node_modules/lodash/fp/trimChars.js | 5 + node_modules/lodash/fp/trimCharsEnd.js | 5 + node_modules/lodash/fp/trimCharsStart.js | 5 + node_modules/lodash/fp/trimEnd.js | 5 + node_modules/lodash/fp/trimStart.js | 5 + node_modules/lodash/fp/truncate.js | 5 + node_modules/lodash/fp/unapply.js | 1 + node_modules/lodash/fp/unary.js | 5 + node_modules/lodash/fp/unescape.js | 5 + node_modules/lodash/fp/union.js | 5 + node_modules/lodash/fp/unionBy.js | 5 + node_modules/lodash/fp/unionWith.js | 5 + node_modules/lodash/fp/uniq.js | 5 + node_modules/lodash/fp/uniqBy.js | 5 + node_modules/lodash/fp/uniqWith.js | 5 + node_modules/lodash/fp/uniqueId.js | 5 + node_modules/lodash/fp/unnest.js | 1 + node_modules/lodash/fp/unset.js | 5 + node_modules/lodash/fp/unzip.js | 5 + node_modules/lodash/fp/unzipWith.js | 5 + node_modules/lodash/fp/update.js | 5 + node_modules/lodash/fp/updateWith.js | 5 + node_modules/lodash/fp/upperCase.js | 5 + node_modules/lodash/fp/upperFirst.js | 5 + node_modules/lodash/fp/useWith.js | 1 + node_modules/lodash/fp/util.js | 2 + node_modules/lodash/fp/value.js | 5 + node_modules/lodash/fp/valueOf.js | 5 + node_modules/lodash/fp/values.js | 5 + node_modules/lodash/fp/valuesIn.js | 5 + node_modules/lodash/fp/where.js | 1 + node_modules/lodash/fp/whereEq.js | 1 + node_modules/lodash/fp/without.js | 5 + node_modules/lodash/fp/words.js | 5 + node_modules/lodash/fp/wrap.js | 5 + node_modules/lodash/fp/wrapperAt.js | 5 + node_modules/lodash/fp/wrapperChain.js | 5 + node_modules/lodash/fp/wrapperLodash.js | 5 + node_modules/lodash/fp/wrapperReverse.js | 5 + node_modules/lodash/fp/wrapperValue.js | 5 + node_modules/lodash/fp/xor.js | 5 + node_modules/lodash/fp/xorBy.js | 5 + node_modules/lodash/fp/xorWith.js | 5 + node_modules/lodash/fp/zip.js | 5 + node_modules/lodash/fp/zipAll.js | 5 + node_modules/lodash/fp/zipObj.js | 1 + node_modules/lodash/fp/zipObject.js | 5 + node_modules/lodash/fp/zipObjectDeep.js | 5 + node_modules/lodash/fp/zipWith.js | 5 + node_modules/lodash/fromPairs.js | 28 + node_modules/lodash/function.js | 25 + node_modules/lodash/functions.js | 31 + node_modules/lodash/functionsIn.js | 31 + node_modules/lodash/get.js | 33 + node_modules/lodash/groupBy.js | 41 + node_modules/lodash/gt.js | 29 + node_modules/lodash/gte.js | 30 + node_modules/lodash/has.js | 35 + node_modules/lodash/hasIn.js | 34 + node_modules/lodash/head.js | 23 + node_modules/lodash/identity.js | 21 + node_modules/lodash/inRange.js | 55 + node_modules/lodash/includes.js | 53 + node_modules/lodash/index.js | 1 + node_modules/lodash/indexOf.js | 42 + node_modules/lodash/initial.js | 22 + node_modules/lodash/intersection.js | 30 + node_modules/lodash/intersectionBy.js | 45 + node_modules/lodash/intersectionWith.js | 41 + node_modules/lodash/invert.js | 42 + node_modules/lodash/invertBy.js | 56 + node_modules/lodash/invoke.js | 24 + node_modules/lodash/invokeMap.js | 41 + node_modules/lodash/isArguments.js | 36 + node_modules/lodash/isArray.js | 26 + node_modules/lodash/isArrayBuffer.js | 27 + node_modules/lodash/isArrayLike.js | 33 + node_modules/lodash/isArrayLikeObject.js | 33 + node_modules/lodash/isBoolean.js | 29 + node_modules/lodash/isBuffer.js | 38 + node_modules/lodash/isDate.js | 27 + node_modules/lodash/isElement.js | 25 + node_modules/lodash/isEmpty.js | 77 + node_modules/lodash/isEqual.js | 35 + node_modules/lodash/isEqualWith.js | 41 + node_modules/lodash/isError.js | 36 + node_modules/lodash/isFinite.js | 36 + node_modules/lodash/isFunction.js | 37 + node_modules/lodash/isInteger.js | 33 + node_modules/lodash/isLength.js | 35 + node_modules/lodash/isMap.js | 27 + node_modules/lodash/isMatch.js | 36 + node_modules/lodash/isMatchWith.js | 41 + node_modules/lodash/isNaN.js | 38 + node_modules/lodash/isNative.js | 40 + node_modules/lodash/isNil.js | 25 + node_modules/lodash/isNull.js | 22 + node_modules/lodash/isNumber.js | 38 + node_modules/lodash/isObject.js | 31 + node_modules/lodash/isObjectLike.js | 29 + node_modules/lodash/isPlainObject.js | 62 + node_modules/lodash/isRegExp.js | 27 + node_modules/lodash/isSafeInteger.js | 37 + node_modules/lodash/isSet.js | 27 + node_modules/lodash/isString.js | 30 + node_modules/lodash/isSymbol.js | 29 + node_modules/lodash/isTypedArray.js | 27 + node_modules/lodash/isUndefined.js | 22 + node_modules/lodash/isWeakMap.js | 28 + node_modules/lodash/isWeakSet.js | 28 + node_modules/lodash/iteratee.js | 53 + node_modules/lodash/join.js | 26 + node_modules/lodash/kebabCase.js | 28 + node_modules/lodash/keyBy.js | 36 + node_modules/lodash/keys.js | 37 + node_modules/lodash/keysIn.js | 32 + node_modules/lodash/lang.js | 58 + node_modules/lodash/last.js | 20 + node_modules/lodash/lastIndexOf.js | 46 + node_modules/lodash/lodash.js | 17209 ++++++++++ node_modules/lodash/lodash.min.js | 140 + node_modules/lodash/lowerCase.js | 27 + node_modules/lodash/lowerFirst.js | 22 + node_modules/lodash/lt.js | 29 + node_modules/lodash/lte.js | 30 + node_modules/lodash/map.js | 53 + node_modules/lodash/mapKeys.js | 36 + node_modules/lodash/mapValues.js | 43 + node_modules/lodash/matches.js | 46 + node_modules/lodash/matchesProperty.js | 44 + node_modules/lodash/math.js | 17 + node_modules/lodash/max.js | 29 + node_modules/lodash/maxBy.js | 34 + node_modules/lodash/mean.js | 22 + node_modules/lodash/meanBy.js | 31 + node_modules/lodash/memoize.js | 73 + node_modules/lodash/merge.js | 39 + node_modules/lodash/mergeWith.js | 39 + node_modules/lodash/method.js | 34 + node_modules/lodash/methodOf.js | 33 + node_modules/lodash/min.js | 29 + node_modules/lodash/minBy.js | 34 + node_modules/lodash/mixin.js | 74 + node_modules/lodash/multiply.js | 22 + node_modules/lodash/negate.js | 40 + node_modules/lodash/next.js | 35 + node_modules/lodash/noop.js | 17 + node_modules/lodash/now.js | 23 + node_modules/lodash/nth.js | 29 + node_modules/lodash/nthArg.js | 32 + node_modules/lodash/number.js | 5 + node_modules/lodash/object.js | 49 + node_modules/lodash/omit.js | 57 + node_modules/lodash/omitBy.js | 29 + node_modules/lodash/once.js | 25 + node_modules/lodash/orderBy.js | 47 + node_modules/lodash/over.js | 24 + node_modules/lodash/overArgs.js | 61 + node_modules/lodash/overEvery.js | 34 + node_modules/lodash/overSome.js | 37 + node_modules/lodash/package.json | 17 + node_modules/lodash/pad.js | 49 + node_modules/lodash/padEnd.js | 39 + node_modules/lodash/padStart.js | 39 + node_modules/lodash/parseInt.js | 43 + node_modules/lodash/partial.js | 50 + node_modules/lodash/partialRight.js | 49 + node_modules/lodash/partition.js | 43 + node_modules/lodash/pick.js | 25 + node_modules/lodash/pickBy.js | 37 + node_modules/lodash/plant.js | 48 + node_modules/lodash/property.js | 32 + node_modules/lodash/propertyOf.js | 30 + node_modules/lodash/pull.js | 29 + node_modules/lodash/pullAll.js | 29 + node_modules/lodash/pullAllBy.js | 33 + node_modules/lodash/pullAllWith.js | 32 + node_modules/lodash/pullAt.js | 43 + node_modules/lodash/random.js | 82 + node_modules/lodash/range.js | 46 + node_modules/lodash/rangeRight.js | 41 + node_modules/lodash/rearg.js | 33 + node_modules/lodash/reduce.js | 51 + node_modules/lodash/reduceRight.js | 36 + node_modules/lodash/reject.js | 46 + node_modules/lodash/release.md | 48 + node_modules/lodash/remove.js | 53 + node_modules/lodash/repeat.js | 37 + node_modules/lodash/replace.js | 29 + node_modules/lodash/rest.js | 40 + node_modules/lodash/result.js | 56 + node_modules/lodash/reverse.js | 34 + node_modules/lodash/round.js | 26 + node_modules/lodash/sample.js | 24 + node_modules/lodash/sampleSize.js | 37 + node_modules/lodash/seq.js | 16 + node_modules/lodash/set.js | 35 + node_modules/lodash/setWith.js | 32 + node_modules/lodash/shuffle.js | 25 + node_modules/lodash/size.js | 46 + node_modules/lodash/slice.js | 37 + node_modules/lodash/snakeCase.js | 28 + node_modules/lodash/some.js | 51 + node_modules/lodash/sortBy.js | 48 + node_modules/lodash/sortedIndex.js | 24 + node_modules/lodash/sortedIndexBy.js | 33 + node_modules/lodash/sortedIndexOf.js | 31 + node_modules/lodash/sortedLastIndex.js | 25 + node_modules/lodash/sortedLastIndexBy.js | 33 + node_modules/lodash/sortedLastIndexOf.js | 31 + node_modules/lodash/sortedUniq.js | 24 + node_modules/lodash/sortedUniqBy.js | 26 + node_modules/lodash/split.js | 52 + node_modules/lodash/spread.js | 63 + node_modules/lodash/startCase.js | 29 + node_modules/lodash/startsWith.js | 39 + node_modules/lodash/string.js | 33 + node_modules/lodash/stubArray.js | 23 + node_modules/lodash/stubFalse.js | 18 + node_modules/lodash/stubObject.js | 23 + node_modules/lodash/stubString.js | 18 + node_modules/lodash/stubTrue.js | 18 + node_modules/lodash/subtract.js | 22 + node_modules/lodash/sum.js | 24 + node_modules/lodash/sumBy.js | 33 + node_modules/lodash/tail.js | 22 + node_modules/lodash/take.js | 37 + node_modules/lodash/takeRight.js | 39 + node_modules/lodash/takeRightWhile.js | 45 + node_modules/lodash/takeWhile.js | 45 + node_modules/lodash/tap.js | 29 + node_modules/lodash/template.js | 272 + node_modules/lodash/templateSettings.js | 67 + node_modules/lodash/throttle.js | 69 + node_modules/lodash/thru.js | 28 + node_modules/lodash/times.js | 51 + node_modules/lodash/toArray.js | 58 + node_modules/lodash/toFinite.js | 42 + node_modules/lodash/toInteger.js | 36 + node_modules/lodash/toIterator.js | 23 + node_modules/lodash/toJSON.js | 1 + node_modules/lodash/toLength.js | 38 + node_modules/lodash/toLower.js | 28 + node_modules/lodash/toNumber.js | 64 + node_modules/lodash/toPairs.js | 30 + node_modules/lodash/toPairsIn.js | 30 + node_modules/lodash/toPath.js | 33 + node_modules/lodash/toPlainObject.js | 32 + node_modules/lodash/toSafeInteger.js | 37 + node_modules/lodash/toString.js | 28 + node_modules/lodash/toUpper.js | 28 + node_modules/lodash/transform.js | 65 + node_modules/lodash/trim.js | 47 + node_modules/lodash/trimEnd.js | 41 + node_modules/lodash/trimStart.js | 43 + node_modules/lodash/truncate.js | 111 + node_modules/lodash/unary.js | 22 + node_modules/lodash/unescape.js | 34 + node_modules/lodash/union.js | 26 + node_modules/lodash/unionBy.js | 39 + node_modules/lodash/unionWith.js | 34 + node_modules/lodash/uniq.js | 25 + node_modules/lodash/uniqBy.js | 31 + node_modules/lodash/uniqWith.js | 28 + node_modules/lodash/uniqueId.js | 28 + node_modules/lodash/unset.js | 34 + node_modules/lodash/unzip.js | 45 + node_modules/lodash/unzipWith.js | 39 + node_modules/lodash/update.js | 35 + node_modules/lodash/updateWith.js | 33 + node_modules/lodash/upperCase.js | 27 + node_modules/lodash/upperFirst.js | 22 + node_modules/lodash/util.js | 34 + node_modules/lodash/value.js | 1 + node_modules/lodash/valueOf.js | 1 + node_modules/lodash/values.js | 34 + node_modules/lodash/valuesIn.js | 32 + node_modules/lodash/without.js | 31 + node_modules/lodash/words.js | 35 + node_modules/lodash/wrap.js | 30 + node_modules/lodash/wrapperAt.js | 48 + node_modules/lodash/wrapperChain.js | 34 + node_modules/lodash/wrapperLodash.js | 147 + node_modules/lodash/wrapperReverse.js | 44 + node_modules/lodash/wrapperValue.js | 21 + node_modules/lodash/xor.js | 28 + node_modules/lodash/xorBy.js | 39 + node_modules/lodash/xorWith.js | 34 + node_modules/lodash/zip.js | 22 + node_modules/lodash/zipObject.js | 24 + node_modules/lodash/zipObjectDeep.js | 23 + node_modules/lodash/zipWith.js | 32 + node_modules/log-symbols/browser.js | 8 + node_modules/log-symbols/index.d.ts | 22 + node_modules/log-symbols/index.js | 20 + node_modules/log-symbols/license | 9 + node_modules/log-symbols/package.json | 56 + node_modules/log-symbols/readme.md | 51 + node_modules/loose-envify/LICENSE | 21 + node_modules/loose-envify/README.md | 45 + node_modules/loose-envify/cli.js | 16 + node_modules/loose-envify/custom.js | 4 + node_modules/loose-envify/index.js | 3 + node_modules/loose-envify/loose-envify.js | 36 + node_modules/loose-envify/package.json | 36 + node_modules/loose-envify/replace.js | 65 + node_modules/marked-terminal/LICENSE | 21 + node_modules/marked-terminal/README.md | 140 + node_modules/marked-terminal/index.cjs | 1288 + node_modules/marked-terminal/index.js | 514 + .../node_modules/ansi-escapes/index.d.ts | 243 + .../node_modules/ansi-escapes/index.js | 156 + .../node_modules/ansi-escapes/license | 9 + .../node_modules/ansi-escapes/package.json | 59 + .../node_modules/ansi-escapes/readme.md | 245 + .../node_modules/type-fest/base.d.ts | 42 + .../node_modules/type-fest/index.d.ts | 2 + .../node_modules/type-fest/license | 9 + .../node_modules/type-fest/package.json | 58 + .../node_modules/type-fest/readme.md | 794 + .../type-fest/source/async-return-type.d.ts | 25 + .../type-fest/source/asyncify.d.ts | 33 + .../node_modules/type-fest/source/basic.d.ts | 32 + .../type-fest/source/conditional-except.d.ts | 45 + .../type-fest/source/conditional-keys.d.ts | 45 + .../type-fest/source/conditional-pick.d.ts | 44 + .../type-fest/source/entries.d.ts | 59 + .../node_modules/type-fest/source/entry.d.ts | 62 + .../node_modules/type-fest/source/except.d.ts | 24 + .../type-fest/source/fixed-length-array.d.ts | 40 + .../type-fest/source/iterable-element.d.ts | 48 + .../type-fest/source/literal-union.d.ts | 35 + .../type-fest/source/merge-exclusive.d.ts | 41 + .../node_modules/type-fest/source/merge.d.ts | 27 + .../type-fest/source/mutable.d.ts | 40 + .../type-fest/source/observable-like.d.ts | 15 + .../node_modules/type-fest/source/opaque.d.ts | 67 + .../type-fest/source/package-json.d.ts | 645 + .../type-fest/source/partial-deep.d.ts | 74 + .../type-fest/source/primitive.d.ts | 13 + .../type-fest/source/promisable.d.ts | 25 + .../type-fest/source/promise-value.d.ts | 29 + .../type-fest/source/readonly-deep.d.ts | 61 + .../source/require-at-least-one.d.ts | 35 + .../type-fest/source/require-exactly-one.d.ts | 37 + .../type-fest/source/set-optional.d.ts | 35 + .../type-fest/source/set-required.d.ts | 35 + .../type-fest/source/set-return-type.d.ts | 31 + .../type-fest/source/simplify.d.ts | 24 + .../type-fest/source/stringified.d.ts | 23 + .../type-fest/source/tsconfig-json.d.ts | 1095 + .../type-fest/source/typed-array.d.ts | 19 + .../source/union-to-intersection.d.ts | 60 + .../type-fest/source/utilities.d.ts | 5 + .../type-fest/source/value-of.d.ts | 42 + .../type-fest/ts41/camel-case.d.ts | 72 + .../ts41/camel-cased-properties-deep.d.ts | 50 + .../ts41/camel-cased-properties.d.ts | 32 + .../type-fest/ts41/delimiter-case.d.ts | 88 + .../ts41/delimiter-cased-properties-deep.d.ts | 56 + .../ts41/delimiter-cased-properties.d.ts | 33 + .../node_modules/type-fest/ts41/get.d.ts | 135 + .../node_modules/type-fest/ts41/includes.d.ts | 31 + .../node_modules/type-fest/ts41/index.d.ts | 25 + .../type-fest/ts41/kebab-case.d.ts | 37 + .../ts41/kebab-cased-properties-deep.d.ts | 43 + .../ts41/kebab-cased-properties.d.ts | 26 + .../type-fest/ts41/last-array-element.d.ts | 25 + .../type-fest/ts41/pascal-case.d.ts | 37 + .../ts41/pascal-cased-properties-deep.d.ts | 50 + .../ts41/pascal-cased-properties.d.ts | 30 + .../type-fest/ts41/screaming-snake-case.d.ts | 32 + .../type-fest/ts41/snake-case.d.ts | 37 + .../ts41/snake-cased-properties-deep.d.ts | 43 + .../ts41/snake-cased-properties.d.ts | 26 + .../node_modules/type-fest/ts41/split.d.ts | 28 + .../node_modules/type-fest/ts41/trim.d.ts | 24 + .../type-fest/ts41/utilities.d.ts | 8 + node_modules/marked-terminal/package.json | 65 + node_modules/marked/LICENSE.md | 44 + node_modules/marked/README.md | 99 + node_modules/marked/bin/marked.js | 217 + node_modules/marked/man/marked.1 | 92 + node_modules/marked/man/marked.1.txt | 86 + node_modules/marked/marked.min.js | 6 + node_modules/marked/package.json | 93 + node_modules/marked/src/Lexer.js | 503 + node_modules/marked/src/Parser.js | 286 + node_modules/marked/src/Renderer.js | 203 + node_modules/marked/src/Slugger.js | 55 + node_modules/marked/src/TextRenderer.js | 42 + node_modules/marked/src/Tokenizer.js | 794 + node_modules/marked/src/defaults.js | 29 + node_modules/marked/src/helpers.js | 276 + node_modules/marked/src/marked.js | 366 + node_modules/marked/src/rules.js | 305 + node_modules/match-sorter/CHANGELOG.md | 5 + node_modules/match-sorter/LICENSE | 20 + node_modules/match-sorter/README.md | 543 + node_modules/match-sorter/package.json | 56 + node_modules/microseconds/.prettierrc | 10 + node_modules/microseconds/README.md | 52 + node_modules/microseconds/index.js | 10 + node_modules/microseconds/now.js | 22 + node_modules/microseconds/package.json | 21 + node_modules/microseconds/parse.js | 87 + node_modules/mime-db/HISTORY.md | 507 + node_modules/mime-db/LICENSE | 23 + node_modules/mime-db/README.md | 100 + node_modules/mime-db/db.json | 8519 +++++ node_modules/mime-db/index.js | 12 + node_modules/mime-db/package.json | 60 + node_modules/mime-types/HISTORY.md | 397 + node_modules/mime-types/LICENSE | 23 + node_modules/mime-types/README.md | 113 + node_modules/mime-types/index.js | 188 + node_modules/mime-types/package.json | 44 + node_modules/mimic-fn/index.d.ts | 54 + node_modules/mimic-fn/index.js | 13 + node_modules/mimic-fn/license | 9 + node_modules/mimic-fn/package.json | 42 + node_modules/mimic-fn/readme.md | 69 + node_modules/minimatch/LICENSE | 15 + node_modules/minimatch/README.md | 230 + node_modules/minimatch/minimatch.js | 947 + node_modules/minimatch/package.json | 33 + node_modules/ms/index.js | 162 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 37 + node_modules/ms/readme.md | 60 + node_modules/mute-stream/LICENSE | 15 + node_modules/mute-stream/README.md | 68 + node_modules/mute-stream/mute.js | 145 + node_modules/mute-stream/package.json | 29 + node_modules/mz/HISTORY.md | 66 + node_modules/mz/LICENSE | 22 + node_modules/mz/README.md | 106 + node_modules/mz/child_process.js | 8 + node_modules/mz/crypto.js | 9 + node_modules/mz/dns.js | 16 + node_modules/mz/fs.js | 62 + node_modules/mz/index.js | 8 + node_modules/mz/package.json | 44 + node_modules/mz/readline.js | 64 + node_modules/mz/zlib.js | 13 + node_modules/nano-time/.npmignore | 2 + node_modules/nano-time/README.md | 17 + node_modules/nano-time/index.js | 18 + node_modules/nano-time/package.json | 30 + node_modules/node-emoji/.github/FUNDING.yml | 1 + node_modules/node-emoji/.travis.yml | 3 + node_modules/node-emoji/LICENSE | 21 + node_modules/node-emoji/README.md | 86 + node_modules/node-emoji/index.js | 1 + node_modules/node-emoji/package.json | 42 + node_modules/node-emoji/test/emoji.js | 308 + node_modules/object-assign/index.js | 90 + node_modules/object-assign/license | 21 + node_modules/object-assign/package.json | 42 + node_modules/object-assign/readme.md | 61 + .../oblivious-set/.github/workflows/main.yml | 16 + node_modules/oblivious-set/LICENSE | 21 + node_modules/oblivious-set/README.md | 30 + node_modules/oblivious-set/package.json | 36 + node_modules/oblivious-set/src/index.ts | 74 + node_modules/oblivious-set/test/unit.test.ts | 52 + node_modules/oblivious-set/tsconfig.json | 38 + node_modules/oblivious-set/tslint.json | 116 + node_modules/once/LICENSE | 15 + node_modules/once/README.md | 79 + node_modules/once/once.js | 42 + node_modules/once/package.json | 33 + node_modules/onetime/index.d.ts | 64 + node_modules/onetime/index.js | 44 + node_modules/onetime/license | 9 + node_modules/onetime/package.json | 43 + node_modules/onetime/readme.md | 94 + node_modules/ora/index.d.ts | 308 + node_modules/ora/index.js | 386 + node_modules/ora/license | 9 + .../ora/node_modules/cli-cursor/index.d.ts | 47 + .../ora/node_modules/cli-cursor/index.js | 39 + .../ora/node_modules/cli-cursor/license | 9 + .../ora/node_modules/cli-cursor/package.json | 49 + .../ora/node_modules/cli-cursor/readme.md | 51 + .../node_modules/restore-cursor/index.d.ts | 11 + .../ora/node_modules/restore-cursor/index.js | 11 + .../ora/node_modules/restore-cursor/license | 9 + .../node_modules/restore-cursor/package.json | 55 + .../ora/node_modules/restore-cursor/readme.md | 31 + node_modules/ora/package.json | 61 + node_modules/ora/readme.md | 300 + node_modules/ora/utilities.js | 85 + node_modules/os-tmpdir/index.js | 25 + node_modules/os-tmpdir/license | 21 + node_modules/os-tmpdir/package.json | 41 + node_modules/os-tmpdir/readme.md | 32 + .../parse5-htmlparser2-tree-adapter/LICENSE | 19 + .../parse5-htmlparser2-tree-adapter/README.md | 34 + .../node_modules/parse5/LICENSE | 19 + .../node_modules/parse5/README.md | 38 + .../node_modules/parse5/package.json | 35 + .../package.json | 27 + node_modules/parse5/LICENSE | 19 + node_modules/parse5/README.md | 38 + node_modules/parse5/package.json | 35 + node_modules/patch-console/package.json | 56 + node_modules/patch-console/readme.md | 62 + node_modules/path-is-absolute/index.js | 20 + node_modules/path-is-absolute/license | 21 + node_modules/path-is-absolute/package.json | 43 + node_modules/path-is-absolute/readme.md | 59 + node_modules/prop-types/LICENSE | 21 + node_modules/prop-types/README.md | 302 + node_modules/prop-types/checkPropTypes.js | 103 + node_modules/prop-types/factory.js | 19 + .../prop-types/factoryWithThrowingShims.js | 65 + .../prop-types/factoryWithTypeCheckers.js | 610 + node_modules/prop-types/index.js | 19 + node_modules/prop-types/package.json | 60 + node_modules/prop-types/prop-types.js | 1315 + node_modules/prop-types/prop-types.min.js | 1 + node_modules/proxy-from-env/.eslintrc | 29 + node_modules/proxy-from-env/.travis.yml | 10 + node_modules/proxy-from-env/LICENSE | 20 + node_modules/proxy-from-env/README.md | 131 + node_modules/proxy-from-env/index.js | 108 + node_modules/proxy-from-env/package.json | 34 + node_modules/proxy-from-env/test.js | 483 + node_modules/radash/LICENSE.md | 27 + node_modules/radash/README.md | 73 + node_modules/radash/package.json | 51 + node_modules/react-devtools-core/README.md | 131 + node_modules/react-devtools-core/backend.js | 1 + node_modules/react-devtools-core/package.json | 34 + .../react-devtools-core/standalone.js | 1 + node_modules/react-dom/LICENSE | 21 + node_modules/react-dom/README.md | 54 + node_modules/react-dom/build-info.json | 8 + .../react-dom-server.browser.development.js | 4342 +++ ...react-dom-server.browser.production.min.js | 51 + .../cjs/react-dom-server.node.development.js | 4383 +++ .../react-dom-server.node.production.min.js | 52 + .../cjs/react-dom-test-utils.development.js | 2118 ++ .../react-dom-test-utils.production.min.js | 43 + .../react-dom/cjs/react-dom.development.js | 26262 +++++++++++++++ .../react-dom/cjs/react-dom.production.min.js | 297 + .../react-dom/cjs/react-dom.profiling.min.js | 310 + node_modules/react-dom/index.js | 38 + node_modules/react-dom/package.json | 49 + node_modules/react-dom/profiling.js | 38 + node_modules/react-dom/server.browser.js | 7 + node_modules/react-dom/server.js | 3 + node_modules/react-dom/server.node.js | 7 + node_modules/react-dom/test-utils.js | 7 + .../react-dom-server.browser.development.js | 4341 +++ ...react-dom-server.browser.production.min.js | 46 + .../umd/react-dom-test-utils.development.js | 2136 ++ .../react-dom-test-utils.production.min.js | 35 + .../react-dom/umd/react-dom.development.js | 26292 ++++++++++++++++ .../react-dom/umd/react-dom.production.min.js | 245 + .../react-dom/umd/react-dom.profiling.min.js | 252 + node_modules/react-is/LICENSE | 21 + node_modules/react-is/README.md | 104 + node_modules/react-is/build-info.json | 8 + .../react-is/cjs/react-is.development.js | 181 + .../react-is/cjs/react-is.production.min.js | 15 + node_modules/react-is/index.js | 7 + node_modules/react-is/package.json | 27 + .../react-is/umd/react-is.development.js | 181 + .../react-is/umd/react-is.production.min.js | 13 + node_modules/react-query/LICENSE | 21 + node_modules/react-query/README.md | 11 + .../package.json | 6 + node_modules/react-query/core/package.json | 6 + .../package.json | 6 + .../package.json | 6 + .../devtools/development/package.json | 6 + node_modules/react-query/devtools/index.js | 12 + .../react-query/devtools/package.json | 6 + .../index.js | 80 + .../react-query/es/core/focusManager.js | 95 + node_modules/react-query/es/core/hydration.js | 97 + node_modules/react-query/es/core/index.js | 17 + .../es/core/infiniteQueryBehavior.js | 153 + .../es/core/infiniteQueryObserver.js | 86 + node_modules/react-query/es/core/logger.js | 9 + node_modules/react-query/es/core/mutation.js | 232 + .../react-query/es/core/mutationCache.js | 111 + .../react-query/es/core/mutationObserver.js | 126 + .../react-query/es/core/notifyManager.js | 105 + .../react-query/es/core/onlineManager.js | 94 + .../react-query/es/core/queriesObserver.js | 202 + node_modules/react-query/es/core/query.js | 500 + .../react-query/es/core/queryCache.js | 147 + .../react-query/es/core/queryClient.js | 350 + .../react-query/es/core/queryObserver.js | 549 + node_modules/react-query/es/core/retryer.js | 157 + .../react-query/es/core/subscribable.js | 37 + node_modules/react-query/es/core/types.js | 0 node_modules/react-query/es/core/utils.js | 332 + .../index.js | 124 + .../index.js | 114 + .../react-query/es/devtools/Explorer.js | 208 + node_modules/react-query/es/devtools/Logo.js | 28 + .../react-query/es/devtools/devtools.js | 693 + node_modules/react-query/es/devtools/index.js | 1 + .../es/devtools/styledComponents.js | 100 + node_modules/react-query/es/devtools/theme.js | 28 + .../es/devtools/useLocalStorage.js | 47 + .../react-query/es/devtools/useMediaQuery.js | 36 + node_modules/react-query/es/devtools/utils.js | 91 + .../react-query/es/hydration/index.js | 5 + node_modules/react-query/es/index.js | 2 + .../persistQueryClient-experimental/index.js | 107 + node_modules/react-query/es/react/Hydrate.js | 24 + .../es/react/QueryClientProvider.js | 48 + .../es/react/QueryErrorResetBoundary.js | 32 + node_modules/react-query/es/react/index.js | 14 + node_modules/react-query/es/react/logger.js | 1 + .../react-query/es/react/logger.native.js | 5 + .../es/react/reactBatchedUpdates.js | 2 + .../es/react/reactBatchedUpdates.native.js | 4 + .../react-query/es/react/setBatchUpdatesFn.js | 3 + .../react-query/es/react/setLogger.js | 3 + node_modules/react-query/es/react/types.js | 0 .../react-query/es/react/useBaseQuery.js | 106 + .../react-query/es/react/useInfiniteQuery.js | 8 + .../react-query/es/react/useIsFetching.js | 43 + .../react-query/es/react/useIsMutating.js | 35 + .../react-query/es/react/useMutation.js | 52 + .../react-query/es/react/useQueries.js | 49 + node_modules/react-query/es/react/useQuery.js | 8 + node_modules/react-query/es/react/utils.js | 11 + node_modules/react-query/es/ts3.8/index.js | 3 + .../react-query/es/ts3.8/useQueries.js | 0 .../react-query/hydration/package.json | 6 + node_modules/react-query/package.json | 157 + .../package.json | 6 + node_modules/react-query/react/package.json | 6 + .../index.d.ts | 7 + .../react-query/types/core/focusManager.d.ts | 16 + .../react-query/types/core/hydration.d.ts | 34 + .../react-query/types/core/index.d.ts | 20 + .../types/core/infiniteQueryBehavior.d.ts | 15 + .../types/core/infiniteQueryObserver.d.ts | 18 + .../react-query/types/core/logger.d.ts | 9 + .../react-query/types/core/mutation.d.ts | 67 + .../react-query/types/core/mutationCache.d.ts | 29 + .../types/core/mutationObserver.d.ts | 23 + .../react-query/types/core/notifyManager.d.ts | 29 + .../react-query/types/core/onlineManager.d.ts | 16 + .../types/core/queriesObserver.d.ts | 25 + .../react-query/types/core/query.d.ts | 120 + .../react-query/types/core/queryCache.d.ts | 59 + .../react-query/types/core/queryClient.d.ts | 65 + .../react-query/types/core/queryObserver.d.ts | 64 + .../react-query/types/core/retryer.d.ts | 40 + .../react-query/types/core/subscribable.d.ts | 10 + .../react-query/types/core/types.d.ts | 445 + .../react-query/types/core/utils.d.ts | 107 + .../index.d.ts | 27 + .../index.d.ts | 22 + .../react-query/types/devtools/Explorer.d.ts | 48 + .../react-query/types/devtools/Logo.d.ts | 1 + .../react-query/types/devtools/devtools.d.ts | 63 + .../react-query/types/devtools/index.d.ts | 1 + .../types/devtools/styledComponents.d.ts | 8 + .../react-query/types/devtools/theme.d.ts | 34 + .../types/devtools/useLocalStorage.d.ts | 1 + .../types/devtools/useMediaQuery.d.ts | 1 + .../react-query/types/devtools/utils.d.ts | 22 + .../react-query/types/hydration/index.d.ts | 3 + node_modules/react-query/types/index.d.ts | 2 + .../index.d.ts | 32 + .../react-query/types/react/Hydrate.d.ts | 9 + .../types/react/QueryClientProvider.d.ts | 14 + .../types/react/QueryErrorResetBoundary.d.ts | 12 + .../react-query/types/react/index.d.ts | 16 + .../react-query/types/react/logger.d.ts | 2 + .../types/react/reactBatchedUpdates.d.ts | 2 + .../types/react/setBatchUpdatesFn.d.ts | 1 + .../react-query/types/react/setLogger.d.ts | 1 + .../react-query/types/react/types.d.ts | 24 + .../react-query/types/react/useBaseQuery.d.ts | 4 + .../types/react/useInfiniteQuery.d.ts | 5 + .../types/react/useIsFetching.d.ts | 4 + .../types/react/useIsMutating.d.ts | 4 + .../react-query/types/react/useMutation.d.ts | 6 + .../react-query/types/react/useQueries.d.ts | 45 + .../react-query/types/react/useQuery.d.ts | 5 + .../react-query/types/react/utils.d.ts | 1 + .../react-query/types/ts3.8/index.d.ts | 3 + .../react-query/types/ts3.8/useQueries.d.ts | 5 + node_modules/react-reconciler/LICENSE | 21 + node_modules/react-reconciler/README.md | 64 + node_modules/react-reconciler/build-info.json | 8 + ...react-reconciler-reflection.development.js | 603 + ...ct-reconciler-reflection.production.min.js | 15 + .../cjs/react-reconciler.development.js | 18644 +++++++++++ .../cjs/react-reconciler.production.min.js | 216 + .../cjs/react-reconciler.profiling.min.js | 224 + node_modules/react-reconciler/index.js | 7 + node_modules/react-reconciler/package.json | 41 + node_modules/react-reconciler/reflection.js | 7 + node_modules/react/LICENSE | 21 + node_modules/react/README.md | 13 + node_modules/react/build-info.json | 8 + .../cjs/react-jsx-dev-runtime.development.js | 1203 + .../react-jsx-dev-runtime.production.min.js | 9 + .../react-jsx-dev-runtime.profiling.min.js | 9 + .../cjs/react-jsx-runtime.development.js | 1221 + .../cjs/react-jsx-runtime.production.min.js | 10 + .../cjs/react-jsx-runtime.profiling.min.js | 10 + node_modules/react/cjs/react.development.js | 2333 ++ .../react/cjs/react.production.min.js | 23 + node_modules/react/index.js | 7 + node_modules/react/jsx-dev-runtime.js | 7 + node_modules/react/jsx-runtime.js | 7 + node_modules/react/package.json | 39 + node_modules/react/umd/react.development.js | 3357 ++ .../react/umd/react.production.min.js | 31 + node_modules/react/umd/react.profiling.min.js | 36 + node_modules/readable-stream/CONTRIBUTING.md | 38 + node_modules/readable-stream/GOVERNANCE.md | 136 + node_modules/readable-stream/LICENSE | 47 + node_modules/readable-stream/README.md | 106 + .../readable-stream/errors-browser.js | 127 + node_modules/readable-stream/errors.js | 116 + .../readable-stream/experimentalWarning.js | 17 + node_modules/readable-stream/package.json | 68 + .../readable-stream/readable-browser.js | 9 + node_modules/readable-stream/readable.js | 16 + node_modules/redeyed/.npmignore | 15 + node_modules/redeyed/.travis.yml | 8 + node_modules/redeyed/LICENSE | 23 + node_modules/redeyed/README.md | 206 + node_modules/redeyed/config-es5.js | 140 + node_modules/redeyed/config.js | 195 + .../redeyed/examples/browser/index.css | 31 + .../redeyed/examples/browser/index.html | 35 + .../redeyed/examples/browser/index.js | 32 + .../redeyed/examples/browser/sample-config.js | 131 + node_modules/redeyed/examples/replace-log.js | 58 + node_modules/redeyed/examples/sources/log.js | 8 + node_modules/redeyed/package.json | 36 + node_modules/redeyed/redeyed.js | 313 + .../test/redeyed-before-after-config.js | 54 + node_modules/redeyed/test/redeyed-comments.js | 72 + .../test/redeyed-config-with-undefineds.js | 59 + .../redeyed-function-config-extra-params.js | 53 + ...redeyed-function-config-skipping-tokens.js | 78 + .../redeyed/test/redeyed-function-config.js | 146 + .../redeyed/test/redeyed-incomplete.js | 37 + node_modules/redeyed/test/redeyed-jsx.js | 39 + node_modules/redeyed/test/redeyed-keywords.js | 44 + node_modules/redeyed/test/redeyed-mixed.js | 47 + node_modules/redeyed/test/redeyed-result.js | 56 + .../test/redeyed-script-level-return.js | 22 + node_modules/redeyed/test/redeyed-shebang.js | 25 + node_modules/redeyed/test/redeyed-smoke.js | 38 + .../redeyed/test/redeyed-string-config.js | 125 + node_modules/redeyed/test/redeyed-types.js | 78 + node_modules/redeyed/test/redeyed-upcoming.js | 45 + node_modules/regenerator-runtime/LICENSE | 21 + node_modules/regenerator-runtime/README.md | 31 + node_modules/regenerator-runtime/package.json | 19 + node_modules/regenerator-runtime/path.js | 11 + node_modules/regenerator-runtime/runtime.js | 761 + node_modules/remove-accents/.npmignore | 27 + node_modules/remove-accents/.travis.yml | 7 + node_modules/remove-accents/LICENSE | 22 + node_modules/remove-accents/README.md | 63 + node_modules/remove-accents/index.d.ts | 8 + node_modules/remove-accents/index.js | 419 + node_modules/remove-accents/package.json | 48 + node_modules/remove-accents/test.js | 40 + node_modules/require-directory/.jshintrc | 67 + node_modules/require-directory/.npmignore | 1 + node_modules/require-directory/.travis.yml | 3 + node_modules/require-directory/LICENSE | 22 + .../require-directory/README.markdown | 184 + node_modules/require-directory/index.js | 86 + node_modules/require-directory/package.json | 40 + node_modules/restore-cursor/index.d.ts | 13 + node_modules/restore-cursor/index.js | 9 + node_modules/restore-cursor/license | 9 + node_modules/restore-cursor/package.json | 52 + node_modules/restore-cursor/readme.md | 26 + node_modules/rimraf/CHANGELOG.md | 65 + node_modules/rimraf/LICENSE | 15 + node_modules/rimraf/README.md | 101 + node_modules/rimraf/bin.js | 68 + node_modules/rimraf/package.json | 32 + node_modules/rimraf/rimraf.js | 360 + node_modules/run-async/LICENSE | 21 + node_modules/run-async/README.md | 79 + node_modules/run-async/index.js | 98 + node_modules/run-async/package.json | 27 + node_modules/rxjs/CHANGELOG.md | 2735 ++ node_modules/rxjs/CODE_OF_CONDUCT.md | 73 + node_modules/rxjs/LICENSE.txt | 202 + node_modules/rxjs/README.md | 107 + node_modules/rxjs/ajax/package.json | 8 + node_modules/rxjs/fetch/package.json | 8 + node_modules/rxjs/operators/package.json | 8 + node_modules/rxjs/package.json | 245 + node_modules/rxjs/src/Rx.global.js | 5 + node_modules/rxjs/src/ajax/index.ts | 4 + node_modules/rxjs/src/fetch/index.ts | 1 + node_modules/rxjs/src/index.ts | 209 + node_modules/rxjs/src/internal/AnyCatcher.ts | 14 + .../rxjs/src/internal/AsyncSubject.ts | 41 + .../rxjs/src/internal/BehaviorSubject.ts | 39 + .../rxjs/src/internal/Notification.ts | 243 + .../src/internal/NotificationFactories.ts | 40 + node_modules/rxjs/src/internal/Observable.ts | 498 + node_modules/rxjs/src/internal/Operator.ts | 9 + .../rxjs/src/internal/ReplaySubject.ts | 110 + node_modules/rxjs/src/internal/Scheduler.ts | 62 + node_modules/rxjs/src/internal/Subject.ts | 189 + node_modules/rxjs/src/internal/Subscriber.ts | 276 + .../rxjs/src/internal/Subscription.ts | 216 + .../rxjs/src/internal/ajax/AjaxResponse.ts | 124 + node_modules/rxjs/src/internal/ajax/ajax.ts | 622 + node_modules/rxjs/src/internal/ajax/errors.ts | 106 + .../rxjs/src/internal/ajax/getXHRResponse.ts | 37 + node_modules/rxjs/src/internal/ajax/types.ts | 235 + node_modules/rxjs/src/internal/config.ts | 84 + .../rxjs/src/internal/firstValueFrom.ts | 75 + .../rxjs/src/internal/lastValueFrom.ts | 76 + .../observable/ConnectableObservable.ts | 104 + .../src/internal/observable/bindCallback.ts | 145 + .../observable/bindCallbackInternals.ts | 119 + .../internal/observable/bindNodeCallback.ts | 128 + .../src/internal/observable/combineLatest.ts | 304 + .../rxjs/src/internal/observable/concat.ts | 115 + .../src/internal/observable/connectable.ts | 64 + .../rxjs/src/internal/observable/defer.ts | 57 + .../observable/dom/WebSocketSubject.ts | 397 + .../observable/dom/animationFrames.ts | 132 + .../rxjs/src/internal/observable/dom/fetch.ts | 180 + .../src/internal/observable/dom/webSocket.ts | 162 + .../rxjs/src/internal/observable/empty.ts | 79 + .../rxjs/src/internal/observable/forkJoin.ts | 186 + .../rxjs/src/internal/observable/from.ts | 104 + .../rxjs/src/internal/observable/fromEvent.ts | 332 + .../internal/observable/fromEventPattern.ts | 155 + .../internal/observable/fromSubscribable.ts | 17 + .../rxjs/src/internal/observable/generate.ts | 384 + .../rxjs/src/internal/observable/iif.ts | 85 + .../rxjs/src/internal/observable/innerFrom.ts | 132 + .../rxjs/src/internal/observable/interval.ts | 58 + .../rxjs/src/internal/observable/merge.ts | 102 + .../rxjs/src/internal/observable/never.ts | 44 + .../rxjs/src/internal/observable/of.ts | 83 + .../internal/observable/onErrorResumeNext.ts | 101 + .../rxjs/src/internal/observable/pairs.ts | 82 + .../rxjs/src/internal/observable/partition.ts | 88 + .../rxjs/src/internal/observable/race.ts | 88 + .../rxjs/src/internal/observable/range.ts | 94 + .../src/internal/observable/throwError.ts | 125 + .../rxjs/src/internal/observable/timer.ts | 186 + .../rxjs/src/internal/observable/using.ts | 51 + .../rxjs/src/internal/observable/zip.ts | 115 + .../internal/operators/OperatorSubscriber.ts | 112 + .../rxjs/src/internal/operators/audit.ts | 96 + .../rxjs/src/internal/operators/auditTime.ts | 55 + .../rxjs/src/internal/operators/buffer.ts | 81 + .../src/internal/operators/bufferCount.ts | 120 + .../rxjs/src/internal/operators/bufferTime.ts | 168 + .../src/internal/operators/bufferToggle.ts | 102 + .../rxjs/src/internal/operators/bufferWhen.ts | 94 + .../rxjs/src/internal/operators/catchError.ts | 141 + .../rxjs/src/internal/operators/combineAll.ts | 6 + .../src/internal/operators/combineLatest.ts | 34 + .../internal/operators/combineLatestAll.ts | 50 + .../internal/operators/combineLatestWith.ts | 48 + .../rxjs/src/internal/operators/concat.ts | 22 + .../rxjs/src/internal/operators/concatAll.ts | 62 + .../rxjs/src/internal/operators/concatMap.ts | 84 + .../src/internal/operators/concatMapTo.ts | 79 + .../rxjs/src/internal/operators/concatWith.ts | 48 + .../rxjs/src/internal/operators/connect.ts | 109 + .../rxjs/src/internal/operators/count.ts | 61 + .../rxjs/src/internal/operators/debounce.ts | 119 + .../src/internal/operators/debounceTime.ts | 124 + .../src/internal/operators/defaultIfEmpty.ts | 59 + .../rxjs/src/internal/operators/delay.ts | 65 + .../rxjs/src/internal/operators/delayWhen.ts | 103 + .../src/internal/operators/dematerialize.ts | 58 + .../rxjs/src/internal/operators/distinct.ts | 79 + .../operators/distinctUntilChanged.ts | 182 + .../operators/distinctUntilKeyChanged.ts | 71 + .../rxjs/src/internal/operators/elementAt.ts | 68 + .../rxjs/src/internal/operators/endWith.ts | 68 + .../rxjs/src/internal/operators/every.ts | 66 + .../rxjs/src/internal/operators/exhaust.ts | 6 + .../rxjs/src/internal/operators/exhaustAll.ts | 51 + .../rxjs/src/internal/operators/exhaustMap.ts | 101 + .../rxjs/src/internal/operators/expand.ts | 96 + .../rxjs/src/internal/operators/filter.ts | 75 + .../rxjs/src/internal/operators/finalize.ts | 75 + .../rxjs/src/internal/operators/find.ts | 97 + .../rxjs/src/internal/operators/findIndex.ts | 64 + .../rxjs/src/internal/operators/first.ts | 92 + .../rxjs/src/internal/operators/flatMap.ts | 6 + .../rxjs/src/internal/operators/groupBy.ts | 288 + .../src/internal/operators/ignoreElements.ts | 45 + .../rxjs/src/internal/operators/isEmpty.ts | 82 + .../internal/operators/joinAllInternals.ts | 29 + .../rxjs/src/internal/operators/last.ts | 90 + .../rxjs/src/internal/operators/map.ts | 62 + .../rxjs/src/internal/operators/mapTo.ts | 48 + .../src/internal/operators/materialize.ts | 73 + .../rxjs/src/internal/operators/max.ts | 53 + .../rxjs/src/internal/operators/merge.ts | 31 + .../rxjs/src/internal/operators/mergeAll.ts | 66 + .../src/internal/operators/mergeInternals.ts | 149 + .../rxjs/src/internal/operators/mergeMap.ts | 96 + .../rxjs/src/internal/operators/mergeMapTo.ts | 74 + .../rxjs/src/internal/operators/mergeScan.ts | 93 + .../rxjs/src/internal/operators/mergeWith.ts | 49 + .../rxjs/src/internal/operators/min.ts | 53 + .../rxjs/src/internal/operators/multicast.ts | 98 + .../rxjs/src/internal/operators/observeOn.ts | 70 + .../operators/onErrorResumeNextWith.ts | 99 + .../rxjs/src/internal/operators/pairwise.ts | 61 + .../rxjs/src/internal/operators/partition.ts | 63 + .../rxjs/src/internal/operators/pluck.ts | 106 + .../rxjs/src/internal/operators/publish.ts | 93 + .../src/internal/operators/publishBehavior.ts | 26 + .../src/internal/operators/publishLast.ts | 76 + .../src/internal/operators/publishReplay.ts | 96 + .../rxjs/src/internal/operators/race.ts | 20 + .../rxjs/src/internal/operators/raceWith.ts | 40 + .../rxjs/src/internal/operators/reduce.ts | 62 + .../rxjs/src/internal/operators/refCount.ts | 119 + .../rxjs/src/internal/operators/repeat.ts | 172 + .../rxjs/src/internal/operators/repeatWhen.ts | 125 + .../rxjs/src/internal/operators/retry.ts | 167 + .../rxjs/src/internal/operators/retryWhen.ts | 113 + .../rxjs/src/internal/operators/sample.ts | 72 + .../rxjs/src/internal/operators/sampleTime.ts | 51 + .../rxjs/src/internal/operators/scan.ts | 95 + .../src/internal/operators/scanInternals.ts | 62 + .../src/internal/operators/sequenceEqual.ts | 146 + .../rxjs/src/internal/operators/share.ts | 267 + .../src/internal/operators/shareReplay.ts | 173 + .../rxjs/src/internal/operators/single.ts | 117 + .../rxjs/src/internal/operators/skip.ts | 39 + .../rxjs/src/internal/operators/skipLast.ts | 95 + .../rxjs/src/internal/operators/skipUntil.ts | 69 + .../rxjs/src/internal/operators/skipWhile.ts | 60 + .../rxjs/src/internal/operators/startWith.ts | 67 + .../src/internal/operators/subscribeOn.ts | 67 + .../rxjs/src/internal/operators/switchAll.ts | 65 + .../rxjs/src/internal/operators/switchMap.ts | 133 + .../src/internal/operators/switchMapTo.ts | 64 + .../rxjs/src/internal/operators/switchScan.ts | 50 + .../rxjs/src/internal/operators/take.ts | 71 + .../rxjs/src/internal/operators/takeLast.ts | 81 + .../rxjs/src/internal/operators/takeUntil.ts | 51 + .../rxjs/src/internal/operators/takeWhile.ts | 66 + .../rxjs/src/internal/operators/tap.ts | 153 + .../rxjs/src/internal/operators/throttle.ts | 126 + .../src/internal/operators/throttleTime.ts | 62 + .../src/internal/operators/throwIfEmpty.ts | 60 + .../src/internal/operators/timeInterval.ts | 67 + .../rxjs/src/internal/operators/timeout.ts | 405 + .../src/internal/operators/timeoutWith.ts | 116 + .../rxjs/src/internal/operators/timestamp.ts | 39 + .../rxjs/src/internal/operators/toArray.ts | 44 + .../rxjs/src/internal/operators/window.ts | 98 + .../src/internal/operators/windowCount.ts | 130 + .../rxjs/src/internal/operators/windowTime.ts | 207 + .../src/internal/operators/windowToggle.ts | 134 + .../rxjs/src/internal/operators/windowWhen.ts | 124 + .../src/internal/operators/withLatestFrom.ts | 110 + .../rxjs/src/internal/operators/zip.ts | 26 + .../rxjs/src/internal/operators/zipAll.ts | 20 + .../rxjs/src/internal/operators/zipWith.ts | 29 + .../src/internal/scheduled/scheduleArray.ts | 27 + .../scheduled/scheduleAsyncIterable.ts | 31 + .../internal/scheduled/scheduleIterable.ts | 60 + .../internal/scheduled/scheduleObservable.ts | 8 + .../src/internal/scheduled/schedulePromise.ts | 8 + .../scheduled/scheduleReadableStreamLike.ts | 8 + .../rxjs/src/internal/scheduled/scheduled.ts | 50 + .../rxjs/src/internal/scheduler/Action.ts | 36 + .../scheduler/AnimationFrameAction.ts | 43 + .../scheduler/AnimationFrameScheduler.ts | 38 + .../rxjs/src/internal/scheduler/AsapAction.ts | 43 + .../src/internal/scheduler/AsapScheduler.ts | 38 + .../src/internal/scheduler/AsyncAction.ts | 151 + .../src/internal/scheduler/AsyncScheduler.ts | 54 + .../src/internal/scheduler/QueueAction.ts | 44 + .../src/internal/scheduler/QueueScheduler.ts | 4 + .../scheduler/VirtualTimeScheduler.ts | 129 + .../src/internal/scheduler/animationFrame.ts | 41 + .../scheduler/animationFrameProvider.ts | 44 + .../rxjs/src/internal/scheduler/asap.ts | 44 + .../rxjs/src/internal/scheduler/async.ts | 56 + .../scheduler/dateTimestampProvider.ts | 14 + .../internal/scheduler/immediateProvider.ts | 31 + .../internal/scheduler/intervalProvider.ts | 31 + .../scheduler/performanceTimestampProvider.ts | 14 + .../rxjs/src/internal/scheduler/queue.ts | 72 + .../src/internal/scheduler/timeoutProvider.ts | 31 + .../src/internal/scheduler/timerHandle.ts | 1 + .../rxjs/src/internal/symbol/iterator.ts | 9 + .../rxjs/src/internal/symbol/observable.ts | 7 + .../src/internal/testing/ColdObservable.ts | 52 + .../src/internal/testing/HotObservable.ts | 53 + .../src/internal/testing/SubscriptionLog.ts | 5 + .../internal/testing/SubscriptionLoggable.ts | 22 + .../rxjs/src/internal/testing/TestMessage.ts | 7 + .../src/internal/testing/TestScheduler.ts | 693 + node_modules/rxjs/src/internal/types.ts | 326 + node_modules/rxjs/src/internal/umd.ts | 26 + .../internal/util/ArgumentOutOfRangeError.ts | 30 + .../rxjs/src/internal/util/EmptyError.ts | 29 + .../rxjs/src/internal/util/Immediate.ts | 45 + .../rxjs/src/internal/util/NotFoundError.ts | 28 + .../internal/util/ObjectUnsubscribedError.ts | 29 + .../rxjs/src/internal/util/SequenceError.ts | 28 + .../src/internal/util/UnsubscriptionError.ts | 30 + .../rxjs/src/internal/util/applyMixins.ts | 10 + node_modules/rxjs/src/internal/util/args.ts | 19 + .../src/internal/util/argsArgArrayOrObject.ts | 30 + .../rxjs/src/internal/util/argsOrArgArray.ts | 9 + .../rxjs/src/internal/util/arrRemove.ts | 11 + .../src/internal/util/createErrorClass.ts | 20 + .../rxjs/src/internal/util/createObject.ts | 3 + .../rxjs/src/internal/util/errorContext.ts | 42 + .../rxjs/src/internal/util/executeSchedule.ts | 44 + .../rxjs/src/internal/util/identity.ts | 45 + .../rxjs/src/internal/util/isArrayLike.ts | 1 + .../rxjs/src/internal/util/isAsyncIterable.ts | 5 + node_modules/rxjs/src/internal/util/isDate.ts | 10 + .../rxjs/src/internal/util/isFunction.ts | 7 + .../src/internal/util/isInteropObservable.ts | 8 + .../rxjs/src/internal/util/isIterable.ts | 7 + .../rxjs/src/internal/util/isObservable.ts | 13 + .../rxjs/src/internal/util/isPromise.ts | 9 + .../src/internal/util/isReadableStreamLike.ts | 23 + .../rxjs/src/internal/util/isScheduler.ts | 6 + node_modules/rxjs/src/internal/util/lift.ts | 32 + .../src/internal/util/mapOneOrManyArgs.ts | 16 + node_modules/rxjs/src/internal/util/noop.ts | 2 + node_modules/rxjs/src/internal/util/not.ts | 3 + node_modules/rxjs/src/internal/util/pipe.ts | 95 + .../src/internal/util/reportUnhandledError.ts | 24 + .../src/internal/util/subscribeToArray.ts | 12 + .../internal/util/throwUnobservableError.ts | 12 + .../rxjs/src/internal/util/workarounds.ts | 7 + node_modules/rxjs/src/operators/index.ts | 114 + node_modules/rxjs/src/testing/index.ts | 1 + node_modules/rxjs/src/tsconfig.base.json | 12 + node_modules/rxjs/src/tsconfig.cjs.json | 10 + node_modules/rxjs/src/tsconfig.cjs.spec.json | 10 + node_modules/rxjs/src/tsconfig.esm.json | 9 + node_modules/rxjs/src/tsconfig.esm5.json | 11 + .../rxjs/src/tsconfig.esm5.rollup.json | 8 + node_modules/rxjs/src/tsconfig.types.json | 14 + .../rxjs/src/tsconfig.types.spec.json | 7 + node_modules/rxjs/src/webSocket/index.ts | 2 + node_modules/rxjs/testing/package.json | 8 + node_modules/rxjs/tsconfig.json | 28 + node_modules/rxjs/webSocket/package.json | 8 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 + node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 65 + node_modules/safe-buffer/package.json | 51 + node_modules/safer-buffer/LICENSE | 21 + node_modules/safer-buffer/Porting-Buffer.md | 268 + node_modules/safer-buffer/Readme.md | 156 + node_modules/safer-buffer/dangerous.js | 58 + node_modules/safer-buffer/package.json | 34 + node_modules/safer-buffer/safer.js | 77 + node_modules/safer-buffer/tests.js | 406 + node_modules/scheduler/LICENSE | 21 + node_modules/scheduler/README.md | 9 + node_modules/scheduler/build-info.json | 8 + .../cjs/scheduler-tracing.development.js | 347 + .../cjs/scheduler-tracing.production.min.js | 9 + .../cjs/scheduler-tracing.profiling.min.js | 16 + .../scheduler-unstable_mock.development.js | 665 + .../scheduler-unstable_mock.production.min.js | 19 + ...cheduler-unstable_post_task.development.js | 206 + ...duler-unstable_post_task.production.min.js | 13 + .../scheduler/cjs/scheduler.development.js | 646 + .../scheduler/cjs/scheduler.production.min.js | 20 + node_modules/scheduler/index.js | 7 + node_modules/scheduler/package.json | 40 + node_modules/scheduler/tracing-profiling.js | 7 + node_modules/scheduler/tracing.js | 7 + .../umd/scheduler-tracing.development.js | 80 + .../umd/scheduler-tracing.production.min.js | 80 + .../umd/scheduler-tracing.profiling.min.js | 80 + .../scheduler-unstable_mock.development.js | 664 + .../scheduler-unstable_mock.production.min.js | 18 + .../scheduler/umd/scheduler.development.js | 152 + .../scheduler/umd/scheduler.production.min.js | 146 + .../scheduler/umd/scheduler.profiling.min.js | 146 + node_modules/scheduler/unstable_mock.js | 7 + node_modules/scheduler/unstable_post_task.js | 7 + node_modules/semver/CHANGELOG.md | 39 + node_modules/semver/LICENSE | 15 + node_modules/semver/README.md | 412 + node_modules/semver/bin/semver | 160 + node_modules/semver/package.json | 28 + node_modules/semver/range.bnf | 16 + node_modules/semver/semver.js | 1483 + node_modules/shell-quote/.eslintrc | 30 + node_modules/shell-quote/.github/FUNDING.yml | 12 + node_modules/shell-quote/.nycrc | 14 + node_modules/shell-quote/CHANGELOG.md | 262 + node_modules/shell-quote/LICENSE | 24 + node_modules/shell-quote/README.md | 161 + node_modules/shell-quote/example/env.js | 5 + node_modules/shell-quote/example/op.js | 5 + node_modules/shell-quote/example/parse.js | 5 + node_modules/shell-quote/example/quote.js | 5 + node_modules/shell-quote/index.js | 4 + node_modules/shell-quote/package.json | 66 + node_modules/shell-quote/parse.js | 190 + node_modules/shell-quote/quote.js | 16 + node_modules/shell-quote/security.md | 11 + node_modules/shell-quote/test/comment.js | 16 + node_modules/shell-quote/test/env.js | 52 + node_modules/shell-quote/test/env_fn.js | 21 + node_modules/shell-quote/test/op.js | 102 + node_modules/shell-quote/test/parse.js | 25 + node_modules/shell-quote/test/quote.js | 50 + node_modules/shell-quote/test/set.js | 31 + node_modules/shimmer/.travis.yml | 7 + node_modules/shimmer/LICENSE | 25 + node_modules/shimmer/README.md | 80 + node_modules/shimmer/index.js | 121 + node_modules/shimmer/package.json | 28 + node_modules/shimmer/test/init.tap.js | 48 + node_modules/shimmer/test/massUnwrap.tap.js | 121 + node_modules/shimmer/test/massWrap.tap.js | 174 + node_modules/shimmer/test/unwrap.tap.js | 101 + node_modules/shimmer/test/wrap.tap.js | 148 + node_modules/signal-exit/LICENSE.txt | 16 + node_modules/signal-exit/README.md | 39 + node_modules/signal-exit/index.js | 202 + node_modules/signal-exit/package.json | 38 + node_modules/signal-exit/signals.js | 53 + node_modules/slice-ansi/index.js | 97 + node_modules/slice-ansi/license | 9 + node_modules/slice-ansi/package.json | 51 + node_modules/slice-ansi/readme.md | 72 + node_modules/stack-chain/.npmignore | 5 + node_modules/stack-chain/.travis.yml | 7 + node_modules/stack-chain/LICENSE.md | 19 + node_modules/stack-chain/README.md | 159 + node_modules/stack-chain/benchmark.js | 55 + node_modules/stack-chain/format.js | 59 + node_modules/stack-chain/index.js | 16 + node_modules/stack-chain/package.json | 26 + node_modules/stack-chain/stack-chain.js | 198 + node_modules/stack-chain/test/produce.js | 44 + .../test/simple/callSite-function.js | 121 + .../test/simple/callSite-property.js | 61 + .../conflict-format-delayed-circular.js | 86 + .../test/simple/conflict-format-delayed.js | 112 + .../test/simple/conflict-format-existing.js | 50 + .../test/simple/conflict-version-first.js | 8 + .../test/simple/conflict-version-match.js | 10 + .../test/simple/conflict-version-mismatch.js | 13 + .../stack-chain/test/simple/extend.js | 84 + .../stack-chain/test/simple/filter.js | 72 + .../stack-chain/test/simple/format-replace.js | 64 + .../simple/format-tostring-non-generic.js | 19 + .../test/simple/non-extensible-errors.js | 29 + node_modules/stack-chain/test/simple/order.js | 40 + .../stack-chain/test/simple/uglify.js | 12 + node_modules/stack-utils/LICENSE.md | 21 + node_modules/stack-utils/index.js | 344 + .../escape-string-regexp/index.d.ts | 18 + .../escape-string-regexp/index.js | 11 + .../node_modules/escape-string-regexp/license | 9 + .../escape-string-regexp/package.json | 43 + .../escape-string-regexp/readme.md | 29 + node_modules/stack-utils/package.json | 39 + node_modules/stack-utils/readme.md | 143 + node_modules/string-width/index.d.ts | 29 + node_modules/string-width/index.js | 47 + node_modules/string-width/license | 9 + .../node_modules/ansi-regex/index.d.ts | 37 + .../node_modules/ansi-regex/index.js | 10 + .../node_modules/ansi-regex/license | 9 + .../node_modules/ansi-regex/package.json | 55 + .../node_modules/ansi-regex/readme.md | 78 + .../node_modules/strip-ansi/index.d.ts | 17 + .../node_modules/strip-ansi/index.js | 4 + .../node_modules/strip-ansi/license | 9 + .../node_modules/strip-ansi/package.json | 54 + .../node_modules/strip-ansi/readme.md | 46 + node_modules/string-width/package.json | 56 + node_modules/string-width/readme.md | 50 + node_modules/string_decoder/LICENSE | 48 + node_modules/string_decoder/README.md | 47 + node_modules/string_decoder/package.json | 34 + node_modules/strip-ansi/index.d.ts | 15 + node_modules/strip-ansi/index.js | 9 + node_modules/strip-ansi/license | 9 + node_modules/strip-ansi/package.json | 57 + node_modules/strip-ansi/readme.md | 41 + node_modules/supports-color/browser.js | 5 + node_modules/supports-color/index.js | 135 + node_modules/supports-color/license | 9 + node_modules/supports-color/package.json | 53 + node_modules/supports-color/readme.md | 76 + node_modules/supports-hyperlinks/browser.js | 8 + node_modules/supports-hyperlinks/index.js | 100 + node_modules/supports-hyperlinks/license | 9 + node_modules/supports-hyperlinks/package.json | 48 + node_modules/supports-hyperlinks/readme.md | 48 + node_modules/thenify-all/History.md | 11 + node_modules/thenify-all/LICENSE | 22 + node_modules/thenify-all/README.md | 66 + node_modules/thenify-all/index.js | 73 + node_modules/thenify-all/package.json | 34 + node_modules/thenify/History.md | 11 + node_modules/thenify/LICENSE | 22 + node_modules/thenify/README.md | 120 + node_modules/thenify/index.js | 77 + node_modules/thenify/package.json | 31 + node_modules/through/.travis.yml | 5 + node_modules/through/LICENSE.APACHE2 | 15 + node_modules/through/LICENSE.MIT | 24 + node_modules/through/index.js | 108 + node_modules/through/package.json | 36 + node_modules/through/readme.markdown | 64 + node_modules/through/test/async.js | 28 + node_modules/through/test/auto-destroy.js | 30 + node_modules/through/test/buffering.js | 71 + node_modules/through/test/end.js | 45 + node_modules/through/test/index.js | 133 + node_modules/tiny-invariant/LICENSE | 21 + node_modules/tiny-invariant/README.md | 105 + node_modules/tiny-invariant/package.json | 88 + .../tiny-invariant/src/tiny-invariant.flow.js | 12 + .../tiny-invariant/src/tiny-invariant.ts | 33 + node_modules/tmp/LICENSE | 21 + node_modules/tmp/README.md | 314 + node_modules/tmp/package.json | 38 + node_modules/ts-dedent/HISTORY.md | 55 + node_modules/ts-dedent/LICENSE | 21 + node_modules/ts-dedent/README.md | 107 + node_modules/ts-dedent/esm/index.d.ts | 2 + node_modules/ts-dedent/esm/index.js | 38 + node_modules/ts-dedent/esm/index.js.map | 1 + node_modules/ts-dedent/package.json | 68 + .../ts-dedent/src/__tests__/index.spec.ts | 554 + .../ts-dedent/src/__tests__/issue-21.spec.ts | 88 + node_modules/ts-dedent/src/index.ts | 58 + node_modules/tslib/CopyrightNotice.txt | 15 + node_modules/tslib/LICENSE.txt | 12 + node_modules/tslib/README.md | 164 + node_modules/tslib/SECURITY.md | 41 + node_modules/tslib/modules/index.js | 63 + node_modules/tslib/modules/package.json | 3 + node_modules/tslib/package.json | 38 + node_modules/tslib/tslib.d.ts | 430 + node_modules/tslib/tslib.es6.html | 1 + node_modules/tslib/tslib.es6.js | 293 + node_modules/tslib/tslib.html | 1 + node_modules/tslib/tslib.js | 370 + node_modules/type-fest/index.d.ts | 27 + node_modules/type-fest/license | 9 + node_modules/type-fest/package.json | 49 + node_modules/type-fest/readme.md | 640 + .../type-fest/source/async-return-type.d.ts | 23 + node_modules/type-fest/source/basic.d.ts | 67 + .../type-fest/source/conditional-except.d.ts | 43 + .../type-fest/source/conditional-keys.d.ts | 43 + .../type-fest/source/conditional-pick.d.ts | 42 + node_modules/type-fest/source/except.d.ts | 22 + .../type-fest/source/literal-union.d.ts | 33 + .../type-fest/source/merge-exclusive.d.ts | 39 + node_modules/type-fest/source/merge.d.ts | 22 + node_modules/type-fest/source/mutable.d.ts | 22 + node_modules/type-fest/source/opaque.d.ts | 65 + .../type-fest/source/package-json.d.ts | 585 + .../type-fest/source/partial-deep.d.ts | 72 + node_modules/type-fest/source/promisable.d.ts | 23 + .../type-fest/source/promise-value.d.ts | 20 + .../type-fest/source/readonly-deep.d.ts | 59 + .../source/require-at-least-one.d.ts | 32 + .../type-fest/source/require-exactly-one.d.ts | 35 + .../type-fest/source/set-optional.d.ts | 34 + .../type-fest/source/set-required.d.ts | 34 + .../type-fest/source/tsconfig-json.d.ts | 872 + .../source/union-to-intersection.d.ts | 58 + node_modules/unload/LICENSE | 201 + node_modules/unload/README.md | 68 + node_modules/unload/package.json | 93 + node_modules/unload/src/browser.js | 38 + node_modules/unload/src/index.browserify.js | 2 + node_modules/unload/src/index.d.ts | 19 + node_modules/unload/src/index.js | 53 + node_modules/unload/src/node.js | 38 + node_modules/use-sync-external-store/LICENSE | 21 + .../use-sync-external-store/README.md | 5 + ...se-sync-external-store-shim.development.js | 239 + ...-external-store-shim.native.development.js | 227 + ...ternal-store-shim.native.production.min.js | 11 + ...sync-external-store-shim.production.min.js | 11 + .../with-selector.development.js | 165 + .../with-selector.production.min.js | 12 + ...xternal-store-with-selector.development.js | 164 + ...rnal-store-with-selector.production.min.js | 12 + .../use-sync-external-store.development.js | 84 + .../use-sync-external-store.production.min.js | 10 + node_modules/use-sync-external-store/index.js | 7 + .../use-sync-external-store/package.json | 24 + .../use-sync-external-store/shim/index.js | 7 + .../shim/index.native.js | 7 + .../shim/with-selector.js | 7 + .../use-sync-external-store/with-selector.js | 7 + node_modules/use-zustand/LICENSE | 21 + node_modules/use-zustand/README.md | 70 + node_modules/use-zustand/package.json | 82 + node_modules/use-zustand/src/index.ts | 36 + node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 27 + node_modules/uuid/CHANGELOG.md | 268 + node_modules/uuid/CONTRIBUTING.md | 18 + node_modules/uuid/LICENSE.md | 9 + node_modules/uuid/README.md | 462 + node_modules/uuid/package.json | 131 + node_modules/uuid/wrapper.mjs | 10 + node_modules/wcwidth/.npmignore | 1 + node_modules/wcwidth/LICENSE | 30 + node_modules/wcwidth/Readme.md | 33 + node_modules/wcwidth/combining.js | 50 + node_modules/wcwidth/docs/index.md | 65 + node_modules/wcwidth/index.js | 99 + node_modules/wcwidth/package.json | 42 + node_modules/wcwidth/test/index.js | 64 + node_modules/widest-line/index.d.ts | 21 + node_modules/widest-line/index.js | 16 + node_modules/widest-line/license | 9 + node_modules/widest-line/package.json | 54 + node_modules/widest-line/readme.md | 34 + node_modules/wrap-ansi/index.js | 186 + node_modules/wrap-ansi/license | 9 + .../node_modules/ansi-regex/index.d.ts | 37 + .../node_modules/ansi-regex/index.js | 10 + .../wrap-ansi/node_modules/ansi-regex/license | 9 + .../node_modules/ansi-regex/package.json | 55 + .../node_modules/ansi-regex/readme.md | 78 + .../node_modules/strip-ansi/index.d.ts | 17 + .../node_modules/strip-ansi/index.js | 4 + .../wrap-ansi/node_modules/strip-ansi/license | 9 + .../node_modules/strip-ansi/package.json | 54 + .../node_modules/strip-ansi/readme.md | 46 + node_modules/wrap-ansi/package.json | 61 + node_modules/wrap-ansi/readme.md | 97 + node_modules/wrappy/LICENSE | 15 + node_modules/wrappy/README.md | 36 + node_modules/wrappy/package.json | 29 + node_modules/wrappy/wrappy.js | 33 + node_modules/ws/LICENSE | 21 + node_modules/ws/README.md | 495 + node_modules/ws/browser.js | 8 + node_modules/ws/index.js | 10 + node_modules/ws/package.json | 56 + node_modules/y18n/CHANGELOG.md | 100 + node_modules/y18n/LICENSE | 13 + node_modules/y18n/README.md | 127 + node_modules/y18n/index.mjs | 8 + node_modules/y18n/package.json | 70 + node_modules/yargs-parser/CHANGELOG.md | 263 + node_modules/yargs-parser/LICENSE.txt | 14 + node_modules/yargs-parser/README.md | 518 + node_modules/yargs-parser/browser.js | 29 + node_modules/yargs-parser/package.json | 87 + node_modules/yargs/CHANGELOG.md | 88 + node_modules/yargs/LICENSE | 21 + node_modules/yargs/README.md | 202 + node_modules/yargs/browser.mjs | 7 + node_modules/yargs/helpers/helpers.mjs | 10 + node_modules/yargs/helpers/index.js | 14 + node_modules/yargs/helpers/package.json | 3 + node_modules/yargs/index.cjs | 39 + node_modules/yargs/index.mjs | 8 + node_modules/yargs/locales/be.json | 46 + node_modules/yargs/locales/de.json | 46 + node_modules/yargs/locales/en.json | 51 + node_modules/yargs/locales/es.json | 46 + node_modules/yargs/locales/fi.json | 49 + node_modules/yargs/locales/fr.json | 53 + node_modules/yargs/locales/hi.json | 49 + node_modules/yargs/locales/hu.json | 46 + node_modules/yargs/locales/id.json | 50 + node_modules/yargs/locales/it.json | 46 + node_modules/yargs/locales/ja.json | 51 + node_modules/yargs/locales/ko.json | 49 + node_modules/yargs/locales/nb.json | 44 + node_modules/yargs/locales/nl.json | 49 + node_modules/yargs/locales/nn.json | 44 + node_modules/yargs/locales/pirate.json | 13 + node_modules/yargs/locales/pl.json | 49 + node_modules/yargs/locales/pt.json | 45 + node_modules/yargs/locales/pt_BR.json | 48 + node_modules/yargs/locales/ru.json | 46 + node_modules/yargs/locales/th.json | 46 + node_modules/yargs/locales/tr.json | 48 + node_modules/yargs/locales/zh_CN.json | 48 + node_modules/yargs/locales/zh_TW.json | 47 + node_modules/yargs/package.json | 122 + node_modules/yargs/yargs | 9 + node_modules/yoga-layout-prebuilt/index.d.ts | 3 + node_modules/yoga-layout-prebuilt/license | 9 + .../yoga-layout-prebuilt/package.json | 42 + node_modules/yoga-layout-prebuilt/readme.md | 23 + node_modules/zustand/LICENSE | 21 + node_modules/zustand/context.d.ts | 24 + node_modules/zustand/context.js | 60 + node_modules/zustand/esm/context.d.mts | 24 + node_modules/zustand/esm/context.d.ts | 24 + node_modules/zustand/esm/context.js | 54 + node_modules/zustand/esm/context.mjs | 54 + node_modules/zustand/esm/index.d.mts | 3 + node_modules/zustand/esm/index.d.ts | 3 + node_modules/zustand/esm/index.js | 39 + node_modules/zustand/esm/index.mjs | 39 + node_modules/zustand/esm/middleware.d.mts | 5 + node_modules/zustand/esm/middleware.d.ts | 5 + node_modules/zustand/esm/middleware.js | 574 + node_modules/zustand/esm/middleware.mjs | 574 + .../zustand/esm/middleware/combine.d.mts | 5 + .../zustand/esm/middleware/combine.d.ts | 5 + .../zustand/esm/middleware/devtools.d.mts | 103 + .../zustand/esm/middleware/devtools.d.ts | 103 + .../zustand/esm/middleware/immer.d.mts | 25 + .../zustand/esm/middleware/immer.d.ts | 25 + node_modules/zustand/esm/middleware/immer.js | 12 + node_modules/zustand/esm/middleware/immer.mjs | 12 + .../zustand/esm/middleware/persist.d.mts | 106 + .../zustand/esm/middleware/persist.d.ts | 106 + .../zustand/esm/middleware/redux.d.mts | 21 + .../zustand/esm/middleware/redux.d.ts | 21 + .../middleware/subscribeWithSelector.d.mts | 25 + .../esm/middleware/subscribeWithSelector.d.ts | 25 + node_modules/zustand/esm/react.d.mts | 28 + node_modules/zustand/esm/react.d.ts | 28 + node_modules/zustand/esm/shallow.d.mts | 6 + node_modules/zustand/esm/shallow.d.ts | 6 + node_modules/zustand/esm/shallow.js | 48 + node_modules/zustand/esm/shallow.mjs | 48 + node_modules/zustand/esm/vanilla.d.mts | 80 + node_modules/zustand/esm/vanilla.d.ts | 80 + node_modules/zustand/esm/vanilla.js | 39 + node_modules/zustand/esm/vanilla.mjs | 39 + node_modules/zustand/index.d.ts | 3 + node_modules/zustand/index.js | 51 + node_modules/zustand/middleware.d.ts | 5 + node_modules/zustand/middleware.js | 604 + node_modules/zustand/middleware/combine.d.ts | 5 + node_modules/zustand/middleware/devtools.d.ts | 103 + node_modules/zustand/middleware/immer.d.ts | 25 + node_modules/zustand/middleware/immer.js | 19 + node_modules/zustand/middleware/persist.d.ts | 106 + node_modules/zustand/middleware/redux.d.ts | 21 + .../middleware/subscribeWithSelector.d.ts | 25 + node_modules/zustand/package.json | 119 + node_modules/zustand/react.d.ts | 28 + node_modules/zustand/readme.md | 523 + node_modules/zustand/shallow.d.ts | 6 + node_modules/zustand/shallow.js | 87 + .../zustand/system/context.development.js | 70 + .../zustand/system/context.production.js | 1 + .../zustand/system/index.development.js | 61 + .../zustand/system/index.production.js | 1 + .../zustand/system/middleware.development.js | 583 + .../zustand/system/middleware.production.js | 5 + .../system/middleware/immer.development.js | 21 + .../system/middleware/immer.production.js | 1 + .../zustand/system/shallow.development.js | 57 + .../zustand/system/shallow.production.js | 1 + .../zustand/system/vanilla.development.js | 46 + .../zustand/system/vanilla.production.js | 1 + node_modules/zustand/ts3.4/context.d.ts | 24 + node_modules/zustand/ts3.4/esm/context.d.ts | 24 + node_modules/zustand/ts3.4/esm/index.d.ts | 3 + .../zustand/ts3.4/esm/middleware.d.ts | 5 + .../zustand/ts3.4/esm/middleware/combine.d.ts | 13 + .../ts3.4/esm/middleware/devtools.d.ts | 156 + .../zustand/ts3.4/esm/middleware/immer.d.ts | 60 + .../zustand/ts3.4/esm/middleware/persist.d.ts | 126 + .../zustand/ts3.4/esm/middleware/redux.d.ts | 30 + .../esm/middleware/subscribeWithSelector.d.ts | 42 + node_modules/zustand/ts3.4/esm/react.d.ts | 38 + node_modules/zustand/ts3.4/esm/shallow.d.ts | 6 + node_modules/zustand/ts3.4/esm/vanilla.d.ts | 105 + node_modules/zustand/ts3.4/index.d.ts | 3 + node_modules/zustand/ts3.4/middleware.d.ts | 5 + .../zustand/ts3.4/middleware/combine.d.ts | 13 + .../zustand/ts3.4/middleware/devtools.d.ts | 156 + .../zustand/ts3.4/middleware/immer.d.ts | 60 + .../zustand/ts3.4/middleware/persist.d.ts | 126 + .../zustand/ts3.4/middleware/redux.d.ts | 30 + .../middleware/subscribeWithSelector.d.ts | 42 + node_modules/zustand/ts3.4/react.d.ts | 38 + node_modules/zustand/ts3.4/shallow.d.ts | 6 + node_modules/zustand/ts3.4/vanilla.d.ts | 105 + .../zustand/umd/context.development.js | 63 + .../zustand/umd/context.production.js | 1 + node_modules/zustand/umd/index.development.js | 49 + node_modules/zustand/umd/index.production.js | 1 + .../zustand/umd/middleware.development.js | 610 + .../zustand/umd/middleware.production.js | 1 + .../umd/middleware/immer.development.js | 23 + .../umd/middleware/immer.production.js | 1 + .../zustand/umd/shallow.development.js | 91 + .../zustand/umd/shallow.production.js | 1 + .../zustand/umd/vanilla.development.js | 59 + .../zustand/umd/vanilla.production.js | 1 + node_modules/zustand/vanilla.d.ts | 80 + node_modules/zustand/vanilla.js | 55 + package-lock.json | 3941 +++ package.json | 5 + tests/test_parameters.py | 8 +- 4294 files changed, 410832 insertions(+), 13 deletions(-) create mode 120000 node_modules/.bin/cdl create mode 120000 node_modules/.bin/esparse create mode 120000 node_modules/.bin/esvalidate create mode 120000 node_modules/.bin/github-copilot-cli create mode 120000 node_modules/.bin/highlight create mode 120000 node_modules/.bin/is-ci create mode 120000 node_modules/.bin/loose-envify create mode 120000 node_modules/.bin/marked create mode 120000 node_modules/.bin/rimraf create mode 120000 node_modules/.bin/semver create mode 120000 node_modules/.bin/uuid create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@azure/abort-controller/CHANGELOG.md create mode 100644 node_modules/@azure/abort-controller/LICENSE create mode 100644 node_modules/@azure/abort-controller/README.md create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/AbortController.js create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/AbortController.js.map create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js.map create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/index.js create mode 100644 node_modules/@azure/abort-controller/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/abort-controller/package.json create mode 100644 node_modules/@azure/abort-controller/shims-public.d.ts create mode 100644 node_modules/@azure/abort-controller/types/3.1/AbortController.d.ts create mode 100644 node_modules/@azure/abort-controller/types/3.1/AbortSignal.d.ts create mode 100644 node_modules/@azure/abort-controller/types/3.1/index.d.ts create mode 100644 node_modules/@azure/abort-controller/types/src/AbortController.d.ts create mode 100644 node_modules/@azure/abort-controller/types/src/AbortController.d.ts.map create mode 100644 node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts create mode 100644 node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts.map create mode 100644 node_modules/@azure/abort-controller/types/src/index.d.ts create mode 100644 node_modules/@azure/abort-controller/types/src/index.d.ts.map create mode 100644 node_modules/@azure/abort-controller/types/src/tsdoc-metadata.json create mode 100644 node_modules/@azure/core-auth/LICENSE create mode 100644 node_modules/@azure/core-auth/README.md create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/index.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/tracing.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/tracing.js.map create mode 100644 node_modules/@azure/core-auth/dist-esm/src/typeguards.js create mode 100644 node_modules/@azure/core-auth/dist-esm/src/typeguards.js.map create mode 100644 node_modules/@azure/core-auth/package.json create mode 100644 node_modules/@azure/core-auth/types/3.1/core-auth.d.ts create mode 100644 node_modules/@azure/core-auth/types/latest/core-auth.d.ts create mode 100644 node_modules/@azure/core-rest-pipeline/LICENSE create mode 100644 node_modules/@azure/core-rest-pipeline/README.md create mode 100644 node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims-3_1.d.ts create mode 100644 node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims.d.ts create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js.map create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js create mode 100644 node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js.map create mode 120000 node_modules/@azure/core-rest-pipeline/node_modules/.bin/uuid create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/LICENSE.md create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/README.md create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/package.json create mode 100644 node_modules/@azure/core-rest-pipeline/node_modules/uuid/wrapper.mjs create mode 100644 node_modules/@azure/core-rest-pipeline/package.json create mode 100644 node_modules/@azure/core-rest-pipeline/types/3.1/core-rest-pipeline.d.ts create mode 100644 node_modules/@azure/core-rest-pipeline/types/latest/core-rest-pipeline.d.ts create mode 100644 node_modules/@azure/core-tracing/CHANGELOG.md create mode 100644 node_modules/@azure/core-tracing/LICENSE create mode 100644 node_modules/@azure/core-tracing/README.md create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/index.js create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js.map create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/interfaces.js create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/interfaces.js.map create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js.map create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js create mode 100644 node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js.map create mode 100644 node_modules/@azure/core-tracing/package.json create mode 100644 node_modules/@azure/core-tracing/types/core-tracing.d.ts create mode 100644 node_modules/@azure/core-util/LICENSE create mode 100644 node_modules/@azure/core-util/README.md create mode 100644 node_modules/@azure/core-util/dist-esm/src/base64.browser.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/base64.browser.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/delay.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/delay.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/error.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/error.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/hex.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/hex.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/index.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/isNode.browser.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/isNode.browser.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/isNode.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/isNode.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/object.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/object.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/random.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/random.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/sha256.browser.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/sha256.browser.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/sha256.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/sha256.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/typeGuards.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/typeGuards.js.map create mode 100644 node_modules/@azure/core-util/dist-esm/src/utf8.browser.js create mode 100644 node_modules/@azure/core-util/dist-esm/src/utf8.browser.js.map create mode 100644 node_modules/@azure/core-util/package.json create mode 100644 node_modules/@azure/core-util/types/3.1/core-util.d.ts create mode 100644 node_modules/@azure/core-util/types/latest/core-util.d.ts create mode 100644 node_modules/@azure/logger/LICENSE create mode 100644 node_modules/@azure/logger/README.md create mode 100644 node_modules/@azure/logger/dist-esm/src/debug.js create mode 100644 node_modules/@azure/logger/dist-esm/src/debug.js.map create mode 100644 node_modules/@azure/logger/dist-esm/src/index.js create mode 100644 node_modules/@azure/logger/dist-esm/src/index.js.map create mode 100644 node_modules/@azure/logger/dist-esm/src/log.browser.js create mode 100644 node_modules/@azure/logger/dist-esm/src/log.browser.js.map create mode 100644 node_modules/@azure/logger/dist-esm/src/log.js create mode 100644 node_modules/@azure/logger/dist-esm/src/log.js.map create mode 100644 node_modules/@azure/logger/package.json create mode 100644 node_modules/@azure/logger/types/logger.d.ts create mode 100644 node_modules/@babel/runtime/LICENSE create mode 100644 node_modules/@babel/runtime/README.md create mode 100644 node_modules/@babel/runtime/helpers/AsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/AwaitValue.js create mode 100644 node_modules/@babel/runtime/helpers/OverloadYield.js create mode 100644 node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/applyDecs.js create mode 100644 node_modules/@babel/runtime/helpers/applyDecs2203.js create mode 100644 node_modules/@babel/runtime/helpers/applyDecs2203R.js create mode 100644 node_modules/@babel/runtime/helpers/applyDecs2301.js create mode 100644 node_modules/@babel/runtime/helpers/arrayLikeToArray.js create mode 100644 node_modules/@babel/runtime/helpers/arrayWithHoles.js create mode 100644 node_modules/@babel/runtime/helpers/arrayWithoutHoles.js create mode 100644 node_modules/@babel/runtime/helpers/assertThisInitialized.js create mode 100644 node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js create mode 100644 node_modules/@babel/runtime/helpers/asyncIterator.js create mode 100644 node_modules/@babel/runtime/helpers/asyncToGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/checkInRHS.js create mode 100644 node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js create mode 100644 node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js create mode 100644 node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js create mode 100644 node_modules/@babel/runtime/helpers/classCallCheck.js create mode 100644 node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js create mode 100644 node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/classNameTDZError.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldGet.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateFieldSet.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateMethodGet.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js create mode 100644 node_modules/@babel/runtime/helpers/classPrivateMethodSet.js create mode 100644 node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js create mode 100644 node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js create mode 100644 node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js create mode 100644 node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js create mode 100644 node_modules/@babel/runtime/helpers/construct.js create mode 100644 node_modules/@babel/runtime/helpers/createClass.js create mode 100644 node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js create mode 100644 node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js create mode 100644 node_modules/@babel/runtime/helpers/createSuper.js create mode 100644 node_modules/@babel/runtime/helpers/decorate.js create mode 100644 node_modules/@babel/runtime/helpers/defaults.js create mode 100644 node_modules/@babel/runtime/helpers/defineAccessor.js create mode 100644 node_modules/@babel/runtime/helpers/defineEnumerableProperties.js create mode 100644 node_modules/@babel/runtime/helpers/defineProperty.js create mode 100644 node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/esm/AwaitValue.js create mode 100644 node_modules/@babel/runtime/helpers/esm/OverloadYield.js create mode 100644 node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/esm/applyDecs.js create mode 100644 node_modules/@babel/runtime/helpers/esm/applyDecs2203.js create mode 100644 node_modules/@babel/runtime/helpers/esm/applyDecs2203R.js create mode 100644 node_modules/@babel/runtime/helpers/esm/applyDecs2301.js create mode 100644 node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js create mode 100644 node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js create mode 100644 node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js create mode 100644 node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js create mode 100644 node_modules/@babel/runtime/helpers/esm/asyncIterator.js create mode 100644 node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/esm/checkInRHS.js create mode 100644 node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classCallCheck.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classNameTDZError.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js create mode 100644 node_modules/@babel/runtime/helpers/esm/construct.js create mode 100644 node_modules/@babel/runtime/helpers/esm/createClass.js create mode 100644 node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js create mode 100644 node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/createSuper.js create mode 100644 node_modules/@babel/runtime/helpers/esm/decorate.js create mode 100644 node_modules/@babel/runtime/helpers/esm/defaults.js create mode 100644 node_modules/@babel/runtime/helpers/esm/defineAccessor.js create mode 100644 node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js create mode 100644 node_modules/@babel/runtime/helpers/esm/defineProperty.js create mode 100644 node_modules/@babel/runtime/helpers/esm/extends.js create mode 100644 node_modules/@babel/runtime/helpers/esm/get.js create mode 100644 node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js create mode 100644 node_modules/@babel/runtime/helpers/esm/identity.js create mode 100644 node_modules/@babel/runtime/helpers/esm/inherits.js create mode 100644 node_modules/@babel/runtime/helpers/esm/inheritsLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js create mode 100644 node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js create mode 100644 node_modules/@babel/runtime/helpers/esm/instanceof.js create mode 100644 node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js create mode 100644 node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js create mode 100644 node_modules/@babel/runtime/helpers/esm/isNativeFunction.js create mode 100644 node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js create mode 100644 node_modules/@babel/runtime/helpers/esm/iterableToArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js create mode 100644 node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/jsx.js create mode 100644 node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js create mode 100644 node_modules/@babel/runtime/helpers/esm/newArrowCheck.js create mode 100644 node_modules/@babel/runtime/helpers/esm/nonIterableRest.js create mode 100644 node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js create mode 100644 node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js create mode 100644 node_modules/@babel/runtime/helpers/esm/objectSpread.js create mode 100644 node_modules/@babel/runtime/helpers/esm/objectSpread2.js create mode 100644 node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js create mode 100644 node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/package.json create mode 100644 node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js create mode 100644 node_modules/@babel/runtime/helpers/esm/readOnlyError.js create mode 100644 node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js create mode 100644 node_modules/@babel/runtime/helpers/esm/set.js create mode 100644 node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js create mode 100644 node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js create mode 100644 node_modules/@babel/runtime/helpers/esm/slicedToArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/superPropBase.js create mode 100644 node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js create mode 100644 node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js create mode 100644 node_modules/@babel/runtime/helpers/esm/tdz.js create mode 100644 node_modules/@babel/runtime/helpers/esm/temporalRef.js create mode 100644 node_modules/@babel/runtime/helpers/esm/temporalUndefined.js create mode 100644 node_modules/@babel/runtime/helpers/esm/toArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/toConsumableArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/toPrimitive.js create mode 100644 node_modules/@babel/runtime/helpers/esm/toPropertyKey.js create mode 100644 node_modules/@babel/runtime/helpers/esm/typeof.js create mode 100644 node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js create mode 100644 node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js create mode 100644 node_modules/@babel/runtime/helpers/esm/wrapRegExp.js create mode 100644 node_modules/@babel/runtime/helpers/esm/writeOnlyError.js create mode 100644 node_modules/@babel/runtime/helpers/extends.js create mode 100644 node_modules/@babel/runtime/helpers/get.js create mode 100644 node_modules/@babel/runtime/helpers/getPrototypeOf.js create mode 100644 node_modules/@babel/runtime/helpers/identity.js create mode 100644 node_modules/@babel/runtime/helpers/inherits.js create mode 100644 node_modules/@babel/runtime/helpers/inheritsLoose.js create mode 100644 node_modules/@babel/runtime/helpers/initializerDefineProperty.js create mode 100644 node_modules/@babel/runtime/helpers/initializerWarningHelper.js create mode 100644 node_modules/@babel/runtime/helpers/instanceof.js create mode 100644 node_modules/@babel/runtime/helpers/interopRequireDefault.js create mode 100644 node_modules/@babel/runtime/helpers/interopRequireWildcard.js create mode 100644 node_modules/@babel/runtime/helpers/isNativeFunction.js create mode 100644 node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js create mode 100644 node_modules/@babel/runtime/helpers/iterableToArray.js create mode 100644 node_modules/@babel/runtime/helpers/iterableToArrayLimit.js create mode 100644 node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js create mode 100644 node_modules/@babel/runtime/helpers/jsx.js create mode 100644 node_modules/@babel/runtime/helpers/maybeArrayLike.js create mode 100644 node_modules/@babel/runtime/helpers/newArrowCheck.js create mode 100644 node_modules/@babel/runtime/helpers/nonIterableRest.js create mode 100644 node_modules/@babel/runtime/helpers/nonIterableSpread.js create mode 100644 node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js create mode 100644 node_modules/@babel/runtime/helpers/objectSpread.js create mode 100644 node_modules/@babel/runtime/helpers/objectSpread2.js create mode 100644 node_modules/@babel/runtime/helpers/objectWithoutProperties.js create mode 100644 node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js create mode 100644 node_modules/@babel/runtime/helpers/possibleConstructorReturn.js create mode 100644 node_modules/@babel/runtime/helpers/readOnlyError.js create mode 100644 node_modules/@babel/runtime/helpers/regeneratorRuntime.js create mode 100644 node_modules/@babel/runtime/helpers/set.js create mode 100644 node_modules/@babel/runtime/helpers/setPrototypeOf.js create mode 100644 node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js create mode 100644 node_modules/@babel/runtime/helpers/slicedToArray.js create mode 100644 node_modules/@babel/runtime/helpers/slicedToArrayLoose.js create mode 100644 node_modules/@babel/runtime/helpers/superPropBase.js create mode 100644 node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js create mode 100644 node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js create mode 100644 node_modules/@babel/runtime/helpers/tdz.js create mode 100644 node_modules/@babel/runtime/helpers/temporalRef.js create mode 100644 node_modules/@babel/runtime/helpers/temporalUndefined.js create mode 100644 node_modules/@babel/runtime/helpers/toArray.js create mode 100644 node_modules/@babel/runtime/helpers/toConsumableArray.js create mode 100644 node_modules/@babel/runtime/helpers/toPrimitive.js create mode 100644 node_modules/@babel/runtime/helpers/toPropertyKey.js create mode 100644 node_modules/@babel/runtime/helpers/typeof.js create mode 100644 node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js create mode 100644 node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js create mode 100644 node_modules/@babel/runtime/helpers/wrapNativeSuper.js create mode 100644 node_modules/@babel/runtime/helpers/wrapRegExp.js create mode 100644 node_modules/@babel/runtime/helpers/writeOnlyError.js create mode 100644 node_modules/@babel/runtime/package.json create mode 100644 node_modules/@babel/runtime/regenerator/index.js create mode 100644 node_modules/@colors/colors/LICENSE create mode 100644 node_modules/@colors/colors/README.md create mode 100644 node_modules/@colors/colors/examples/normal-usage.js create mode 100644 node_modules/@colors/colors/examples/safe-string.js create mode 100644 node_modules/@colors/colors/index.d.ts create mode 100644 node_modules/@colors/colors/package.json create mode 100644 node_modules/@colors/colors/safe.d.ts create mode 100644 node_modules/@colors/colors/safe.js create mode 100644 node_modules/@colors/colors/themes/generic-logging.js create mode 100644 node_modules/@githubnext/github-copilot-cli/README.md create mode 100755 node_modules/@githubnext/github-copilot-cli/cli.js create mode 100644 node_modules/@githubnext/github-copilot-cli/package.json create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/LICENSE create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/README.md create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/dest/applicationinsights-web-snippet.ts create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/package.json create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/src/applicationinsights-web-snippet.ts create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/tsconfig.json create mode 100644 node_modules/@microsoft/applicationinsights-web-snippet/types/applicationinsights-web-snippet.d.ts create mode 100644 node_modules/@opentelemetry/api/LICENSE create mode 100644 node_modules/@opentelemetry/api/README.md create mode 100644 node_modules/@opentelemetry/api/package.json create mode 100644 node_modules/@opentelemetry/core/LICENSE create mode 100644 node_modules/@opentelemetry/core/README.md create mode 100644 node_modules/@opentelemetry/core/package.json create mode 100644 node_modules/@opentelemetry/resources/LICENSE create mode 100644 node_modules/@opentelemetry/resources/README.md create mode 100644 node_modules/@opentelemetry/resources/package.json create mode 100644 node_modules/@opentelemetry/sdk-trace-base/LICENSE create mode 100644 node_modules/@opentelemetry/sdk-trace-base/README.md create mode 100644 node_modules/@opentelemetry/sdk-trace-base/package.json create mode 100644 node_modules/@opentelemetry/semantic-conventions/LICENSE create mode 100644 node_modules/@opentelemetry/semantic-conventions/README.md create mode 100644 node_modules/@opentelemetry/semantic-conventions/package.json create mode 100644 node_modules/@tootallnate/once/LICENSE create mode 100644 node_modules/@tootallnate/once/README.md create mode 100644 node_modules/@tootallnate/once/package.json create mode 100644 node_modules/@types/yoga-layout/LICENSE create mode 100644 node_modules/@types/yoga-layout/README.md create mode 100644 node_modules/@types/yoga-layout/index.d.ts create mode 100644 node_modules/@types/yoga-layout/package.json create mode 100644 node_modules/agent-base/README.md create mode 100644 node_modules/agent-base/package.json create mode 100644 node_modules/agent-base/src/index.ts create mode 100644 node_modules/agent-base/src/promisify.ts create mode 100644 node_modules/ansi-escapes/index.d.ts create mode 100644 node_modules/ansi-escapes/index.js create mode 100644 node_modules/ansi-escapes/license create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/base.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/index.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/license create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/package.json create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/readme.md create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/async-return-type.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/asyncify.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/basic.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/conditional-except.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/conditional-keys.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/conditional-pick.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/entries.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/entry.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/except.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/fixed-length-array.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/iterable-element.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/literal-union.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/merge-exclusive.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/merge.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/mutable.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/opaque.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/package-json.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/partial-deep.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/promisable.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/promise-value.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/readonly-deep.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/require-at-least-one.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/require-exactly-one.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/set-optional.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/set-required.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/set-return-type.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/simplify.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/stringified.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/tsconfig-json.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/typed-array.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/union-to-intersection.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/utilities.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/source/value-of.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/camel-case.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/delimiter-case.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/get.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/index.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/kebab-case.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/pascal-case.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/snake-case.d.ts create mode 100644 node_modules/ansi-escapes/node_modules/type-fest/ts41/utilities.d.ts create mode 100644 node_modules/ansi-escapes/package.json create mode 100644 node_modules/ansi-escapes/readme.md create mode 100644 node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/ansi-regex/index.js create mode 100644 node_modules/ansi-regex/license create mode 100644 node_modules/ansi-regex/package.json create mode 100644 node_modules/ansi-regex/readme.md create mode 100644 node_modules/ansi-styles/index.d.ts create mode 100644 node_modules/ansi-styles/index.js create mode 100644 node_modules/ansi-styles/license create mode 100644 node_modules/ansi-styles/package.json create mode 100644 node_modules/ansi-styles/readme.md create mode 100644 node_modules/ansicolors/LICENSE create mode 100644 node_modules/ansicolors/README.md create mode 100644 node_modules/ansicolors/ansicolors.js create mode 100644 node_modules/ansicolors/package.json create mode 100644 node_modules/ansicolors/test/ansicolors.js create mode 100644 node_modules/any-promise/.jshintrc create mode 100644 node_modules/any-promise/.npmignore create mode 100644 node_modules/any-promise/LICENSE create mode 100644 node_modules/any-promise/README.md create mode 100644 node_modules/any-promise/implementation.d.ts create mode 100644 node_modules/any-promise/implementation.js create mode 100644 node_modules/any-promise/index.d.ts create mode 100644 node_modules/any-promise/index.js create mode 100644 node_modules/any-promise/loader.js create mode 100644 node_modules/any-promise/optional.js create mode 100644 node_modules/any-promise/package.json create mode 100644 node_modules/any-promise/register-shim.js create mode 100644 node_modules/any-promise/register.d.ts create mode 100644 node_modules/any-promise/register.js create mode 100644 node_modules/any-promise/register/bluebird.d.ts create mode 100644 node_modules/any-promise/register/bluebird.js create mode 100644 node_modules/any-promise/register/es6-promise.d.ts create mode 100644 node_modules/any-promise/register/es6-promise.js create mode 100644 node_modules/any-promise/register/lie.d.ts create mode 100644 node_modules/any-promise/register/lie.js create mode 100644 node_modules/any-promise/register/native-promise-only.d.ts create mode 100644 node_modules/any-promise/register/native-promise-only.js create mode 100644 node_modules/any-promise/register/pinkie.d.ts create mode 100644 node_modules/any-promise/register/pinkie.js create mode 100644 node_modules/any-promise/register/promise.d.ts create mode 100644 node_modules/any-promise/register/promise.js create mode 100644 node_modules/any-promise/register/q.d.ts create mode 100644 node_modules/any-promise/register/q.js create mode 100644 node_modules/any-promise/register/rsvp.d.ts create mode 100644 node_modules/any-promise/register/rsvp.js create mode 100644 node_modules/any-promise/register/vow.d.ts create mode 100644 node_modules/any-promise/register/vow.js create mode 100644 node_modules/any-promise/register/when.d.ts create mode 100644 node_modules/any-promise/register/when.js create mode 100644 node_modules/applicationinsights/.eslintignore create mode 100644 node_modules/applicationinsights/.eslintrc create mode 100644 node_modules/applicationinsights/CODE_OF_CONDUCT.md create mode 100644 node_modules/applicationinsights/CONTRIBUTING.md create mode 100644 node_modules/applicationinsights/LICENSE create mode 100644 node_modules/applicationinsights/NOTICE create mode 100644 node_modules/applicationinsights/PRIVACY create mode 100644 node_modules/applicationinsights/README.md create mode 100644 node_modules/applicationinsights/SECURITY.md create mode 100644 node_modules/applicationinsights/SUPPORT.md create mode 100644 node_modules/applicationinsights/applicationinsights.json create mode 100644 node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/Console.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/Console.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/Console.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/Exceptions.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/Exceptions.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/Exceptions.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/HeartBeat.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/HeartBeat.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/HeartBeat.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencies.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequests.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequests.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/HttpRequests.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/NativePerformance.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/NativePerformance.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/NativePerformance.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/Performance.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/Performance.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/Performance.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/RequestParser.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/RequestParser.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/RequestParser.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/Statsbeat.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/Statsbeat.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/Statsbeat.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/WebSnippet.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/WebSnippet.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/WebSnippet.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js.map create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.d.ts create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js create mode 100644 node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/DataModel.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/DataModel.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/DataModel.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/Default.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/Default.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/Default.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/FileWriter.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/FileWriter.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/FileWriter.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/NoopLogger.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/NoopLogger.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/NoopLogger.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/Oryx.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/Oryx.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/Oryx.js.map create mode 100644 node_modules/applicationinsights/out/Bootstrap/StatusLogger.d.ts create mode 100644 node_modules/applicationinsights/out/Bootstrap/StatusLogger.js create mode 100644 node_modules/applicationinsights/out/Bootstrap/StatusLogger.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Constants.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Constants.js create mode 100644 node_modules/applicationinsights/out/Declarations/Constants.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Constants.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Constants.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Constants.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/index.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/index.js create mode 100644 node_modules/applicationinsights/out/Declarations/Contracts/index.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Interfaces.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Interfaces.js create mode 100644 node_modules/applicationinsights/out/Declarations/Interfaces.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js.map create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.d.ts create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js create mode 100644 node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js.map create mode 100644 node_modules/applicationinsights/out/Library/AuthorizationHandler.d.ts create mode 100644 node_modules/applicationinsights/out/Library/AuthorizationHandler.js create mode 100644 node_modules/applicationinsights/out/Library/AuthorizationHandler.js.map create mode 100644 node_modules/applicationinsights/out/Library/AzureVirtualMachine.d.ts create mode 100644 node_modules/applicationinsights/out/Library/AzureVirtualMachine.js create mode 100644 node_modules/applicationinsights/out/Library/AzureVirtualMachine.js.map create mode 100644 node_modules/applicationinsights/out/Library/Channel.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Channel.js create mode 100644 node_modules/applicationinsights/out/Library/Channel.js.map create mode 100644 node_modules/applicationinsights/out/Library/Config.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Config.js create mode 100644 node_modules/applicationinsights/out/Library/Config.js.map create mode 100644 node_modules/applicationinsights/out/Library/ConnectionStringParser.d.ts create mode 100644 node_modules/applicationinsights/out/Library/ConnectionStringParser.js create mode 100644 node_modules/applicationinsights/out/Library/ConnectionStringParser.js.map create mode 100644 node_modules/applicationinsights/out/Library/Context.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Context.js create mode 100644 node_modules/applicationinsights/out/Library/Context.js.map create mode 100644 node_modules/applicationinsights/out/Library/CorrelationIdManager.d.ts create mode 100644 node_modules/applicationinsights/out/Library/CorrelationIdManager.js create mode 100644 node_modules/applicationinsights/out/Library/CorrelationIdManager.js.map create mode 100644 node_modules/applicationinsights/out/Library/EnvelopeFactory.d.ts create mode 100644 node_modules/applicationinsights/out/Library/EnvelopeFactory.js create mode 100644 node_modules/applicationinsights/out/Library/EnvelopeFactory.js.map create mode 100644 node_modules/applicationinsights/out/Library/FileAccessControl.d.ts create mode 100644 node_modules/applicationinsights/out/Library/FileAccessControl.js create mode 100644 node_modules/applicationinsights/out/Library/FileAccessControl.js.map create mode 100644 node_modules/applicationinsights/out/Library/FileSystemHelper.d.ts create mode 100644 node_modules/applicationinsights/out/Library/FileSystemHelper.js create mode 100644 node_modules/applicationinsights/out/Library/FileSystemHelper.js.map create mode 100644 node_modules/applicationinsights/out/Library/FlushOptions.d.ts create mode 100644 node_modules/applicationinsights/out/Library/FlushOptions.js create mode 100644 node_modules/applicationinsights/out/Library/FlushOptions.js.map create mode 100644 node_modules/applicationinsights/out/Library/Functions.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Functions.js create mode 100644 node_modules/applicationinsights/out/Library/Functions.js.map create mode 100644 node_modules/applicationinsights/out/Library/InternalAzureLogger.d.ts create mode 100644 node_modules/applicationinsights/out/Library/InternalAzureLogger.js create mode 100644 node_modules/applicationinsights/out/Library/InternalAzureLogger.js.map create mode 100644 node_modules/applicationinsights/out/Library/JsonConfig.d.ts create mode 100644 node_modules/applicationinsights/out/Library/JsonConfig.js create mode 100644 node_modules/applicationinsights/out/Library/JsonConfig.js.map create mode 100644 node_modules/applicationinsights/out/Library/Logging.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Logging.js create mode 100644 node_modules/applicationinsights/out/Library/Logging.js.map create mode 100644 node_modules/applicationinsights/out/Library/NodeClient.d.ts create mode 100644 node_modules/applicationinsights/out/Library/NodeClient.js create mode 100644 node_modules/applicationinsights/out/Library/NodeClient.js.map create mode 100644 node_modules/applicationinsights/out/Library/PrefixHelper.d.ts create mode 100644 node_modules/applicationinsights/out/Library/PrefixHelper.js create mode 100644 node_modules/applicationinsights/out/Library/PrefixHelper.js.map create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.d.ts create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js.map create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseSender.d.ts create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseSender.js create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseSender.js.map create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseStateManager.d.ts create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseStateManager.js create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseStateManager.js.map create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseUtil.d.ts create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseUtil.js create mode 100644 node_modules/applicationinsights/out/Library/QuickPulseUtil.js.map create mode 100644 node_modules/applicationinsights/out/Library/RequestResponseHeaders.d.ts create mode 100644 node_modules/applicationinsights/out/Library/RequestResponseHeaders.js create mode 100644 node_modules/applicationinsights/out/Library/RequestResponseHeaders.js.map create mode 100644 node_modules/applicationinsights/out/Library/Sender.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Sender.js create mode 100644 node_modules/applicationinsights/out/Library/Sender.js.map create mode 100644 node_modules/applicationinsights/out/Library/SnippetInjectionHelper.d.ts create mode 100644 node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js create mode 100644 node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js.map create mode 100644 node_modules/applicationinsights/out/Library/TelemetryClient.d.ts create mode 100644 node_modules/applicationinsights/out/Library/TelemetryClient.js create mode 100644 node_modules/applicationinsights/out/Library/TelemetryClient.js.map create mode 100644 node_modules/applicationinsights/out/Library/Traceparent.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Traceparent.js create mode 100644 node_modules/applicationinsights/out/Library/Traceparent.js.map create mode 100644 node_modules/applicationinsights/out/Library/Tracestate.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Tracestate.js create mode 100644 node_modules/applicationinsights/out/Library/Tracestate.js.map create mode 100644 node_modules/applicationinsights/out/Library/Util.d.ts create mode 100644 node_modules/applicationinsights/out/Library/Util.js create mode 100644 node_modules/applicationinsights/out/Library/Util.js.map create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.d.ts create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js.map create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.d.ts create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js.map create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.d.ts create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js.map create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.d.ts create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js.map create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/index.d.ts create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/index.js create mode 100644 node_modules/applicationinsights/out/TelemetryProcessors/index.js.map create mode 100644 node_modules/applicationinsights/out/applicationinsights.d.ts create mode 100644 node_modules/applicationinsights/out/applicationinsights.js create mode 100644 node_modules/applicationinsights/out/applicationinsights.js.map create mode 100644 node_modules/applicationinsights/package.json create mode 100644 node_modules/applicationinsights/policheck-exclusions.xml create mode 100644 node_modules/applicationinsights/types/@azure_functions-core/index.d.ts create mode 100644 node_modules/arr-rotate/index.js create mode 100644 node_modules/arr-rotate/license create mode 100644 node_modules/arr-rotate/package.json create mode 100644 node_modules/arr-rotate/readme.md create mode 100644 node_modules/astral-regex/index.d.ts create mode 100644 node_modules/astral-regex/index.js create mode 100644 node_modules/astral-regex/license create mode 100644 node_modules/astral-regex/package.json create mode 100644 node_modules/astral-regex/readme.md create mode 100644 node_modules/async-hook-jl/.eslintrc create mode 100644 node_modules/async-hook-jl/.npmignore create mode 100644 node_modules/async-hook-jl/.travis.yml create mode 100644 node_modules/async-hook-jl/LICENSE.md create mode 100644 node_modules/async-hook-jl/README.md create mode 100644 node_modules/async-hook-jl/async-hook.js create mode 100644 node_modules/async-hook-jl/index.js create mode 100644 node_modules/async-hook-jl/package.json create mode 100644 node_modules/async-hook-jl/patches/next-tick.js create mode 100644 node_modules/async-hook-jl/patches/promise.js create mode 100644 node_modules/async-hook-jl/patches/timers.js create mode 100644 node_modules/async-hook-jl/test/runner.js create mode 100644 node_modules/async-hook-jl/test/test-conflict-match.js create mode 100644 node_modules/async-hook-jl/test/test-conflict-mismatch.js create mode 100644 node_modules/async-hook-jl/test/test-fsaccess-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-fsaccess-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-hooks-remove.js create mode 100644 node_modules/async-hook-jl/test/test-hooks-twice.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-clear-in-callback.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-clear.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-didthrow.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-exception.js create mode 100644 node_modules/async-hook-jl/test/test-immediate-non-function.js create mode 100644 node_modules/async-hook-jl/test/test-interval-clear-in-callback.js create mode 100644 node_modules/async-hook-jl/test/test-interval-clear.js create mode 100644 node_modules/async-hook-jl/test/test-interval-didthrow.js create mode 100644 node_modules/async-hook-jl/test/test-interval-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-interval-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-interval-exception.js create mode 100644 node_modules/async-hook-jl/test/test-interval-non-function.js create mode 100644 node_modules/async-hook-jl/test/test-nexttick-didthrow.js create mode 100644 node_modules/async-hook-jl/test/test-nexttick-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-nexttick-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-nexttick-exception.js create mode 100644 node_modules/async-hook-jl/test/test-nexttick-non-function.js create mode 100644 node_modules/async-hook-jl/test/test-parent.js create mode 100644 node_modules/async-hook-jl/test/test-promise-catch-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-catch-then-chain-fulfilled-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-then-catch-chain-rejected-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-then-fulfilled-chained-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-then-fulfilled-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-then-fulfilled-multiple-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-then-rejected-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-promise-timing.js create mode 100644 node_modules/async-hook-jl/test/test-stackfilter-eval.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-clear-in-callback.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-clear.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-didthrow.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-disabled.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-enabled.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-exception.js create mode 100644 node_modules/async-hook-jl/test/test-timeout-non-function.js create mode 100644 node_modules/async-hook-jl/yarn.lock create mode 100644 node_modules/async-listener/.travis.yml create mode 100644 node_modules/async-listener/LICENSE create mode 100644 node_modules/async-listener/README.md create mode 100644 node_modules/async-listener/es6-wrapped-promise.js create mode 100644 node_modules/async-listener/glue.js create mode 100644 node_modules/async-listener/index.js create mode 100644 node_modules/async-listener/package.json create mode 100644 node_modules/async-listener/test/add-remove.tap.js create mode 100644 node_modules/async-listener/test/connection-handler-disconnects.tap.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-multiple-handled.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-multiple-mix.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-multiple-unhandled.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-net.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-throw-in-after.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-throw-in-before-multiple.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-throw-in-before.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error-throw-in-error.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-error.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-nexttick-remove.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-only-add.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-remove-before.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-remove-inflight-error.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener-remove-inflight.simple.js create mode 100644 node_modules/async-listener/test/core-asynclistener.simple.js create mode 100644 node_modules/async-listener/test/core/core-asynclistener-add-inflight.js create mode 100644 node_modules/async-listener/test/core/core-asynclistener-error-throw-in-before-inflight.js create mode 100644 node_modules/async-listener/test/errors-this-tick.tap.js create mode 100644 node_modules/async-listener/test/fork-listen2-problem.tap.js create mode 100644 node_modules/async-listener/test/fork-listener.js create mode 100644 node_modules/async-listener/test/function-length-preserved.tap.js create mode 100644 node_modules/async-listener/test/handle.tap.js create mode 100644 node_modules/async-listener/test/http-request.tap.js create mode 100644 node_modules/async-listener/test/native-promises.tap.js create mode 100644 node_modules/async-listener/test/no-after-following-error.tap.js create mode 100644 node_modules/async-listener/test/overlapping-nexttick.tap.js create mode 100644 node_modules/async-listener/test/promise-subclass.js create mode 100644 node_modules/async-listener/test/simple-counter-with-io.tap.js create mode 100644 node_modules/async-listener/test/simple-counter.tap.js create mode 100644 node_modules/async-listener/test/simplified-error.simple.js create mode 100644 node_modules/async-listener/test/spawn.tap.js create mode 100644 node_modules/async-listener/test/timers.tap.js create mode 100644 node_modules/async-listener/test/zlib.tap.js create mode 100644 node_modules/asynckit/LICENSE create mode 100644 node_modules/asynckit/README.md create mode 100644 node_modules/asynckit/bench.js create mode 100644 node_modules/asynckit/index.js create mode 100644 node_modules/asynckit/package.json create mode 100644 node_modules/asynckit/parallel.js create mode 100644 node_modules/asynckit/serial.js create mode 100644 node_modules/asynckit/serialOrdered.js create mode 100644 node_modules/asynckit/stream.js create mode 100644 node_modules/auto-bind/index.d.ts create mode 100644 node_modules/auto-bind/index.js create mode 100644 node_modules/auto-bind/license create mode 100644 node_modules/auto-bind/package.json create mode 100644 node_modules/auto-bind/react.d.ts create mode 100644 node_modules/auto-bind/react.js create mode 100644 node_modules/auto-bind/readme.md create mode 100644 node_modules/axios/CHANGELOG.md create mode 100644 node_modules/axios/LICENSE create mode 100644 node_modules/axios/MIGRATION_GUIDE.md create mode 100644 node_modules/axios/README.md create mode 100644 node_modules/axios/SECURITY.md create mode 100644 node_modules/axios/index.d.cts create mode 100644 node_modules/axios/index.d.ts create mode 100644 node_modules/axios/index.js create mode 100644 node_modules/axios/package.json create mode 100644 node_modules/balanced-match/.github/FUNDING.yml create mode 100644 node_modules/balanced-match/LICENSE.md create mode 100644 node_modules/balanced-match/README.md create mode 100644 node_modules/balanced-match/index.js create mode 100644 node_modules/balanced-match/package.json create mode 100644 node_modules/base64-js/LICENSE create mode 100644 node_modules/base64-js/README.md create mode 100644 node_modules/base64-js/base64js.min.js create mode 100644 node_modules/base64-js/index.d.ts create mode 100644 node_modules/base64-js/index.js create mode 100644 node_modules/base64-js/package.json create mode 100644 node_modules/big-integer/BigInteger.d.ts create mode 100644 node_modules/big-integer/BigInteger.js create mode 100644 node_modules/big-integer/BigInteger.min.js create mode 100644 node_modules/big-integer/LICENSE create mode 100644 node_modules/big-integer/README.md create mode 100644 node_modules/big-integer/bower.json create mode 100644 node_modules/big-integer/package.json create mode 100644 node_modules/big-integer/tsconfig.json create mode 100644 node_modules/bl/.github/dependabot.yml create mode 100644 node_modules/bl/.github/workflows/test-and-release.yml create mode 100644 node_modules/bl/BufferList.d.ts create mode 100644 node_modules/bl/BufferList.js create mode 100644 node_modules/bl/CHANGELOG.md create mode 100644 node_modules/bl/LICENSE.md create mode 100644 node_modules/bl/README.md create mode 100644 node_modules/bl/bl.js create mode 100644 node_modules/bl/index.d.ts create mode 100644 node_modules/bl/package.json create mode 100644 node_modules/bl/test/convert.js create mode 100644 node_modules/bl/test/indexOf.js create mode 100644 node_modules/bl/test/isBufferList.js create mode 100644 node_modules/bl/test/test.js create mode 100644 node_modules/brace-expansion/LICENSE create mode 100644 node_modules/brace-expansion/README.md create mode 100644 node_modules/brace-expansion/index.js create mode 100644 node_modules/brace-expansion/package.json create mode 100644 node_modules/broadcast-channel/.github/FUNDING.yml create mode 100644 node_modules/broadcast-channel/.github/README.md create mode 100644 node_modules/broadcast-channel/.github/workflows/main.yml create mode 100644 node_modules/broadcast-channel/CHANGELOG.md create mode 100644 node_modules/broadcast-channel/LICENSE create mode 100644 node_modules/broadcast-channel/README.md create mode 100644 node_modules/broadcast-channel/package.json create mode 100644 node_modules/broadcast-channel/src/broadcast-channel.js create mode 100644 node_modules/broadcast-channel/src/browserify.index.js create mode 100644 node_modules/broadcast-channel/src/index.es5.js create mode 100644 node_modules/broadcast-channel/src/index.js create mode 100644 node_modules/broadcast-channel/src/leader-election.js create mode 100644 node_modules/broadcast-channel/src/method-chooser.js create mode 100644 node_modules/broadcast-channel/src/methods/cookies.js create mode 100644 node_modules/broadcast-channel/src/methods/indexed-db.js create mode 100644 node_modules/broadcast-channel/src/methods/localstorage.js create mode 100644 node_modules/broadcast-channel/src/methods/native.js create mode 100644 node_modules/broadcast-channel/src/methods/node.js create mode 100644 node_modules/broadcast-channel/src/methods/simulate.js create mode 100644 node_modules/broadcast-channel/src/options.js create mode 100644 node_modules/broadcast-channel/src/util.js create mode 100644 node_modules/broadcast-channel/types/broadcast-channel.d.ts create mode 100644 node_modules/broadcast-channel/types/index.d.ts create mode 100644 node_modules/broadcast-channel/types/leader-election.d.ts create mode 100644 node_modules/buffer/AUTHORS.md create mode 100644 node_modules/buffer/LICENSE create mode 100644 node_modules/buffer/README.md create mode 100644 node_modules/buffer/index.d.ts create mode 100644 node_modules/buffer/index.js create mode 100644 node_modules/buffer/package.json create mode 100644 node_modules/cardinal/.npmignore create mode 100644 node_modules/cardinal/.travis.yml create mode 100644 node_modules/cardinal/LICENSE create mode 100644 node_modules/cardinal/README.md create mode 100755 node_modules/cardinal/bin/cdl.js create mode 100644 node_modules/cardinal/cardinal.js create mode 100644 node_modules/cardinal/examples/.cardinalrc create mode 100644 node_modules/cardinal/examples/README.md create mode 100644 node_modules/cardinal/examples/git-diff.txt create mode 100644 node_modules/cardinal/examples/highlight-diff.js create mode 100644 node_modules/cardinal/examples/highlight-json.js create mode 100644 node_modules/cardinal/examples/highlight-self-hide-semicolons.js create mode 100644 node_modules/cardinal/examples/highlight-self.js create mode 100644 node_modules/cardinal/examples/highlight-string.js create mode 100644 node_modules/cardinal/package.json create mode 100644 node_modules/cardinal/settings.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-block-comment.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-file-async.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-file-sync.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-json-file-async.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-json-file-sync.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-json.js create mode 100644 node_modules/cardinal/test/cardinal-highlight-string.js create mode 100644 node_modules/cardinal/test/cardinal-smoke.js create mode 100644 node_modules/cardinal/test/fixtures/block-comment.js create mode 100644 node_modules/cardinal/test/fixtures/custom.js create mode 100644 node_modules/cardinal/test/fixtures/foo-with-errors.js create mode 100644 node_modules/cardinal/test/fixtures/foo.js create mode 100644 node_modules/cardinal/test/fixtures/json.json create mode 100644 node_modules/cardinal/test/fixtures/svn-diff.txt create mode 100644 node_modules/cardinal/test/settings.js create mode 100644 node_modules/cardinal/test/themes.js create mode 100644 node_modules/cardinal/themes/README.md create mode 100644 node_modules/cardinal/themes/default.js create mode 100644 node_modules/cardinal/themes/empty.js create mode 100644 node_modules/cardinal/themes/hide-semicolons.js create mode 100644 node_modules/cardinal/themes/jq.js create mode 100644 node_modules/cardinal/themes/tomorrow-night.js create mode 100644 node_modules/cardinal/utl.js create mode 100644 node_modules/chalk/license create mode 100644 node_modules/chalk/package.json create mode 100644 node_modules/chalk/readme.md create mode 100644 node_modules/chalk/source/index.d.ts create mode 100644 node_modules/chalk/source/index.js create mode 100644 node_modules/chalk/source/utilities.js create mode 100644 node_modules/chalk/source/vendor/ansi-styles/index.d.ts create mode 100644 node_modules/chalk/source/vendor/ansi-styles/index.js create mode 100644 node_modules/chalk/source/vendor/supports-color/browser.d.ts create mode 100644 node_modules/chalk/source/vendor/supports-color/browser.js create mode 100644 node_modules/chalk/source/vendor/supports-color/index.d.ts create mode 100644 node_modules/chalk/source/vendor/supports-color/index.js create mode 100644 node_modules/chardet/.travis.yml create mode 100644 node_modules/chardet/LICENSE create mode 100644 node_modules/chardet/README.md create mode 100644 node_modules/chardet/encoding/iso2022.js create mode 100644 node_modules/chardet/encoding/mbcs.js create mode 100644 node_modules/chardet/encoding/sbcs.js create mode 100644 node_modules/chardet/encoding/unicode.js create mode 100644 node_modules/chardet/encoding/utf8.js create mode 100644 node_modules/chardet/index.js create mode 100644 node_modules/chardet/match.js create mode 100644 node_modules/chardet/package.json create mode 100644 node_modules/ci-info/CHANGELOG.md create mode 100644 node_modules/ci-info/LICENSE create mode 100644 node_modules/ci-info/README.md create mode 100644 node_modules/ci-info/index.js create mode 100644 node_modules/ci-info/package.json create mode 100644 node_modules/ci-info/vendors.json create mode 100644 node_modules/cli-boxes/boxes.json create mode 100644 node_modules/cli-boxes/index.d.ts create mode 100644 node_modules/cli-boxes/index.js create mode 100644 node_modules/cli-boxes/license create mode 100644 node_modules/cli-boxes/package.json create mode 100644 node_modules/cli-boxes/readme.md create mode 100644 node_modules/cli-cursor/index.d.ts create mode 100644 node_modules/cli-cursor/index.js create mode 100644 node_modules/cli-cursor/license create mode 100644 node_modules/cli-cursor/package.json create mode 100644 node_modules/cli-cursor/readme.md create mode 100644 node_modules/cli-highlight/LICENSE.txt create mode 100644 node_modules/cli-highlight/README.md create mode 100755 node_modules/cli-highlight/bin/highlight create mode 100644 node_modules/cli-highlight/node_modules/chalk/index.d.ts create mode 100644 node_modules/cli-highlight/node_modules/chalk/license create mode 100644 node_modules/cli-highlight/node_modules/chalk/package.json create mode 100644 node_modules/cli-highlight/node_modules/chalk/readme.md create mode 100644 node_modules/cli-highlight/node_modules/chalk/source/index.js create mode 100644 node_modules/cli-highlight/node_modules/chalk/source/templates.js create mode 100644 node_modules/cli-highlight/node_modules/chalk/source/util.js create mode 100644 node_modules/cli-highlight/package.json create mode 100644 node_modules/cli-spinners/index.d.ts create mode 100644 node_modules/cli-spinners/index.js create mode 100644 node_modules/cli-spinners/license create mode 100644 node_modules/cli-spinners/package.json create mode 100644 node_modules/cli-spinners/readme.md create mode 100644 node_modules/cli-spinners/spinners.json create mode 100644 node_modules/cli-table3/CHANGELOG.md create mode 100644 node_modules/cli-table3/LICENSE create mode 100644 node_modules/cli-table3/README.md create mode 100644 node_modules/cli-table3/index.d.ts create mode 100644 node_modules/cli-table3/index.js create mode 100644 node_modules/cli-table3/package.json create mode 100644 node_modules/cli-table3/src/cell.js create mode 100644 node_modules/cli-table3/src/debug.js create mode 100644 node_modules/cli-table3/src/layout-manager.js create mode 100644 node_modules/cli-table3/src/table.js create mode 100644 node_modules/cli-table3/src/utils.js create mode 100644 node_modules/cli-truncate/index.d.ts create mode 100644 node_modules/cli-truncate/index.js create mode 100644 node_modules/cli-truncate/license create mode 100644 node_modules/cli-truncate/package.json create mode 100644 node_modules/cli-truncate/readme.md create mode 100644 node_modules/cli-width/.github/FUNDING.yml create mode 100644 node_modules/cli-width/.github/workflows/node.js.yml create mode 100644 node_modules/cli-width/.prettierrc create mode 100644 node_modules/cli-width/LICENSE create mode 100644 node_modules/cli-width/README.md create mode 100644 node_modules/cli-width/index.js create mode 100644 node_modules/cli-width/package.json create mode 100644 node_modules/cliui/CHANGELOG.md create mode 100644 node_modules/cliui/LICENSE.txt create mode 100644 node_modules/cliui/README.md create mode 100644 node_modules/cliui/index.mjs create mode 100644 node_modules/cliui/node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/cliui/node_modules/ansi-regex/index.js create mode 100644 node_modules/cliui/node_modules/ansi-regex/license create mode 100644 node_modules/cliui/node_modules/ansi-regex/package.json create mode 100644 node_modules/cliui/node_modules/ansi-regex/readme.md create mode 100644 node_modules/cliui/node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/cliui/node_modules/strip-ansi/index.js create mode 100644 node_modules/cliui/node_modules/strip-ansi/license create mode 100644 node_modules/cliui/node_modules/strip-ansi/package.json create mode 100644 node_modules/cliui/node_modules/strip-ansi/readme.md create mode 100755 node_modules/cliui/node_modules/wrap-ansi/index.js create mode 100644 node_modules/cliui/node_modules/wrap-ansi/license create mode 100644 node_modules/cliui/node_modules/wrap-ansi/package.json create mode 100644 node_modules/cliui/node_modules/wrap-ansi/readme.md create mode 100644 node_modules/cliui/package.json create mode 100644 node_modules/clone/.npmignore create mode 100644 node_modules/clone/LICENSE create mode 100644 node_modules/clone/README.md create mode 100644 node_modules/clone/clone.iml create mode 100644 node_modules/clone/clone.js create mode 100644 node_modules/clone/package.json create mode 100644 node_modules/cls-hooked/CHANGELOG.md create mode 100644 node_modules/cls-hooked/LICENSE create mode 100644 node_modules/cls-hooked/README.md create mode 100644 node_modules/cls-hooked/context-legacy.js create mode 100644 node_modules/cls-hooked/context.js create mode 100644 node_modules/cls-hooked/index.js create mode 100644 node_modules/cls-hooked/package.json create mode 100644 node_modules/code-excerpt/index.d.ts create mode 100644 node_modules/code-excerpt/index.js create mode 100644 node_modules/code-excerpt/license create mode 100644 node_modules/code-excerpt/package.json create mode 100644 node_modules/code-excerpt/readme.md create mode 100644 node_modules/color-convert/CHANGELOG.md create mode 100644 node_modules/color-convert/LICENSE create mode 100644 node_modules/color-convert/README.md create mode 100644 node_modules/color-convert/conversions.js create mode 100644 node_modules/color-convert/index.js create mode 100644 node_modules/color-convert/package.json create mode 100644 node_modules/color-convert/route.js create mode 100644 node_modules/color-name/LICENSE create mode 100644 node_modules/color-name/README.md create mode 100644 node_modules/color-name/index.js create mode 100644 node_modules/color-name/package.json create mode 100644 node_modules/combined-stream/License create mode 100644 node_modules/combined-stream/Readme.md create mode 100644 node_modules/combined-stream/package.json create mode 100644 node_modules/combined-stream/yarn.lock create mode 100644 node_modules/commander/LICENSE create mode 100644 node_modules/commander/Readme.md create mode 100644 node_modules/commander/esm.mjs create mode 100644 node_modules/commander/index.js create mode 100644 node_modules/commander/package-support.json create mode 100644 node_modules/commander/package.json create mode 100644 node_modules/commander/typings/index.d.ts create mode 100644 node_modules/concat-map/.travis.yml create mode 100644 node_modules/concat-map/LICENSE create mode 100644 node_modules/concat-map/README.markdown create mode 100644 node_modules/concat-map/example/map.js create mode 100644 node_modules/concat-map/index.js create mode 100644 node_modules/concat-map/package.json create mode 100644 node_modules/concat-map/test/map.js create mode 100644 node_modules/continuation-local-storage/.eslintrc create mode 100644 node_modules/continuation-local-storage/.travis.yml create mode 100644 node_modules/continuation-local-storage/CHANGELOG.md create mode 100644 node_modules/continuation-local-storage/LICENSE create mode 100644 node_modules/continuation-local-storage/README.md create mode 100644 node_modules/continuation-local-storage/context.js create mode 100644 node_modules/continuation-local-storage/package.json create mode 100644 node_modules/continuation-local-storage/test/async-context.tap.js create mode 100644 node_modules/continuation-local-storage/test/async-no-run-queue-multiple.tap.js create mode 100644 node_modules/continuation-local-storage/test/bind-emitter.tap.js create mode 100644 node_modules/continuation-local-storage/test/bind.tap.js create mode 100644 node_modules/continuation-local-storage/test/crypto.tap.js create mode 100644 node_modules/continuation-local-storage/test/dns.tap.js create mode 100644 node_modules/continuation-local-storage/test/error-handling.tap.js create mode 100644 node_modules/continuation-local-storage/test/fs.tap.js create mode 100644 node_modules/continuation-local-storage/test/interleave-contexts.tap.js create mode 100644 node_modules/continuation-local-storage/test/monkeypatching.tap.js create mode 100644 node_modules/continuation-local-storage/test/namespaces.tap.js create mode 100644 node_modules/continuation-local-storage/test/nesting.tap.js create mode 100644 node_modules/continuation-local-storage/test/net-events.tap.js create mode 100644 node_modules/continuation-local-storage/test/promises.tap.js create mode 100644 node_modules/continuation-local-storage/test/proper-exit.tap.js create mode 100644 node_modules/continuation-local-storage/test/run-and-return.tap.js create mode 100644 node_modules/continuation-local-storage/test/simple.tap.js create mode 100644 node_modules/continuation-local-storage/test/timers.tap.js create mode 100644 node_modules/continuation-local-storage/test/tracer-scenarios.tap.js create mode 100644 node_modules/continuation-local-storage/test/zlib.tap.js create mode 100644 node_modules/convert-to-spaces/index.js create mode 100644 node_modules/convert-to-spaces/license create mode 100644 node_modules/convert-to-spaces/package.json create mode 100644 node_modules/convert-to-spaces/readme.md create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/common.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/defaults/LICENSE create mode 100644 node_modules/defaults/README.md create mode 100644 node_modules/defaults/index.js create mode 100644 node_modules/defaults/package.json create mode 100644 node_modules/defaults/test.js create mode 100644 node_modules/delayed-stream/.npmignore create mode 100644 node_modules/delayed-stream/License create mode 100644 node_modules/delayed-stream/Makefile create mode 100644 node_modules/delayed-stream/Readme.md create mode 100644 node_modules/delayed-stream/package.json create mode 100644 node_modules/detect-node/LICENSE create mode 100644 node_modules/detect-node/Readme.md create mode 100644 node_modules/detect-node/browser.js create mode 100644 node_modules/detect-node/index.esm.js create mode 100644 node_modules/detect-node/index.js create mode 100644 node_modules/detect-node/package.json create mode 100644 node_modules/diagnostic-channel-publishers/LICENSE create mode 100644 node_modules/diagnostic-channel-publishers/README.md create mode 100644 node_modules/diagnostic-channel-publishers/package.json create mode 100644 node_modules/diagnostic-channel/LICENSE create mode 100644 node_modules/diagnostic-channel/README.md create mode 100644 node_modules/diagnostic-channel/package.json create mode 100644 node_modules/eastasianwidth/README.md create mode 100644 node_modules/eastasianwidth/eastasianwidth.js create mode 100644 node_modules/eastasianwidth/package.json create mode 100644 node_modules/emitter-listener/.travis.yml create mode 100644 node_modules/emitter-listener/README.md create mode 100644 node_modules/emitter-listener/listener.js create mode 100644 node_modules/emitter-listener/package.json create mode 100644 node_modules/emitter-listener/test/basic.tap.js create mode 100644 node_modules/emoji-regex/LICENSE-MIT.txt create mode 100644 node_modules/emoji-regex/README.md create mode 100644 node_modules/emoji-regex/es2015/index.js create mode 100644 node_modules/emoji-regex/es2015/text.js create mode 100644 node_modules/emoji-regex/index.d.ts create mode 100644 node_modules/emoji-regex/index.js create mode 100644 node_modules/emoji-regex/package.json create mode 100644 node_modules/emoji-regex/text.js create mode 100644 node_modules/escalade/index.d.ts create mode 100644 node_modules/escalade/license create mode 100644 node_modules/escalade/package.json create mode 100644 node_modules/escalade/readme.md create mode 100644 node_modules/escalade/sync/index.d.ts create mode 100644 node_modules/escalade/sync/index.js create mode 100644 node_modules/escalade/sync/index.mjs create mode 100644 node_modules/escape-string-regexp/index.js create mode 100644 node_modules/escape-string-regexp/license create mode 100644 node_modules/escape-string-regexp/package.json create mode 100644 node_modules/escape-string-regexp/readme.md create mode 100644 node_modules/esprima/ChangeLog create mode 100644 node_modules/esprima/LICENSE.BSD create mode 100644 node_modules/esprima/README.md create mode 100755 node_modules/esprima/bin/esparse.js create mode 100755 node_modules/esprima/bin/esvalidate.js create mode 100644 node_modules/esprima/package.json create mode 100644 node_modules/external-editor/LICENSE create mode 100644 node_modules/external-editor/README.md create mode 100644 node_modules/external-editor/example_async.js create mode 100644 node_modules/external-editor/example_sync.js create mode 100644 node_modules/external-editor/main/errors/CreateFileError.d.ts create mode 100644 node_modules/external-editor/main/errors/CreateFileError.js create mode 100644 node_modules/external-editor/main/errors/LaunchEditorError.d.ts create mode 100644 node_modules/external-editor/main/errors/LaunchEditorError.js create mode 100644 node_modules/external-editor/main/errors/ReadFileError.d.ts create mode 100644 node_modules/external-editor/main/errors/ReadFileError.js create mode 100644 node_modules/external-editor/main/errors/RemoveFileError.d.ts create mode 100644 node_modules/external-editor/main/errors/RemoveFileError.js create mode 100644 node_modules/external-editor/main/index.d.ts create mode 100644 node_modules/external-editor/main/index.js create mode 100644 node_modules/external-editor/package.json create mode 100644 node_modules/figures/index.d.ts create mode 100644 node_modules/figures/index.js create mode 100644 node_modules/figures/license create mode 100644 node_modules/figures/package.json create mode 100644 node_modules/figures/readme.md create mode 100644 node_modules/follow-redirects/LICENSE create mode 100644 node_modules/follow-redirects/README.md create mode 100644 node_modules/follow-redirects/debug.js create mode 100644 node_modules/follow-redirects/http.js create mode 100644 node_modules/follow-redirects/https.js create mode 100644 node_modules/follow-redirects/index.js create mode 100644 node_modules/follow-redirects/package.json create mode 100644 node_modules/form-data/License create mode 100644 node_modules/form-data/README.md.bak create mode 100644 node_modules/form-data/Readme.md create mode 100644 node_modules/form-data/index.d.ts create mode 100644 node_modules/form-data/package.json create mode 100644 node_modules/fs.realpath/LICENSE create mode 100644 node_modules/fs.realpath/README.md create mode 100644 node_modules/fs.realpath/index.js create mode 100644 node_modules/fs.realpath/old.js create mode 100644 node_modules/fs.realpath/package.json create mode 100644 node_modules/get-caller-file/LICENSE.md create mode 100644 node_modules/get-caller-file/README.md create mode 100644 node_modules/get-caller-file/index.d.ts create mode 100644 node_modules/get-caller-file/index.js create mode 100644 node_modules/get-caller-file/index.js.map create mode 100644 node_modules/get-caller-file/package.json create mode 100644 node_modules/get-stream/buffer-stream.js create mode 100644 node_modules/get-stream/index.d.ts create mode 100644 node_modules/get-stream/index.js create mode 100644 node_modules/get-stream/license create mode 100644 node_modules/get-stream/package.json create mode 100644 node_modules/get-stream/readme.md create mode 100644 node_modules/glob/LICENSE create mode 100644 node_modules/glob/README.md create mode 100644 node_modules/glob/common.js create mode 100644 node_modules/glob/glob.js create mode 100644 node_modules/glob/package.json create mode 100644 node_modules/glob/sync.js create mode 100644 node_modules/has-flag/index.d.ts create mode 100644 node_modules/has-flag/index.js create mode 100644 node_modules/has-flag/license create mode 100644 node_modules/has-flag/package.json create mode 100644 node_modules/has-flag/readme.md create mode 100644 node_modules/highlight.js/LICENSE create mode 100644 node_modules/highlight.js/README.md create mode 100644 node_modules/highlight.js/package.json create mode 100644 node_modules/highlight.js/scss/a11y-dark.scss create mode 100644 node_modules/highlight.js/scss/a11y-light.scss create mode 100644 node_modules/highlight.js/scss/agate.scss create mode 100644 node_modules/highlight.js/scss/an-old-hope.scss create mode 100644 node_modules/highlight.js/scss/androidstudio.scss create mode 100644 node_modules/highlight.js/scss/arduino-light.scss create mode 100644 node_modules/highlight.js/scss/arta.scss create mode 100644 node_modules/highlight.js/scss/ascetic.scss create mode 100644 node_modules/highlight.js/scss/atelier-cave-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-cave-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-dune-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-dune-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-estuary-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-estuary-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-forest-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-forest-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-heath-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-heath-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-lakeside-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-lakeside-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-plateau-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-plateau-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-savanna-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-savanna-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-seaside-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-seaside-light.scss create mode 100644 node_modules/highlight.js/scss/atelier-sulphurpool-dark.scss create mode 100644 node_modules/highlight.js/scss/atelier-sulphurpool-light.scss create mode 100644 node_modules/highlight.js/scss/atom-one-dark-reasonable.scss create mode 100644 node_modules/highlight.js/scss/atom-one-dark.scss create mode 100644 node_modules/highlight.js/scss/atom-one-light.scss create mode 100644 node_modules/highlight.js/scss/brown-paper.scss create mode 100644 node_modules/highlight.js/scss/brown-papersq.png create mode 100644 node_modules/highlight.js/scss/codepen-embed.scss create mode 100644 node_modules/highlight.js/scss/color-brewer.scss create mode 100644 node_modules/highlight.js/scss/darcula.scss create mode 100644 node_modules/highlight.js/scss/dark.scss create mode 100644 node_modules/highlight.js/scss/default.scss create mode 100644 node_modules/highlight.js/scss/docco.scss create mode 100644 node_modules/highlight.js/scss/dracula.scss create mode 100644 node_modules/highlight.js/scss/far.scss create mode 100644 node_modules/highlight.js/scss/foundation.scss create mode 100644 node_modules/highlight.js/scss/github-gist.scss create mode 100644 node_modules/highlight.js/scss/github.scss create mode 100644 node_modules/highlight.js/scss/gml.scss create mode 100644 node_modules/highlight.js/scss/googlecode.scss create mode 100644 node_modules/highlight.js/scss/gradient-dark.scss create mode 100644 node_modules/highlight.js/scss/gradient-light.scss create mode 100644 node_modules/highlight.js/scss/grayscale.scss create mode 100644 node_modules/highlight.js/scss/gruvbox-dark.scss create mode 100644 node_modules/highlight.js/scss/gruvbox-light.scss create mode 100644 node_modules/highlight.js/scss/hopscotch.scss create mode 100644 node_modules/highlight.js/scss/hybrid.scss create mode 100644 node_modules/highlight.js/scss/idea.scss create mode 100644 node_modules/highlight.js/scss/ir-black.scss create mode 100644 node_modules/highlight.js/scss/isbl-editor-dark.scss create mode 100644 node_modules/highlight.js/scss/isbl-editor-light.scss create mode 100644 node_modules/highlight.js/scss/kimbie.dark.scss create mode 100644 node_modules/highlight.js/scss/kimbie.light.scss create mode 100644 node_modules/highlight.js/scss/lightfair.scss create mode 100644 node_modules/highlight.js/scss/lioshi.scss create mode 100644 node_modules/highlight.js/scss/magula.scss create mode 100644 node_modules/highlight.js/scss/mono-blue.scss create mode 100644 node_modules/highlight.js/scss/monokai-sublime.scss create mode 100644 node_modules/highlight.js/scss/monokai.scss create mode 100644 node_modules/highlight.js/scss/night-owl.scss create mode 100644 node_modules/highlight.js/scss/nnfx-dark.scss create mode 100644 node_modules/highlight.js/scss/nnfx.scss create mode 100644 node_modules/highlight.js/scss/nord.scss create mode 100644 node_modules/highlight.js/scss/obsidian.scss create mode 100644 node_modules/highlight.js/scss/ocean.scss create mode 100644 node_modules/highlight.js/scss/paraiso-dark.scss create mode 100644 node_modules/highlight.js/scss/paraiso-light.scss create mode 100644 node_modules/highlight.js/scss/pojoaque.jpg create mode 100644 node_modules/highlight.js/scss/pojoaque.scss create mode 100644 node_modules/highlight.js/scss/purebasic.scss create mode 100644 node_modules/highlight.js/scss/qtcreator_dark.scss create mode 100644 node_modules/highlight.js/scss/qtcreator_light.scss create mode 100644 node_modules/highlight.js/scss/railscasts.scss create mode 100644 node_modules/highlight.js/scss/rainbow.scss create mode 100644 node_modules/highlight.js/scss/routeros.scss create mode 100644 node_modules/highlight.js/scss/school-book.png create mode 100644 node_modules/highlight.js/scss/school-book.scss create mode 100644 node_modules/highlight.js/scss/shades-of-purple.scss create mode 100644 node_modules/highlight.js/scss/solarized-dark.scss create mode 100644 node_modules/highlight.js/scss/solarized-light.scss create mode 100644 node_modules/highlight.js/scss/srcery.scss create mode 100644 node_modules/highlight.js/scss/stackoverflow-dark.scss create mode 100644 node_modules/highlight.js/scss/stackoverflow-light.scss create mode 100644 node_modules/highlight.js/scss/sunburst.scss create mode 100644 node_modules/highlight.js/scss/tomorrow-night-blue.scss create mode 100644 node_modules/highlight.js/scss/tomorrow-night-bright.scss create mode 100644 node_modules/highlight.js/scss/tomorrow-night-eighties.scss create mode 100644 node_modules/highlight.js/scss/tomorrow-night.scss create mode 100644 node_modules/highlight.js/scss/tomorrow.scss create mode 100644 node_modules/highlight.js/scss/vs.scss create mode 100644 node_modules/highlight.js/scss/vs2015.scss create mode 100644 node_modules/highlight.js/scss/xcode.scss create mode 100644 node_modules/highlight.js/scss/xt256.scss create mode 100644 node_modules/highlight.js/scss/zenburn.scss create mode 100644 node_modules/highlight.js/styles/a11y-dark.css create mode 100644 node_modules/highlight.js/styles/a11y-light.css create mode 100644 node_modules/highlight.js/styles/agate.css create mode 100644 node_modules/highlight.js/styles/an-old-hope.css create mode 100644 node_modules/highlight.js/styles/androidstudio.css create mode 100644 node_modules/highlight.js/styles/arduino-light.css create mode 100644 node_modules/highlight.js/styles/arta.css create mode 100644 node_modules/highlight.js/styles/ascetic.css create mode 100644 node_modules/highlight.js/styles/atelier-cave-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-cave-light.css create mode 100644 node_modules/highlight.js/styles/atelier-dune-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-dune-light.css create mode 100644 node_modules/highlight.js/styles/atelier-estuary-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-estuary-light.css create mode 100644 node_modules/highlight.js/styles/atelier-forest-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-forest-light.css create mode 100644 node_modules/highlight.js/styles/atelier-heath-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-heath-light.css create mode 100644 node_modules/highlight.js/styles/atelier-lakeside-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-lakeside-light.css create mode 100644 node_modules/highlight.js/styles/atelier-plateau-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-plateau-light.css create mode 100644 node_modules/highlight.js/styles/atelier-savanna-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-savanna-light.css create mode 100644 node_modules/highlight.js/styles/atelier-seaside-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-seaside-light.css create mode 100644 node_modules/highlight.js/styles/atelier-sulphurpool-dark.css create mode 100644 node_modules/highlight.js/styles/atelier-sulphurpool-light.css create mode 100644 node_modules/highlight.js/styles/atom-one-dark-reasonable.css create mode 100644 node_modules/highlight.js/styles/atom-one-dark.css create mode 100644 node_modules/highlight.js/styles/atom-one-light.css create mode 100644 node_modules/highlight.js/styles/brown-paper.css create mode 100644 node_modules/highlight.js/styles/brown-papersq.png create mode 100644 node_modules/highlight.js/styles/codepen-embed.css create mode 100644 node_modules/highlight.js/styles/color-brewer.css create mode 100644 node_modules/highlight.js/styles/darcula.css create mode 100644 node_modules/highlight.js/styles/dark.css create mode 100644 node_modules/highlight.js/styles/default.css create mode 100644 node_modules/highlight.js/styles/docco.css create mode 100644 node_modules/highlight.js/styles/dracula.css create mode 100644 node_modules/highlight.js/styles/far.css create mode 100644 node_modules/highlight.js/styles/foundation.css create mode 100644 node_modules/highlight.js/styles/github-gist.css create mode 100644 node_modules/highlight.js/styles/github.css create mode 100644 node_modules/highlight.js/styles/gml.css create mode 100644 node_modules/highlight.js/styles/googlecode.css create mode 100644 node_modules/highlight.js/styles/gradient-dark.css create mode 100644 node_modules/highlight.js/styles/gradient-light.css create mode 100644 node_modules/highlight.js/styles/grayscale.css create mode 100644 node_modules/highlight.js/styles/gruvbox-dark.css create mode 100644 node_modules/highlight.js/styles/gruvbox-light.css create mode 100644 node_modules/highlight.js/styles/hopscotch.css create mode 100644 node_modules/highlight.js/styles/hybrid.css create mode 100644 node_modules/highlight.js/styles/idea.css create mode 100644 node_modules/highlight.js/styles/ir-black.css create mode 100644 node_modules/highlight.js/styles/isbl-editor-dark.css create mode 100644 node_modules/highlight.js/styles/isbl-editor-light.css create mode 100644 node_modules/highlight.js/styles/kimbie.dark.css create mode 100644 node_modules/highlight.js/styles/kimbie.light.css create mode 100644 node_modules/highlight.js/styles/lightfair.css create mode 100644 node_modules/highlight.js/styles/lioshi.css create mode 100644 node_modules/highlight.js/styles/magula.css create mode 100644 node_modules/highlight.js/styles/mono-blue.css create mode 100644 node_modules/highlight.js/styles/monokai-sublime.css create mode 100644 node_modules/highlight.js/styles/monokai.css create mode 100644 node_modules/highlight.js/styles/night-owl.css create mode 100644 node_modules/highlight.js/styles/nnfx-dark.css create mode 100644 node_modules/highlight.js/styles/nnfx.css create mode 100644 node_modules/highlight.js/styles/nord.css create mode 100644 node_modules/highlight.js/styles/obsidian.css create mode 100644 node_modules/highlight.js/styles/ocean.css create mode 100644 node_modules/highlight.js/styles/paraiso-dark.css create mode 100644 node_modules/highlight.js/styles/paraiso-light.css create mode 100644 node_modules/highlight.js/styles/pojoaque.css create mode 100644 node_modules/highlight.js/styles/pojoaque.jpg create mode 100644 node_modules/highlight.js/styles/purebasic.css create mode 100644 node_modules/highlight.js/styles/qtcreator_dark.css create mode 100644 node_modules/highlight.js/styles/qtcreator_light.css create mode 100644 node_modules/highlight.js/styles/railscasts.css create mode 100644 node_modules/highlight.js/styles/rainbow.css create mode 100644 node_modules/highlight.js/styles/routeros.css create mode 100644 node_modules/highlight.js/styles/school-book.css create mode 100644 node_modules/highlight.js/styles/school-book.png create mode 100644 node_modules/highlight.js/styles/shades-of-purple.css create mode 100644 node_modules/highlight.js/styles/solarized-dark.css create mode 100644 node_modules/highlight.js/styles/solarized-light.css create mode 100644 node_modules/highlight.js/styles/srcery.css create mode 100644 node_modules/highlight.js/styles/stackoverflow-dark.css create mode 100644 node_modules/highlight.js/styles/stackoverflow-light.css create mode 100644 node_modules/highlight.js/styles/sunburst.css create mode 100644 node_modules/highlight.js/styles/tomorrow-night-blue.css create mode 100644 node_modules/highlight.js/styles/tomorrow-night-bright.css create mode 100644 node_modules/highlight.js/styles/tomorrow-night-eighties.css create mode 100644 node_modules/highlight.js/styles/tomorrow-night.css create mode 100644 node_modules/highlight.js/styles/tomorrow.css create mode 100644 node_modules/highlight.js/styles/vs.css create mode 100644 node_modules/highlight.js/styles/vs2015.css create mode 100644 node_modules/highlight.js/styles/xcode.css create mode 100644 node_modules/highlight.js/styles/xt256.css create mode 100644 node_modules/highlight.js/styles/zenburn.css create mode 100644 node_modules/highlight.js/types/index.d.ts create mode 100644 node_modules/http-proxy-agent/README.md create mode 100644 node_modules/http-proxy-agent/package.json create mode 100644 node_modules/https-proxy-agent/README.md create mode 100644 node_modules/https-proxy-agent/package.json create mode 100644 node_modules/iconv-lite/Changelog.md create mode 100644 node_modules/iconv-lite/LICENSE create mode 100644 node_modules/iconv-lite/README.md create mode 100644 node_modules/iconv-lite/encodings/dbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/dbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/index.js create mode 100644 node_modules/iconv-lite/encodings/internal.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-codec.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data-generated.js create mode 100644 node_modules/iconv-lite/encodings/sbcs-data.js create mode 100644 node_modules/iconv-lite/encodings/tables/big5-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp936.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp949.json create mode 100644 node_modules/iconv-lite/encodings/tables/cp950.json create mode 100644 node_modules/iconv-lite/encodings/tables/eucjp.json create mode 100644 node_modules/iconv-lite/encodings/tables/gb18030-ranges.json create mode 100644 node_modules/iconv-lite/encodings/tables/gbk-added.json create mode 100644 node_modules/iconv-lite/encodings/tables/shiftjis.json create mode 100644 node_modules/iconv-lite/encodings/utf16.js create mode 100644 node_modules/iconv-lite/encodings/utf7.js create mode 100644 node_modules/iconv-lite/package.json create mode 100644 node_modules/ieee754/LICENSE create mode 100644 node_modules/ieee754/README.md create mode 100644 node_modules/ieee754/index.d.ts create mode 100644 node_modules/ieee754/index.js create mode 100644 node_modules/ieee754/package.json create mode 100644 node_modules/immer/LICENSE create mode 100644 node_modules/immer/package.json create mode 100644 node_modules/immer/readme.md create mode 100644 node_modules/immer/src/core/current.ts create mode 100644 node_modules/immer/src/core/finalize.ts create mode 100644 node_modules/immer/src/core/immerClass.ts create mode 100644 node_modules/immer/src/core/proxy.ts create mode 100644 node_modules/immer/src/core/scope.ts create mode 100644 node_modules/immer/src/immer.ts create mode 100644 node_modules/immer/src/internal.ts create mode 100644 node_modules/immer/src/plugins/all.ts create mode 100644 node_modules/immer/src/plugins/es5.ts create mode 100644 node_modules/immer/src/plugins/mapset.ts create mode 100644 node_modules/immer/src/plugins/patches.ts create mode 100644 node_modules/immer/src/types/globals.d.ts create mode 100644 node_modules/immer/src/types/index.js.flow create mode 100644 node_modules/immer/src/types/types-external.ts create mode 100644 node_modules/immer/src/types/types-internal.ts create mode 100644 node_modules/immer/src/utils/common.ts create mode 100644 node_modules/immer/src/utils/env.ts create mode 100644 node_modules/immer/src/utils/errors.ts create mode 100644 node_modules/immer/src/utils/plugins.ts create mode 100644 node_modules/indent-string/index.d.ts create mode 100644 node_modules/indent-string/index.js create mode 100644 node_modules/indent-string/license create mode 100644 node_modules/indent-string/package.json create mode 100644 node_modules/indent-string/readme.md create mode 100644 node_modules/inflight/LICENSE create mode 100644 node_modules/inflight/README.md create mode 100644 node_modules/inflight/inflight.js create mode 100644 node_modules/inflight/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/ink-divider/license create mode 100644 node_modules/ink-divider/package.json create mode 100644 node_modules/ink-divider/readme.md create mode 100644 node_modules/ink-select-input/license create mode 100644 node_modules/ink-select-input/package.json create mode 100644 node_modules/ink-select-input/readme.md create mode 100644 node_modules/ink-spinner/license create mode 100644 node_modules/ink-spinner/package.json create mode 100644 node_modules/ink-spinner/readme.md create mode 100644 node_modules/ink-text-input/license create mode 100644 node_modules/ink-text-input/node_modules/chalk/index.d.ts create mode 100644 node_modules/ink-text-input/node_modules/chalk/license create mode 100644 node_modules/ink-text-input/node_modules/chalk/package.json create mode 100644 node_modules/ink-text-input/node_modules/chalk/readme.md create mode 100644 node_modules/ink-text-input/node_modules/chalk/source/index.js create mode 100644 node_modules/ink-text-input/node_modules/chalk/source/templates.js create mode 100644 node_modules/ink-text-input/node_modules/chalk/source/util.js create mode 100644 node_modules/ink-text-input/node_modules/type-fest/index.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/license create mode 100644 node_modules/ink-text-input/node_modules/type-fest/package.json create mode 100644 node_modules/ink-text-input/node_modules/type-fest/readme.md create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/async-return-type.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/basic.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/conditional-except.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/conditional-keys.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/conditional-pick.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/except.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/fixed-length-array.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/literal-union.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/merge-exclusive.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/merge.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/mutable.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/opaque.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/package-json.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/partial-deep.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/promisable.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/promise-value.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/readonly-deep.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/require-at-least-one.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/require-exactly-one.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/set-optional.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/set-required.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/stringified.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/tsconfig-json.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/union-to-intersection.d.ts create mode 100644 node_modules/ink-text-input/node_modules/type-fest/source/value-of.d.ts create mode 100644 node_modules/ink-text-input/package.json create mode 100644 node_modules/ink-text-input/readme.md create mode 100644 node_modules/ink/license create mode 100644 node_modules/ink/node_modules/chalk/index.d.ts create mode 100644 node_modules/ink/node_modules/chalk/license create mode 100644 node_modules/ink/node_modules/chalk/package.json create mode 100644 node_modules/ink/node_modules/chalk/readme.md create mode 100644 node_modules/ink/node_modules/chalk/source/index.js create mode 100644 node_modules/ink/node_modules/chalk/source/templates.js create mode 100644 node_modules/ink/node_modules/chalk/source/util.js create mode 100644 node_modules/ink/package.json create mode 100644 node_modules/ink/readme.md create mode 100644 node_modules/inquirer/LICENSE create mode 100644 node_modules/inquirer/README.md create mode 100644 node_modules/inquirer/node_modules/ansi-escapes/index.d.ts create mode 100644 node_modules/inquirer/node_modules/ansi-escapes/index.js create mode 100644 node_modules/inquirer/node_modules/ansi-escapes/license create mode 100644 node_modules/inquirer/node_modules/ansi-escapes/package.json create mode 100644 node_modules/inquirer/node_modules/ansi-escapes/readme.md create mode 100644 node_modules/inquirer/node_modules/ansi-styles/index.d.ts create mode 100644 node_modules/inquirer/node_modules/ansi-styles/index.js create mode 100644 node_modules/inquirer/node_modules/ansi-styles/license create mode 100644 node_modules/inquirer/node_modules/ansi-styles/package.json create mode 100644 node_modules/inquirer/node_modules/ansi-styles/readme.md create mode 100644 node_modules/inquirer/node_modules/cli-cursor/index.d.ts create mode 100644 node_modules/inquirer/node_modules/cli-cursor/index.js create mode 100644 node_modules/inquirer/node_modules/cli-cursor/license create mode 100644 node_modules/inquirer/node_modules/cli-cursor/package.json create mode 100644 node_modules/inquirer/node_modules/cli-cursor/readme.md create mode 100644 node_modules/inquirer/node_modules/emoji-regex/LICENSE-MIT.txt create mode 100644 node_modules/inquirer/node_modules/emoji-regex/README.md create mode 100644 node_modules/inquirer/node_modules/emoji-regex/RGI_Emoji.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/RGI_Emoji.js create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/RGI_Emoji.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/RGI_Emoji.js create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/index.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/index.js create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/text.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/es2015/text.js create mode 100644 node_modules/inquirer/node_modules/emoji-regex/index.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/index.js create mode 100644 node_modules/inquirer/node_modules/emoji-regex/package.json create mode 100644 node_modules/inquirer/node_modules/emoji-regex/text.d.ts create mode 100644 node_modules/inquirer/node_modules/emoji-regex/text.js create mode 100644 node_modules/inquirer/node_modules/escape-string-regexp/index.d.ts create mode 100644 node_modules/inquirer/node_modules/escape-string-regexp/index.js create mode 100644 node_modules/inquirer/node_modules/escape-string-regexp/license create mode 100644 node_modules/inquirer/node_modules/escape-string-regexp/package.json create mode 100644 node_modules/inquirer/node_modules/escape-string-regexp/readme.md create mode 100644 node_modules/inquirer/node_modules/figures/index.d.ts create mode 100644 node_modules/inquirer/node_modules/figures/index.js create mode 100644 node_modules/inquirer/node_modules/figures/license create mode 100644 node_modules/inquirer/node_modules/figures/package.json create mode 100644 node_modules/inquirer/node_modules/figures/readme.md create mode 100644 node_modules/inquirer/node_modules/restore-cursor/index.d.ts create mode 100644 node_modules/inquirer/node_modules/restore-cursor/index.js create mode 100644 node_modules/inquirer/node_modules/restore-cursor/license create mode 100644 node_modules/inquirer/node_modules/restore-cursor/package.json create mode 100644 node_modules/inquirer/node_modules/restore-cursor/readme.md create mode 100644 node_modules/inquirer/node_modules/string-width/index.d.ts create mode 100644 node_modules/inquirer/node_modules/string-width/index.js create mode 100644 node_modules/inquirer/node_modules/string-width/license create mode 100644 node_modules/inquirer/node_modules/string-width/package.json create mode 100644 node_modules/inquirer/node_modules/string-width/readme.md create mode 100644 node_modules/inquirer/node_modules/type-fest/index.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/package.json create mode 100644 node_modules/inquirer/node_modules/type-fest/readme.md create mode 100644 node_modules/inquirer/node_modules/type-fest/source/async-return-type.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/asyncify.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/basic.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/camel-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/camel-cased-properties-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/camel-cased-properties.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/conditional-except.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/conditional-keys.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/conditional-pick-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/conditional-pick.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/conditional-simplify.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/delimiter-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/delimiter-cased-properties-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/delimiter-cased-properties.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/empty-object.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/enforce-optional.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/entries.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/entry.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/exact.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/except.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/fixed-length-array.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/get.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/global-this.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/has-optional-keys.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/has-required-keys.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/includes.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/internal.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/invariant-of.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/is-equal.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/iterable-element.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/join.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/jsonifiable.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/jsonify.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/kebab-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/kebab-cased-properties-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/kebab-cased-properties.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/last-array-element.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/literal-to-primitive.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/literal-union.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/merge-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/merge-exclusive.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/merge.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/multidimensional-array.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/multidimensional-readonly-array.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/numeric.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/observable-like.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/omit-index-signature.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/opaque.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/optional-keys-of.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/package-json.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/partial-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/partial-on-undefined-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/pascal-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/pascal-cased-properties-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/pascal-cased-properties.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/pick-index-signature.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/primitive.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/promisable.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/readonly-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/readonly-tuple.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/replace.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/require-all-or-none.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/require-at-least-one.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/require-exactly-one.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/required-keys-of.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/schema.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/screaming-snake-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/set-non-nullable.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/set-optional.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/set-required.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/set-return-type.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/simplify.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/snake-case.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/snake-cased-properties-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/snake-cased-properties.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/split-words.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/split.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/spread.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/string-key-of.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/stringified.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/trim.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/tsconfig-json.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/tuple-to-union.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/typed-array.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/union-to-intersection.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/value-of.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/writable-deep.d.ts create mode 100644 node_modules/inquirer/node_modules/type-fest/source/writable.d.ts create mode 100644 node_modules/inquirer/node_modules/wrap-ansi/index.d.ts create mode 100755 node_modules/inquirer/node_modules/wrap-ansi/index.js create mode 100644 node_modules/inquirer/node_modules/wrap-ansi/license create mode 100644 node_modules/inquirer/node_modules/wrap-ansi/package.json create mode 100644 node_modules/inquirer/node_modules/wrap-ansi/readme.md create mode 100644 node_modules/inquirer/package.json create mode 100644 node_modules/is-ci/CHANGELOG.md create mode 100644 node_modules/is-ci/LICENSE create mode 100644 node_modules/is-ci/README.md create mode 100755 node_modules/is-ci/bin.js create mode 100644 node_modules/is-ci/index.js create mode 100644 node_modules/is-ci/package.json create mode 100644 node_modules/is-fullwidth-code-point/index.d.ts create mode 100644 node_modules/is-fullwidth-code-point/index.js create mode 100644 node_modules/is-fullwidth-code-point/license create mode 100644 node_modules/is-fullwidth-code-point/package.json create mode 100644 node_modules/is-fullwidth-code-point/readme.md create mode 100644 node_modules/is-interactive/index.d.ts create mode 100644 node_modules/is-interactive/index.js create mode 100644 node_modules/is-interactive/license create mode 100644 node_modules/is-interactive/package.json create mode 100644 node_modules/is-interactive/readme.md create mode 100644 node_modules/is-unicode-supported/index.d.ts create mode 100644 node_modules/is-unicode-supported/index.js create mode 100644 node_modules/is-unicode-supported/license create mode 100644 node_modules/is-unicode-supported/package.json create mode 100644 node_modules/is-unicode-supported/readme.md create mode 100644 node_modules/js-sha3/CHANGELOG.md create mode 100644 node_modules/js-sha3/LICENSE.txt create mode 100644 node_modules/js-sha3/README.md create mode 100644 node_modules/js-sha3/index.d.ts create mode 100644 node_modules/js-sha3/package.json create mode 100644 node_modules/js-sha3/src/sha3.js create mode 100644 node_modules/js-tokens/CHANGELOG.md create mode 100644 node_modules/js-tokens/LICENSE create mode 100644 node_modules/js-tokens/README.md create mode 100644 node_modules/js-tokens/index.js create mode 100644 node_modules/js-tokens/package.json create mode 100644 node_modules/lodash.isequal/LICENSE create mode 100644 node_modules/lodash.isequal/README.md create mode 100644 node_modules/lodash.isequal/index.js create mode 100644 node_modules/lodash.isequal/package.json create mode 100644 node_modules/lodash/LICENSE create mode 100644 node_modules/lodash/README.md create mode 100644 node_modules/lodash/_DataView.js create mode 100644 node_modules/lodash/_Hash.js create mode 100644 node_modules/lodash/_LazyWrapper.js create mode 100644 node_modules/lodash/_ListCache.js create mode 100644 node_modules/lodash/_LodashWrapper.js create mode 100644 node_modules/lodash/_Map.js create mode 100644 node_modules/lodash/_MapCache.js create mode 100644 node_modules/lodash/_Promise.js create mode 100644 node_modules/lodash/_Set.js create mode 100644 node_modules/lodash/_SetCache.js create mode 100644 node_modules/lodash/_Stack.js create mode 100644 node_modules/lodash/_Symbol.js create mode 100644 node_modules/lodash/_Uint8Array.js create mode 100644 node_modules/lodash/_WeakMap.js create mode 100644 node_modules/lodash/_apply.js create mode 100644 node_modules/lodash/_arrayAggregator.js create mode 100644 node_modules/lodash/_arrayEach.js create mode 100644 node_modules/lodash/_arrayEachRight.js create mode 100644 node_modules/lodash/_arrayEvery.js create mode 100644 node_modules/lodash/_arrayFilter.js create mode 100644 node_modules/lodash/_arrayIncludes.js create mode 100644 node_modules/lodash/_arrayIncludesWith.js create mode 100644 node_modules/lodash/_arrayLikeKeys.js create mode 100644 node_modules/lodash/_arrayMap.js create mode 100644 node_modules/lodash/_arrayPush.js create mode 100644 node_modules/lodash/_arrayReduce.js create mode 100644 node_modules/lodash/_arrayReduceRight.js create mode 100644 node_modules/lodash/_arraySample.js create mode 100644 node_modules/lodash/_arraySampleSize.js create mode 100644 node_modules/lodash/_arrayShuffle.js create mode 100644 node_modules/lodash/_arraySome.js create mode 100644 node_modules/lodash/_asciiSize.js create mode 100644 node_modules/lodash/_asciiToArray.js create mode 100644 node_modules/lodash/_asciiWords.js create mode 100644 node_modules/lodash/_assignMergeValue.js create mode 100644 node_modules/lodash/_assignValue.js create mode 100644 node_modules/lodash/_assocIndexOf.js create mode 100644 node_modules/lodash/_baseAggregator.js create mode 100644 node_modules/lodash/_baseAssign.js create mode 100644 node_modules/lodash/_baseAssignIn.js create mode 100644 node_modules/lodash/_baseAssignValue.js create mode 100644 node_modules/lodash/_baseAt.js create mode 100644 node_modules/lodash/_baseClamp.js create mode 100644 node_modules/lodash/_baseClone.js create mode 100644 node_modules/lodash/_baseConforms.js create mode 100644 node_modules/lodash/_baseConformsTo.js create mode 100644 node_modules/lodash/_baseCreate.js create mode 100644 node_modules/lodash/_baseDelay.js create mode 100644 node_modules/lodash/_baseDifference.js create mode 100644 node_modules/lodash/_baseEach.js create mode 100644 node_modules/lodash/_baseEachRight.js create mode 100644 node_modules/lodash/_baseEvery.js create mode 100644 node_modules/lodash/_baseExtremum.js create mode 100644 node_modules/lodash/_baseFill.js create mode 100644 node_modules/lodash/_baseFilter.js create mode 100644 node_modules/lodash/_baseFindIndex.js create mode 100644 node_modules/lodash/_baseFindKey.js create mode 100644 node_modules/lodash/_baseFlatten.js create mode 100644 node_modules/lodash/_baseFor.js create mode 100644 node_modules/lodash/_baseForOwn.js create mode 100644 node_modules/lodash/_baseForOwnRight.js create mode 100644 node_modules/lodash/_baseForRight.js create mode 100644 node_modules/lodash/_baseFunctions.js create mode 100644 node_modules/lodash/_baseGet.js create mode 100644 node_modules/lodash/_baseGetAllKeys.js create mode 100644 node_modules/lodash/_baseGetTag.js create mode 100644 node_modules/lodash/_baseGt.js create mode 100644 node_modules/lodash/_baseHas.js create mode 100644 node_modules/lodash/_baseHasIn.js create mode 100644 node_modules/lodash/_baseInRange.js create mode 100644 node_modules/lodash/_baseIndexOf.js create mode 100644 node_modules/lodash/_baseIndexOfWith.js create mode 100644 node_modules/lodash/_baseIntersection.js create mode 100644 node_modules/lodash/_baseInverter.js create mode 100644 node_modules/lodash/_baseInvoke.js create mode 100644 node_modules/lodash/_baseIsArguments.js create mode 100644 node_modules/lodash/_baseIsArrayBuffer.js create mode 100644 node_modules/lodash/_baseIsDate.js create mode 100644 node_modules/lodash/_baseIsEqual.js create mode 100644 node_modules/lodash/_baseIsEqualDeep.js create mode 100644 node_modules/lodash/_baseIsMap.js create mode 100644 node_modules/lodash/_baseIsMatch.js create mode 100644 node_modules/lodash/_baseIsNaN.js create mode 100644 node_modules/lodash/_baseIsNative.js create mode 100644 node_modules/lodash/_baseIsRegExp.js create mode 100644 node_modules/lodash/_baseIsSet.js create mode 100644 node_modules/lodash/_baseIsTypedArray.js create mode 100644 node_modules/lodash/_baseIteratee.js create mode 100644 node_modules/lodash/_baseKeys.js create mode 100644 node_modules/lodash/_baseKeysIn.js create mode 100644 node_modules/lodash/_baseLodash.js create mode 100644 node_modules/lodash/_baseLt.js create mode 100644 node_modules/lodash/_baseMap.js create mode 100644 node_modules/lodash/_baseMatches.js create mode 100644 node_modules/lodash/_baseMatchesProperty.js create mode 100644 node_modules/lodash/_baseMean.js create mode 100644 node_modules/lodash/_baseMerge.js create mode 100644 node_modules/lodash/_baseMergeDeep.js create mode 100644 node_modules/lodash/_baseNth.js create mode 100644 node_modules/lodash/_baseOrderBy.js create mode 100644 node_modules/lodash/_basePick.js create mode 100644 node_modules/lodash/_basePickBy.js create mode 100644 node_modules/lodash/_baseProperty.js create mode 100644 node_modules/lodash/_basePropertyDeep.js create mode 100644 node_modules/lodash/_basePropertyOf.js create mode 100644 node_modules/lodash/_basePullAll.js create mode 100644 node_modules/lodash/_basePullAt.js create mode 100644 node_modules/lodash/_baseRandom.js create mode 100644 node_modules/lodash/_baseRange.js create mode 100644 node_modules/lodash/_baseReduce.js create mode 100644 node_modules/lodash/_baseRepeat.js create mode 100644 node_modules/lodash/_baseRest.js create mode 100644 node_modules/lodash/_baseSample.js create mode 100644 node_modules/lodash/_baseSampleSize.js create mode 100644 node_modules/lodash/_baseSet.js create mode 100644 node_modules/lodash/_baseSetData.js create mode 100644 node_modules/lodash/_baseSetToString.js create mode 100644 node_modules/lodash/_baseShuffle.js create mode 100644 node_modules/lodash/_baseSlice.js create mode 100644 node_modules/lodash/_baseSome.js create mode 100644 node_modules/lodash/_baseSortBy.js create mode 100644 node_modules/lodash/_baseSortedIndex.js create mode 100644 node_modules/lodash/_baseSortedIndexBy.js create mode 100644 node_modules/lodash/_baseSortedUniq.js create mode 100644 node_modules/lodash/_baseSum.js create mode 100644 node_modules/lodash/_baseTimes.js create mode 100644 node_modules/lodash/_baseToNumber.js create mode 100644 node_modules/lodash/_baseToPairs.js create mode 100644 node_modules/lodash/_baseToString.js create mode 100644 node_modules/lodash/_baseTrim.js create mode 100644 node_modules/lodash/_baseUnary.js create mode 100644 node_modules/lodash/_baseUniq.js create mode 100644 node_modules/lodash/_baseUnset.js create mode 100644 node_modules/lodash/_baseUpdate.js create mode 100644 node_modules/lodash/_baseValues.js create mode 100644 node_modules/lodash/_baseWhile.js create mode 100644 node_modules/lodash/_baseWrapperValue.js create mode 100644 node_modules/lodash/_baseXor.js create mode 100644 node_modules/lodash/_baseZipObject.js create mode 100644 node_modules/lodash/_cacheHas.js create mode 100644 node_modules/lodash/_castArrayLikeObject.js create mode 100644 node_modules/lodash/_castFunction.js create mode 100644 node_modules/lodash/_castPath.js create mode 100644 node_modules/lodash/_castRest.js create mode 100644 node_modules/lodash/_castSlice.js create mode 100644 node_modules/lodash/_charsEndIndex.js create mode 100644 node_modules/lodash/_charsStartIndex.js create mode 100644 node_modules/lodash/_cloneArrayBuffer.js create mode 100644 node_modules/lodash/_cloneBuffer.js create mode 100644 node_modules/lodash/_cloneDataView.js create mode 100644 node_modules/lodash/_cloneRegExp.js create mode 100644 node_modules/lodash/_cloneSymbol.js create mode 100644 node_modules/lodash/_cloneTypedArray.js create mode 100644 node_modules/lodash/_compareAscending.js create mode 100644 node_modules/lodash/_compareMultiple.js create mode 100644 node_modules/lodash/_composeArgs.js create mode 100644 node_modules/lodash/_composeArgsRight.js create mode 100644 node_modules/lodash/_copyArray.js create mode 100644 node_modules/lodash/_copyObject.js create mode 100644 node_modules/lodash/_copySymbols.js create mode 100644 node_modules/lodash/_copySymbolsIn.js create mode 100644 node_modules/lodash/_coreJsData.js create mode 100644 node_modules/lodash/_countHolders.js create mode 100644 node_modules/lodash/_createAggregator.js create mode 100644 node_modules/lodash/_createAssigner.js create mode 100644 node_modules/lodash/_createBaseEach.js create mode 100644 node_modules/lodash/_createBaseFor.js create mode 100644 node_modules/lodash/_createBind.js create mode 100644 node_modules/lodash/_createCaseFirst.js create mode 100644 node_modules/lodash/_createCompounder.js create mode 100644 node_modules/lodash/_createCtor.js create mode 100644 node_modules/lodash/_createCurry.js create mode 100644 node_modules/lodash/_createFind.js create mode 100644 node_modules/lodash/_createFlow.js create mode 100644 node_modules/lodash/_createHybrid.js create mode 100644 node_modules/lodash/_createInverter.js create mode 100644 node_modules/lodash/_createMathOperation.js create mode 100644 node_modules/lodash/_createOver.js create mode 100644 node_modules/lodash/_createPadding.js create mode 100644 node_modules/lodash/_createPartial.js create mode 100644 node_modules/lodash/_createRange.js create mode 100644 node_modules/lodash/_createRecurry.js create mode 100644 node_modules/lodash/_createRelationalOperation.js create mode 100644 node_modules/lodash/_createRound.js create mode 100644 node_modules/lodash/_createSet.js create mode 100644 node_modules/lodash/_createToPairs.js create mode 100644 node_modules/lodash/_createWrap.js create mode 100644 node_modules/lodash/_customDefaultsAssignIn.js create mode 100644 node_modules/lodash/_customDefaultsMerge.js create mode 100644 node_modules/lodash/_customOmitClone.js create mode 100644 node_modules/lodash/_deburrLetter.js create mode 100644 node_modules/lodash/_defineProperty.js create mode 100644 node_modules/lodash/_equalArrays.js create mode 100644 node_modules/lodash/_equalByTag.js create mode 100644 node_modules/lodash/_equalObjects.js create mode 100644 node_modules/lodash/_escapeHtmlChar.js create mode 100644 node_modules/lodash/_escapeStringChar.js create mode 100644 node_modules/lodash/_flatRest.js create mode 100644 node_modules/lodash/_freeGlobal.js create mode 100644 node_modules/lodash/_getAllKeys.js create mode 100644 node_modules/lodash/_getAllKeysIn.js create mode 100644 node_modules/lodash/_getData.js create mode 100644 node_modules/lodash/_getFuncName.js create mode 100644 node_modules/lodash/_getHolder.js create mode 100644 node_modules/lodash/_getMapData.js create mode 100644 node_modules/lodash/_getMatchData.js create mode 100644 node_modules/lodash/_getNative.js create mode 100644 node_modules/lodash/_getPrototype.js create mode 100644 node_modules/lodash/_getRawTag.js create mode 100644 node_modules/lodash/_getSymbols.js create mode 100644 node_modules/lodash/_getSymbolsIn.js create mode 100644 node_modules/lodash/_getTag.js create mode 100644 node_modules/lodash/_getValue.js create mode 100644 node_modules/lodash/_getView.js create mode 100644 node_modules/lodash/_getWrapDetails.js create mode 100644 node_modules/lodash/_hasPath.js create mode 100644 node_modules/lodash/_hasUnicode.js create mode 100644 node_modules/lodash/_hasUnicodeWord.js create mode 100644 node_modules/lodash/_hashClear.js create mode 100644 node_modules/lodash/_hashDelete.js create mode 100644 node_modules/lodash/_hashGet.js create mode 100644 node_modules/lodash/_hashHas.js create mode 100644 node_modules/lodash/_hashSet.js create mode 100644 node_modules/lodash/_initCloneArray.js create mode 100644 node_modules/lodash/_initCloneByTag.js create mode 100644 node_modules/lodash/_initCloneObject.js create mode 100644 node_modules/lodash/_insertWrapDetails.js create mode 100644 node_modules/lodash/_isFlattenable.js create mode 100644 node_modules/lodash/_isIndex.js create mode 100644 node_modules/lodash/_isIterateeCall.js create mode 100644 node_modules/lodash/_isKey.js create mode 100644 node_modules/lodash/_isKeyable.js create mode 100644 node_modules/lodash/_isLaziable.js create mode 100644 node_modules/lodash/_isMaskable.js create mode 100644 node_modules/lodash/_isMasked.js create mode 100644 node_modules/lodash/_isPrototype.js create mode 100644 node_modules/lodash/_isStrictComparable.js create mode 100644 node_modules/lodash/_iteratorToArray.js create mode 100644 node_modules/lodash/_lazyClone.js create mode 100644 node_modules/lodash/_lazyReverse.js create mode 100644 node_modules/lodash/_lazyValue.js create mode 100644 node_modules/lodash/_listCacheClear.js create mode 100644 node_modules/lodash/_listCacheDelete.js create mode 100644 node_modules/lodash/_listCacheGet.js create mode 100644 node_modules/lodash/_listCacheHas.js create mode 100644 node_modules/lodash/_listCacheSet.js create mode 100644 node_modules/lodash/_mapCacheClear.js create mode 100644 node_modules/lodash/_mapCacheDelete.js create mode 100644 node_modules/lodash/_mapCacheGet.js create mode 100644 node_modules/lodash/_mapCacheHas.js create mode 100644 node_modules/lodash/_mapCacheSet.js create mode 100644 node_modules/lodash/_mapToArray.js create mode 100644 node_modules/lodash/_matchesStrictComparable.js create mode 100644 node_modules/lodash/_memoizeCapped.js create mode 100644 node_modules/lodash/_mergeData.js create mode 100644 node_modules/lodash/_metaMap.js create mode 100644 node_modules/lodash/_nativeCreate.js create mode 100644 node_modules/lodash/_nativeKeys.js create mode 100644 node_modules/lodash/_nativeKeysIn.js create mode 100644 node_modules/lodash/_nodeUtil.js create mode 100644 node_modules/lodash/_objectToString.js create mode 100644 node_modules/lodash/_overArg.js create mode 100644 node_modules/lodash/_overRest.js create mode 100644 node_modules/lodash/_parent.js create mode 100644 node_modules/lodash/_reEscape.js create mode 100644 node_modules/lodash/_reEvaluate.js create mode 100644 node_modules/lodash/_reInterpolate.js create mode 100644 node_modules/lodash/_realNames.js create mode 100644 node_modules/lodash/_reorder.js create mode 100644 node_modules/lodash/_replaceHolders.js create mode 100644 node_modules/lodash/_root.js create mode 100644 node_modules/lodash/_safeGet.js create mode 100644 node_modules/lodash/_setCacheAdd.js create mode 100644 node_modules/lodash/_setCacheHas.js create mode 100644 node_modules/lodash/_setData.js create mode 100644 node_modules/lodash/_setToArray.js create mode 100644 node_modules/lodash/_setToPairs.js create mode 100644 node_modules/lodash/_setToString.js create mode 100644 node_modules/lodash/_setWrapToString.js create mode 100644 node_modules/lodash/_shortOut.js create mode 100644 node_modules/lodash/_shuffleSelf.js create mode 100644 node_modules/lodash/_stackClear.js create mode 100644 node_modules/lodash/_stackDelete.js create mode 100644 node_modules/lodash/_stackGet.js create mode 100644 node_modules/lodash/_stackHas.js create mode 100644 node_modules/lodash/_stackSet.js create mode 100644 node_modules/lodash/_strictIndexOf.js create mode 100644 node_modules/lodash/_strictLastIndexOf.js create mode 100644 node_modules/lodash/_stringSize.js create mode 100644 node_modules/lodash/_stringToArray.js create mode 100644 node_modules/lodash/_stringToPath.js create mode 100644 node_modules/lodash/_toKey.js create mode 100644 node_modules/lodash/_toSource.js create mode 100644 node_modules/lodash/_trimmedEndIndex.js create mode 100644 node_modules/lodash/_unescapeHtmlChar.js create mode 100644 node_modules/lodash/_unicodeSize.js create mode 100644 node_modules/lodash/_unicodeToArray.js create mode 100644 node_modules/lodash/_unicodeWords.js create mode 100644 node_modules/lodash/_updateWrapDetails.js create mode 100644 node_modules/lodash/_wrapperClone.js create mode 100644 node_modules/lodash/add.js create mode 100644 node_modules/lodash/after.js create mode 100644 node_modules/lodash/array.js create mode 100644 node_modules/lodash/ary.js create mode 100644 node_modules/lodash/assign.js create mode 100644 node_modules/lodash/assignIn.js create mode 100644 node_modules/lodash/assignInWith.js create mode 100644 node_modules/lodash/assignWith.js create mode 100644 node_modules/lodash/at.js create mode 100644 node_modules/lodash/attempt.js create mode 100644 node_modules/lodash/before.js create mode 100644 node_modules/lodash/bind.js create mode 100644 node_modules/lodash/bindAll.js create mode 100644 node_modules/lodash/bindKey.js create mode 100644 node_modules/lodash/camelCase.js create mode 100644 node_modules/lodash/capitalize.js create mode 100644 node_modules/lodash/castArray.js create mode 100644 node_modules/lodash/ceil.js create mode 100644 node_modules/lodash/chain.js create mode 100644 node_modules/lodash/chunk.js create mode 100644 node_modules/lodash/clamp.js create mode 100644 node_modules/lodash/clone.js create mode 100644 node_modules/lodash/cloneDeep.js create mode 100644 node_modules/lodash/cloneDeepWith.js create mode 100644 node_modules/lodash/cloneWith.js create mode 100644 node_modules/lodash/collection.js create mode 100644 node_modules/lodash/commit.js create mode 100644 node_modules/lodash/compact.js create mode 100644 node_modules/lodash/concat.js create mode 100644 node_modules/lodash/cond.js create mode 100644 node_modules/lodash/conforms.js create mode 100644 node_modules/lodash/conformsTo.js create mode 100644 node_modules/lodash/constant.js create mode 100644 node_modules/lodash/core.js create mode 100644 node_modules/lodash/core.min.js create mode 100644 node_modules/lodash/countBy.js create mode 100644 node_modules/lodash/create.js create mode 100644 node_modules/lodash/curry.js create mode 100644 node_modules/lodash/curryRight.js create mode 100644 node_modules/lodash/date.js create mode 100644 node_modules/lodash/debounce.js create mode 100644 node_modules/lodash/deburr.js create mode 100644 node_modules/lodash/defaultTo.js create mode 100644 node_modules/lodash/defaults.js create mode 100644 node_modules/lodash/defaultsDeep.js create mode 100644 node_modules/lodash/defer.js create mode 100644 node_modules/lodash/delay.js create mode 100644 node_modules/lodash/difference.js create mode 100644 node_modules/lodash/differenceBy.js create mode 100644 node_modules/lodash/differenceWith.js create mode 100644 node_modules/lodash/divide.js create mode 100644 node_modules/lodash/drop.js create mode 100644 node_modules/lodash/dropRight.js create mode 100644 node_modules/lodash/dropRightWhile.js create mode 100644 node_modules/lodash/dropWhile.js create mode 100644 node_modules/lodash/each.js create mode 100644 node_modules/lodash/eachRight.js create mode 100644 node_modules/lodash/endsWith.js create mode 100644 node_modules/lodash/entries.js create mode 100644 node_modules/lodash/entriesIn.js create mode 100644 node_modules/lodash/eq.js create mode 100644 node_modules/lodash/escape.js create mode 100644 node_modules/lodash/escapeRegExp.js create mode 100644 node_modules/lodash/every.js create mode 100644 node_modules/lodash/extend.js create mode 100644 node_modules/lodash/extendWith.js create mode 100644 node_modules/lodash/fill.js create mode 100644 node_modules/lodash/filter.js create mode 100644 node_modules/lodash/find.js create mode 100644 node_modules/lodash/findIndex.js create mode 100644 node_modules/lodash/findKey.js create mode 100644 node_modules/lodash/findLast.js create mode 100644 node_modules/lodash/findLastIndex.js create mode 100644 node_modules/lodash/findLastKey.js create mode 100644 node_modules/lodash/first.js create mode 100644 node_modules/lodash/flake.lock create mode 100644 node_modules/lodash/flake.nix create mode 100644 node_modules/lodash/flatMap.js create mode 100644 node_modules/lodash/flatMapDeep.js create mode 100644 node_modules/lodash/flatMapDepth.js create mode 100644 node_modules/lodash/flatten.js create mode 100644 node_modules/lodash/flattenDeep.js create mode 100644 node_modules/lodash/flattenDepth.js create mode 100644 node_modules/lodash/flip.js create mode 100644 node_modules/lodash/floor.js create mode 100644 node_modules/lodash/flow.js create mode 100644 node_modules/lodash/flowRight.js create mode 100644 node_modules/lodash/forEach.js create mode 100644 node_modules/lodash/forEachRight.js create mode 100644 node_modules/lodash/forIn.js create mode 100644 node_modules/lodash/forInRight.js create mode 100644 node_modules/lodash/forOwn.js create mode 100644 node_modules/lodash/forOwnRight.js create mode 100644 node_modules/lodash/fp.js create mode 100644 node_modules/lodash/fp/F.js create mode 100644 node_modules/lodash/fp/T.js create mode 100644 node_modules/lodash/fp/__.js create mode 100644 node_modules/lodash/fp/_baseConvert.js create mode 100644 node_modules/lodash/fp/_convertBrowser.js create mode 100644 node_modules/lodash/fp/_falseOptions.js create mode 100644 node_modules/lodash/fp/_mapping.js create mode 100644 node_modules/lodash/fp/_util.js create mode 100644 node_modules/lodash/fp/add.js create mode 100644 node_modules/lodash/fp/after.js create mode 100644 node_modules/lodash/fp/all.js create mode 100644 node_modules/lodash/fp/allPass.js create mode 100644 node_modules/lodash/fp/always.js create mode 100644 node_modules/lodash/fp/any.js create mode 100644 node_modules/lodash/fp/anyPass.js create mode 100644 node_modules/lodash/fp/apply.js create mode 100644 node_modules/lodash/fp/array.js create mode 100644 node_modules/lodash/fp/ary.js create mode 100644 node_modules/lodash/fp/assign.js create mode 100644 node_modules/lodash/fp/assignAll.js create mode 100644 node_modules/lodash/fp/assignAllWith.js create mode 100644 node_modules/lodash/fp/assignIn.js create mode 100644 node_modules/lodash/fp/assignInAll.js create mode 100644 node_modules/lodash/fp/assignInAllWith.js create mode 100644 node_modules/lodash/fp/assignInWith.js create mode 100644 node_modules/lodash/fp/assignWith.js create mode 100644 node_modules/lodash/fp/assoc.js create mode 100644 node_modules/lodash/fp/assocPath.js create mode 100644 node_modules/lodash/fp/at.js create mode 100644 node_modules/lodash/fp/attempt.js create mode 100644 node_modules/lodash/fp/before.js create mode 100644 node_modules/lodash/fp/bind.js create mode 100644 node_modules/lodash/fp/bindAll.js create mode 100644 node_modules/lodash/fp/bindKey.js create mode 100644 node_modules/lodash/fp/camelCase.js create mode 100644 node_modules/lodash/fp/capitalize.js create mode 100644 node_modules/lodash/fp/castArray.js create mode 100644 node_modules/lodash/fp/ceil.js create mode 100644 node_modules/lodash/fp/chain.js create mode 100644 node_modules/lodash/fp/chunk.js create mode 100644 node_modules/lodash/fp/clamp.js create mode 100644 node_modules/lodash/fp/clone.js create mode 100644 node_modules/lodash/fp/cloneDeep.js create mode 100644 node_modules/lodash/fp/cloneDeepWith.js create mode 100644 node_modules/lodash/fp/cloneWith.js create mode 100644 node_modules/lodash/fp/collection.js create mode 100644 node_modules/lodash/fp/commit.js create mode 100644 node_modules/lodash/fp/compact.js create mode 100644 node_modules/lodash/fp/complement.js create mode 100644 node_modules/lodash/fp/compose.js create mode 100644 node_modules/lodash/fp/concat.js create mode 100644 node_modules/lodash/fp/cond.js create mode 100644 node_modules/lodash/fp/conforms.js create mode 100644 node_modules/lodash/fp/conformsTo.js create mode 100644 node_modules/lodash/fp/constant.js create mode 100644 node_modules/lodash/fp/contains.js create mode 100644 node_modules/lodash/fp/convert.js create mode 100644 node_modules/lodash/fp/countBy.js create mode 100644 node_modules/lodash/fp/create.js create mode 100644 node_modules/lodash/fp/curry.js create mode 100644 node_modules/lodash/fp/curryN.js create mode 100644 node_modules/lodash/fp/curryRight.js create mode 100644 node_modules/lodash/fp/curryRightN.js create mode 100644 node_modules/lodash/fp/date.js create mode 100644 node_modules/lodash/fp/debounce.js create mode 100644 node_modules/lodash/fp/deburr.js create mode 100644 node_modules/lodash/fp/defaultTo.js create mode 100644 node_modules/lodash/fp/defaults.js create mode 100644 node_modules/lodash/fp/defaultsAll.js create mode 100644 node_modules/lodash/fp/defaultsDeep.js create mode 100644 node_modules/lodash/fp/defaultsDeepAll.js create mode 100644 node_modules/lodash/fp/defer.js create mode 100644 node_modules/lodash/fp/delay.js create mode 100644 node_modules/lodash/fp/difference.js create mode 100644 node_modules/lodash/fp/differenceBy.js create mode 100644 node_modules/lodash/fp/differenceWith.js create mode 100644 node_modules/lodash/fp/dissoc.js create mode 100644 node_modules/lodash/fp/dissocPath.js create mode 100644 node_modules/lodash/fp/divide.js create mode 100644 node_modules/lodash/fp/drop.js create mode 100644 node_modules/lodash/fp/dropLast.js create mode 100644 node_modules/lodash/fp/dropLastWhile.js create mode 100644 node_modules/lodash/fp/dropRight.js create mode 100644 node_modules/lodash/fp/dropRightWhile.js create mode 100644 node_modules/lodash/fp/dropWhile.js create mode 100644 node_modules/lodash/fp/each.js create mode 100644 node_modules/lodash/fp/eachRight.js create mode 100644 node_modules/lodash/fp/endsWith.js create mode 100644 node_modules/lodash/fp/entries.js create mode 100644 node_modules/lodash/fp/entriesIn.js create mode 100644 node_modules/lodash/fp/eq.js create mode 100644 node_modules/lodash/fp/equals.js create mode 100644 node_modules/lodash/fp/escape.js create mode 100644 node_modules/lodash/fp/escapeRegExp.js create mode 100644 node_modules/lodash/fp/every.js create mode 100644 node_modules/lodash/fp/extend.js create mode 100644 node_modules/lodash/fp/extendAll.js create mode 100644 node_modules/lodash/fp/extendAllWith.js create mode 100644 node_modules/lodash/fp/extendWith.js create mode 100644 node_modules/lodash/fp/fill.js create mode 100644 node_modules/lodash/fp/filter.js create mode 100644 node_modules/lodash/fp/find.js create mode 100644 node_modules/lodash/fp/findFrom.js create mode 100644 node_modules/lodash/fp/findIndex.js create mode 100644 node_modules/lodash/fp/findIndexFrom.js create mode 100644 node_modules/lodash/fp/findKey.js create mode 100644 node_modules/lodash/fp/findLast.js create mode 100644 node_modules/lodash/fp/findLastFrom.js create mode 100644 node_modules/lodash/fp/findLastIndex.js create mode 100644 node_modules/lodash/fp/findLastIndexFrom.js create mode 100644 node_modules/lodash/fp/findLastKey.js create mode 100644 node_modules/lodash/fp/first.js create mode 100644 node_modules/lodash/fp/flatMap.js create mode 100644 node_modules/lodash/fp/flatMapDeep.js create mode 100644 node_modules/lodash/fp/flatMapDepth.js create mode 100644 node_modules/lodash/fp/flatten.js create mode 100644 node_modules/lodash/fp/flattenDeep.js create mode 100644 node_modules/lodash/fp/flattenDepth.js create mode 100644 node_modules/lodash/fp/flip.js create mode 100644 node_modules/lodash/fp/floor.js create mode 100644 node_modules/lodash/fp/flow.js create mode 100644 node_modules/lodash/fp/flowRight.js create mode 100644 node_modules/lodash/fp/forEach.js create mode 100644 node_modules/lodash/fp/forEachRight.js create mode 100644 node_modules/lodash/fp/forIn.js create mode 100644 node_modules/lodash/fp/forInRight.js create mode 100644 node_modules/lodash/fp/forOwn.js create mode 100644 node_modules/lodash/fp/forOwnRight.js create mode 100644 node_modules/lodash/fp/fromPairs.js create mode 100644 node_modules/lodash/fp/function.js create mode 100644 node_modules/lodash/fp/functions.js create mode 100644 node_modules/lodash/fp/functionsIn.js create mode 100644 node_modules/lodash/fp/get.js create mode 100644 node_modules/lodash/fp/getOr.js create mode 100644 node_modules/lodash/fp/groupBy.js create mode 100644 node_modules/lodash/fp/gt.js create mode 100644 node_modules/lodash/fp/gte.js create mode 100644 node_modules/lodash/fp/has.js create mode 100644 node_modules/lodash/fp/hasIn.js create mode 100644 node_modules/lodash/fp/head.js create mode 100644 node_modules/lodash/fp/identical.js create mode 100644 node_modules/lodash/fp/identity.js create mode 100644 node_modules/lodash/fp/inRange.js create mode 100644 node_modules/lodash/fp/includes.js create mode 100644 node_modules/lodash/fp/includesFrom.js create mode 100644 node_modules/lodash/fp/indexBy.js create mode 100644 node_modules/lodash/fp/indexOf.js create mode 100644 node_modules/lodash/fp/indexOfFrom.js create mode 100644 node_modules/lodash/fp/init.js create mode 100644 node_modules/lodash/fp/initial.js create mode 100644 node_modules/lodash/fp/intersection.js create mode 100644 node_modules/lodash/fp/intersectionBy.js create mode 100644 node_modules/lodash/fp/intersectionWith.js create mode 100644 node_modules/lodash/fp/invert.js create mode 100644 node_modules/lodash/fp/invertBy.js create mode 100644 node_modules/lodash/fp/invertObj.js create mode 100644 node_modules/lodash/fp/invoke.js create mode 100644 node_modules/lodash/fp/invokeArgs.js create mode 100644 node_modules/lodash/fp/invokeArgsMap.js create mode 100644 node_modules/lodash/fp/invokeMap.js create mode 100644 node_modules/lodash/fp/isArguments.js create mode 100644 node_modules/lodash/fp/isArray.js create mode 100644 node_modules/lodash/fp/isArrayBuffer.js create mode 100644 node_modules/lodash/fp/isArrayLike.js create mode 100644 node_modules/lodash/fp/isArrayLikeObject.js create mode 100644 node_modules/lodash/fp/isBoolean.js create mode 100644 node_modules/lodash/fp/isBuffer.js create mode 100644 node_modules/lodash/fp/isDate.js create mode 100644 node_modules/lodash/fp/isElement.js create mode 100644 node_modules/lodash/fp/isEmpty.js create mode 100644 node_modules/lodash/fp/isEqual.js create mode 100644 node_modules/lodash/fp/isEqualWith.js create mode 100644 node_modules/lodash/fp/isError.js create mode 100644 node_modules/lodash/fp/isFinite.js create mode 100644 node_modules/lodash/fp/isFunction.js create mode 100644 node_modules/lodash/fp/isInteger.js create mode 100644 node_modules/lodash/fp/isLength.js create mode 100644 node_modules/lodash/fp/isMap.js create mode 100644 node_modules/lodash/fp/isMatch.js create mode 100644 node_modules/lodash/fp/isMatchWith.js create mode 100644 node_modules/lodash/fp/isNaN.js create mode 100644 node_modules/lodash/fp/isNative.js create mode 100644 node_modules/lodash/fp/isNil.js create mode 100644 node_modules/lodash/fp/isNull.js create mode 100644 node_modules/lodash/fp/isNumber.js create mode 100644 node_modules/lodash/fp/isObject.js create mode 100644 node_modules/lodash/fp/isObjectLike.js create mode 100644 node_modules/lodash/fp/isPlainObject.js create mode 100644 node_modules/lodash/fp/isRegExp.js create mode 100644 node_modules/lodash/fp/isSafeInteger.js create mode 100644 node_modules/lodash/fp/isSet.js create mode 100644 node_modules/lodash/fp/isString.js create mode 100644 node_modules/lodash/fp/isSymbol.js create mode 100644 node_modules/lodash/fp/isTypedArray.js create mode 100644 node_modules/lodash/fp/isUndefined.js create mode 100644 node_modules/lodash/fp/isWeakMap.js create mode 100644 node_modules/lodash/fp/isWeakSet.js create mode 100644 node_modules/lodash/fp/iteratee.js create mode 100644 node_modules/lodash/fp/join.js create mode 100644 node_modules/lodash/fp/juxt.js create mode 100644 node_modules/lodash/fp/kebabCase.js create mode 100644 node_modules/lodash/fp/keyBy.js create mode 100644 node_modules/lodash/fp/keys.js create mode 100644 node_modules/lodash/fp/keysIn.js create mode 100644 node_modules/lodash/fp/lang.js create mode 100644 node_modules/lodash/fp/last.js create mode 100644 node_modules/lodash/fp/lastIndexOf.js create mode 100644 node_modules/lodash/fp/lastIndexOfFrom.js create mode 100644 node_modules/lodash/fp/lowerCase.js create mode 100644 node_modules/lodash/fp/lowerFirst.js create mode 100644 node_modules/lodash/fp/lt.js create mode 100644 node_modules/lodash/fp/lte.js create mode 100644 node_modules/lodash/fp/map.js create mode 100644 node_modules/lodash/fp/mapKeys.js create mode 100644 node_modules/lodash/fp/mapValues.js create mode 100644 node_modules/lodash/fp/matches.js create mode 100644 node_modules/lodash/fp/matchesProperty.js create mode 100644 node_modules/lodash/fp/math.js create mode 100644 node_modules/lodash/fp/max.js create mode 100644 node_modules/lodash/fp/maxBy.js create mode 100644 node_modules/lodash/fp/mean.js create mode 100644 node_modules/lodash/fp/meanBy.js create mode 100644 node_modules/lodash/fp/memoize.js create mode 100644 node_modules/lodash/fp/merge.js create mode 100644 node_modules/lodash/fp/mergeAll.js create mode 100644 node_modules/lodash/fp/mergeAllWith.js create mode 100644 node_modules/lodash/fp/mergeWith.js create mode 100644 node_modules/lodash/fp/method.js create mode 100644 node_modules/lodash/fp/methodOf.js create mode 100644 node_modules/lodash/fp/min.js create mode 100644 node_modules/lodash/fp/minBy.js create mode 100644 node_modules/lodash/fp/mixin.js create mode 100644 node_modules/lodash/fp/multiply.js create mode 100644 node_modules/lodash/fp/nAry.js create mode 100644 node_modules/lodash/fp/negate.js create mode 100644 node_modules/lodash/fp/next.js create mode 100644 node_modules/lodash/fp/noop.js create mode 100644 node_modules/lodash/fp/now.js create mode 100644 node_modules/lodash/fp/nth.js create mode 100644 node_modules/lodash/fp/nthArg.js create mode 100644 node_modules/lodash/fp/number.js create mode 100644 node_modules/lodash/fp/object.js create mode 100644 node_modules/lodash/fp/omit.js create mode 100644 node_modules/lodash/fp/omitAll.js create mode 100644 node_modules/lodash/fp/omitBy.js create mode 100644 node_modules/lodash/fp/once.js create mode 100644 node_modules/lodash/fp/orderBy.js create mode 100644 node_modules/lodash/fp/over.js create mode 100644 node_modules/lodash/fp/overArgs.js create mode 100644 node_modules/lodash/fp/overEvery.js create mode 100644 node_modules/lodash/fp/overSome.js create mode 100644 node_modules/lodash/fp/pad.js create mode 100644 node_modules/lodash/fp/padChars.js create mode 100644 node_modules/lodash/fp/padCharsEnd.js create mode 100644 node_modules/lodash/fp/padCharsStart.js create mode 100644 node_modules/lodash/fp/padEnd.js create mode 100644 node_modules/lodash/fp/padStart.js create mode 100644 node_modules/lodash/fp/parseInt.js create mode 100644 node_modules/lodash/fp/partial.js create mode 100644 node_modules/lodash/fp/partialRight.js create mode 100644 node_modules/lodash/fp/partition.js create mode 100644 node_modules/lodash/fp/path.js create mode 100644 node_modules/lodash/fp/pathEq.js create mode 100644 node_modules/lodash/fp/pathOr.js create mode 100644 node_modules/lodash/fp/paths.js create mode 100644 node_modules/lodash/fp/pick.js create mode 100644 node_modules/lodash/fp/pickAll.js create mode 100644 node_modules/lodash/fp/pickBy.js create mode 100644 node_modules/lodash/fp/pipe.js create mode 100644 node_modules/lodash/fp/placeholder.js create mode 100644 node_modules/lodash/fp/plant.js create mode 100644 node_modules/lodash/fp/pluck.js create mode 100644 node_modules/lodash/fp/prop.js create mode 100644 node_modules/lodash/fp/propEq.js create mode 100644 node_modules/lodash/fp/propOr.js create mode 100644 node_modules/lodash/fp/property.js create mode 100644 node_modules/lodash/fp/propertyOf.js create mode 100644 node_modules/lodash/fp/props.js create mode 100644 node_modules/lodash/fp/pull.js create mode 100644 node_modules/lodash/fp/pullAll.js create mode 100644 node_modules/lodash/fp/pullAllBy.js create mode 100644 node_modules/lodash/fp/pullAllWith.js create mode 100644 node_modules/lodash/fp/pullAt.js create mode 100644 node_modules/lodash/fp/random.js create mode 100644 node_modules/lodash/fp/range.js create mode 100644 node_modules/lodash/fp/rangeRight.js create mode 100644 node_modules/lodash/fp/rangeStep.js create mode 100644 node_modules/lodash/fp/rangeStepRight.js create mode 100644 node_modules/lodash/fp/rearg.js create mode 100644 node_modules/lodash/fp/reduce.js create mode 100644 node_modules/lodash/fp/reduceRight.js create mode 100644 node_modules/lodash/fp/reject.js create mode 100644 node_modules/lodash/fp/remove.js create mode 100644 node_modules/lodash/fp/repeat.js create mode 100644 node_modules/lodash/fp/replace.js create mode 100644 node_modules/lodash/fp/rest.js create mode 100644 node_modules/lodash/fp/restFrom.js create mode 100644 node_modules/lodash/fp/result.js create mode 100644 node_modules/lodash/fp/reverse.js create mode 100644 node_modules/lodash/fp/round.js create mode 100644 node_modules/lodash/fp/sample.js create mode 100644 node_modules/lodash/fp/sampleSize.js create mode 100644 node_modules/lodash/fp/seq.js create mode 100644 node_modules/lodash/fp/set.js create mode 100644 node_modules/lodash/fp/setWith.js create mode 100644 node_modules/lodash/fp/shuffle.js create mode 100644 node_modules/lodash/fp/size.js create mode 100644 node_modules/lodash/fp/slice.js create mode 100644 node_modules/lodash/fp/snakeCase.js create mode 100644 node_modules/lodash/fp/some.js create mode 100644 node_modules/lodash/fp/sortBy.js create mode 100644 node_modules/lodash/fp/sortedIndex.js create mode 100644 node_modules/lodash/fp/sortedIndexBy.js create mode 100644 node_modules/lodash/fp/sortedIndexOf.js create mode 100644 node_modules/lodash/fp/sortedLastIndex.js create mode 100644 node_modules/lodash/fp/sortedLastIndexBy.js create mode 100644 node_modules/lodash/fp/sortedLastIndexOf.js create mode 100644 node_modules/lodash/fp/sortedUniq.js create mode 100644 node_modules/lodash/fp/sortedUniqBy.js create mode 100644 node_modules/lodash/fp/split.js create mode 100644 node_modules/lodash/fp/spread.js create mode 100644 node_modules/lodash/fp/spreadFrom.js create mode 100644 node_modules/lodash/fp/startCase.js create mode 100644 node_modules/lodash/fp/startsWith.js create mode 100644 node_modules/lodash/fp/string.js create mode 100644 node_modules/lodash/fp/stubArray.js create mode 100644 node_modules/lodash/fp/stubFalse.js create mode 100644 node_modules/lodash/fp/stubObject.js create mode 100644 node_modules/lodash/fp/stubString.js create mode 100644 node_modules/lodash/fp/stubTrue.js create mode 100644 node_modules/lodash/fp/subtract.js create mode 100644 node_modules/lodash/fp/sum.js create mode 100644 node_modules/lodash/fp/sumBy.js create mode 100644 node_modules/lodash/fp/symmetricDifference.js create mode 100644 node_modules/lodash/fp/symmetricDifferenceBy.js create mode 100644 node_modules/lodash/fp/symmetricDifferenceWith.js create mode 100644 node_modules/lodash/fp/tail.js create mode 100644 node_modules/lodash/fp/take.js create mode 100644 node_modules/lodash/fp/takeLast.js create mode 100644 node_modules/lodash/fp/takeLastWhile.js create mode 100644 node_modules/lodash/fp/takeRight.js create mode 100644 node_modules/lodash/fp/takeRightWhile.js create mode 100644 node_modules/lodash/fp/takeWhile.js create mode 100644 node_modules/lodash/fp/tap.js create mode 100644 node_modules/lodash/fp/template.js create mode 100644 node_modules/lodash/fp/templateSettings.js create mode 100644 node_modules/lodash/fp/throttle.js create mode 100644 node_modules/lodash/fp/thru.js create mode 100644 node_modules/lodash/fp/times.js create mode 100644 node_modules/lodash/fp/toArray.js create mode 100644 node_modules/lodash/fp/toFinite.js create mode 100644 node_modules/lodash/fp/toInteger.js create mode 100644 node_modules/lodash/fp/toIterator.js create mode 100644 node_modules/lodash/fp/toJSON.js create mode 100644 node_modules/lodash/fp/toLength.js create mode 100644 node_modules/lodash/fp/toLower.js create mode 100644 node_modules/lodash/fp/toNumber.js create mode 100644 node_modules/lodash/fp/toPairs.js create mode 100644 node_modules/lodash/fp/toPairsIn.js create mode 100644 node_modules/lodash/fp/toPath.js create mode 100644 node_modules/lodash/fp/toPlainObject.js create mode 100644 node_modules/lodash/fp/toSafeInteger.js create mode 100644 node_modules/lodash/fp/toString.js create mode 100644 node_modules/lodash/fp/toUpper.js create mode 100644 node_modules/lodash/fp/transform.js create mode 100644 node_modules/lodash/fp/trim.js create mode 100644 node_modules/lodash/fp/trimChars.js create mode 100644 node_modules/lodash/fp/trimCharsEnd.js create mode 100644 node_modules/lodash/fp/trimCharsStart.js create mode 100644 node_modules/lodash/fp/trimEnd.js create mode 100644 node_modules/lodash/fp/trimStart.js create mode 100644 node_modules/lodash/fp/truncate.js create mode 100644 node_modules/lodash/fp/unapply.js create mode 100644 node_modules/lodash/fp/unary.js create mode 100644 node_modules/lodash/fp/unescape.js create mode 100644 node_modules/lodash/fp/union.js create mode 100644 node_modules/lodash/fp/unionBy.js create mode 100644 node_modules/lodash/fp/unionWith.js create mode 100644 node_modules/lodash/fp/uniq.js create mode 100644 node_modules/lodash/fp/uniqBy.js create mode 100644 node_modules/lodash/fp/uniqWith.js create mode 100644 node_modules/lodash/fp/uniqueId.js create mode 100644 node_modules/lodash/fp/unnest.js create mode 100644 node_modules/lodash/fp/unset.js create mode 100644 node_modules/lodash/fp/unzip.js create mode 100644 node_modules/lodash/fp/unzipWith.js create mode 100644 node_modules/lodash/fp/update.js create mode 100644 node_modules/lodash/fp/updateWith.js create mode 100644 node_modules/lodash/fp/upperCase.js create mode 100644 node_modules/lodash/fp/upperFirst.js create mode 100644 node_modules/lodash/fp/useWith.js create mode 100644 node_modules/lodash/fp/util.js create mode 100644 node_modules/lodash/fp/value.js create mode 100644 node_modules/lodash/fp/valueOf.js create mode 100644 node_modules/lodash/fp/values.js create mode 100644 node_modules/lodash/fp/valuesIn.js create mode 100644 node_modules/lodash/fp/where.js create mode 100644 node_modules/lodash/fp/whereEq.js create mode 100644 node_modules/lodash/fp/without.js create mode 100644 node_modules/lodash/fp/words.js create mode 100644 node_modules/lodash/fp/wrap.js create mode 100644 node_modules/lodash/fp/wrapperAt.js create mode 100644 node_modules/lodash/fp/wrapperChain.js create mode 100644 node_modules/lodash/fp/wrapperLodash.js create mode 100644 node_modules/lodash/fp/wrapperReverse.js create mode 100644 node_modules/lodash/fp/wrapperValue.js create mode 100644 node_modules/lodash/fp/xor.js create mode 100644 node_modules/lodash/fp/xorBy.js create mode 100644 node_modules/lodash/fp/xorWith.js create mode 100644 node_modules/lodash/fp/zip.js create mode 100644 node_modules/lodash/fp/zipAll.js create mode 100644 node_modules/lodash/fp/zipObj.js create mode 100644 node_modules/lodash/fp/zipObject.js create mode 100644 node_modules/lodash/fp/zipObjectDeep.js create mode 100644 node_modules/lodash/fp/zipWith.js create mode 100644 node_modules/lodash/fromPairs.js create mode 100644 node_modules/lodash/function.js create mode 100644 node_modules/lodash/functions.js create mode 100644 node_modules/lodash/functionsIn.js create mode 100644 node_modules/lodash/get.js create mode 100644 node_modules/lodash/groupBy.js create mode 100644 node_modules/lodash/gt.js create mode 100644 node_modules/lodash/gte.js create mode 100644 node_modules/lodash/has.js create mode 100644 node_modules/lodash/hasIn.js create mode 100644 node_modules/lodash/head.js create mode 100644 node_modules/lodash/identity.js create mode 100644 node_modules/lodash/inRange.js create mode 100644 node_modules/lodash/includes.js create mode 100644 node_modules/lodash/index.js create mode 100644 node_modules/lodash/indexOf.js create mode 100644 node_modules/lodash/initial.js create mode 100644 node_modules/lodash/intersection.js create mode 100644 node_modules/lodash/intersectionBy.js create mode 100644 node_modules/lodash/intersectionWith.js create mode 100644 node_modules/lodash/invert.js create mode 100644 node_modules/lodash/invertBy.js create mode 100644 node_modules/lodash/invoke.js create mode 100644 node_modules/lodash/invokeMap.js create mode 100644 node_modules/lodash/isArguments.js create mode 100644 node_modules/lodash/isArray.js create mode 100644 node_modules/lodash/isArrayBuffer.js create mode 100644 node_modules/lodash/isArrayLike.js create mode 100644 node_modules/lodash/isArrayLikeObject.js create mode 100644 node_modules/lodash/isBoolean.js create mode 100644 node_modules/lodash/isBuffer.js create mode 100644 node_modules/lodash/isDate.js create mode 100644 node_modules/lodash/isElement.js create mode 100644 node_modules/lodash/isEmpty.js create mode 100644 node_modules/lodash/isEqual.js create mode 100644 node_modules/lodash/isEqualWith.js create mode 100644 node_modules/lodash/isError.js create mode 100644 node_modules/lodash/isFinite.js create mode 100644 node_modules/lodash/isFunction.js create mode 100644 node_modules/lodash/isInteger.js create mode 100644 node_modules/lodash/isLength.js create mode 100644 node_modules/lodash/isMap.js create mode 100644 node_modules/lodash/isMatch.js create mode 100644 node_modules/lodash/isMatchWith.js create mode 100644 node_modules/lodash/isNaN.js create mode 100644 node_modules/lodash/isNative.js create mode 100644 node_modules/lodash/isNil.js create mode 100644 node_modules/lodash/isNull.js create mode 100644 node_modules/lodash/isNumber.js create mode 100644 node_modules/lodash/isObject.js create mode 100644 node_modules/lodash/isObjectLike.js create mode 100644 node_modules/lodash/isPlainObject.js create mode 100644 node_modules/lodash/isRegExp.js create mode 100644 node_modules/lodash/isSafeInteger.js create mode 100644 node_modules/lodash/isSet.js create mode 100644 node_modules/lodash/isString.js create mode 100644 node_modules/lodash/isSymbol.js create mode 100644 node_modules/lodash/isTypedArray.js create mode 100644 node_modules/lodash/isUndefined.js create mode 100644 node_modules/lodash/isWeakMap.js create mode 100644 node_modules/lodash/isWeakSet.js create mode 100644 node_modules/lodash/iteratee.js create mode 100644 node_modules/lodash/join.js create mode 100644 node_modules/lodash/kebabCase.js create mode 100644 node_modules/lodash/keyBy.js create mode 100644 node_modules/lodash/keys.js create mode 100644 node_modules/lodash/keysIn.js create mode 100644 node_modules/lodash/lang.js create mode 100644 node_modules/lodash/last.js create mode 100644 node_modules/lodash/lastIndexOf.js create mode 100644 node_modules/lodash/lodash.js create mode 100644 node_modules/lodash/lodash.min.js create mode 100644 node_modules/lodash/lowerCase.js create mode 100644 node_modules/lodash/lowerFirst.js create mode 100644 node_modules/lodash/lt.js create mode 100644 node_modules/lodash/lte.js create mode 100644 node_modules/lodash/map.js create mode 100644 node_modules/lodash/mapKeys.js create mode 100644 node_modules/lodash/mapValues.js create mode 100644 node_modules/lodash/matches.js create mode 100644 node_modules/lodash/matchesProperty.js create mode 100644 node_modules/lodash/math.js create mode 100644 node_modules/lodash/max.js create mode 100644 node_modules/lodash/maxBy.js create mode 100644 node_modules/lodash/mean.js create mode 100644 node_modules/lodash/meanBy.js create mode 100644 node_modules/lodash/memoize.js create mode 100644 node_modules/lodash/merge.js create mode 100644 node_modules/lodash/mergeWith.js create mode 100644 node_modules/lodash/method.js create mode 100644 node_modules/lodash/methodOf.js create mode 100644 node_modules/lodash/min.js create mode 100644 node_modules/lodash/minBy.js create mode 100644 node_modules/lodash/mixin.js create mode 100644 node_modules/lodash/multiply.js create mode 100644 node_modules/lodash/negate.js create mode 100644 node_modules/lodash/next.js create mode 100644 node_modules/lodash/noop.js create mode 100644 node_modules/lodash/now.js create mode 100644 node_modules/lodash/nth.js create mode 100644 node_modules/lodash/nthArg.js create mode 100644 node_modules/lodash/number.js create mode 100644 node_modules/lodash/object.js create mode 100644 node_modules/lodash/omit.js create mode 100644 node_modules/lodash/omitBy.js create mode 100644 node_modules/lodash/once.js create mode 100644 node_modules/lodash/orderBy.js create mode 100644 node_modules/lodash/over.js create mode 100644 node_modules/lodash/overArgs.js create mode 100644 node_modules/lodash/overEvery.js create mode 100644 node_modules/lodash/overSome.js create mode 100644 node_modules/lodash/package.json create mode 100644 node_modules/lodash/pad.js create mode 100644 node_modules/lodash/padEnd.js create mode 100644 node_modules/lodash/padStart.js create mode 100644 node_modules/lodash/parseInt.js create mode 100644 node_modules/lodash/partial.js create mode 100644 node_modules/lodash/partialRight.js create mode 100644 node_modules/lodash/partition.js create mode 100644 node_modules/lodash/pick.js create mode 100644 node_modules/lodash/pickBy.js create mode 100644 node_modules/lodash/plant.js create mode 100644 node_modules/lodash/property.js create mode 100644 node_modules/lodash/propertyOf.js create mode 100644 node_modules/lodash/pull.js create mode 100644 node_modules/lodash/pullAll.js create mode 100644 node_modules/lodash/pullAllBy.js create mode 100644 node_modules/lodash/pullAllWith.js create mode 100644 node_modules/lodash/pullAt.js create mode 100644 node_modules/lodash/random.js create mode 100644 node_modules/lodash/range.js create mode 100644 node_modules/lodash/rangeRight.js create mode 100644 node_modules/lodash/rearg.js create mode 100644 node_modules/lodash/reduce.js create mode 100644 node_modules/lodash/reduceRight.js create mode 100644 node_modules/lodash/reject.js create mode 100644 node_modules/lodash/release.md create mode 100644 node_modules/lodash/remove.js create mode 100644 node_modules/lodash/repeat.js create mode 100644 node_modules/lodash/replace.js create mode 100644 node_modules/lodash/rest.js create mode 100644 node_modules/lodash/result.js create mode 100644 node_modules/lodash/reverse.js create mode 100644 node_modules/lodash/round.js create mode 100644 node_modules/lodash/sample.js create mode 100644 node_modules/lodash/sampleSize.js create mode 100644 node_modules/lodash/seq.js create mode 100644 node_modules/lodash/set.js create mode 100644 node_modules/lodash/setWith.js create mode 100644 node_modules/lodash/shuffle.js create mode 100644 node_modules/lodash/size.js create mode 100644 node_modules/lodash/slice.js create mode 100644 node_modules/lodash/snakeCase.js create mode 100644 node_modules/lodash/some.js create mode 100644 node_modules/lodash/sortBy.js create mode 100644 node_modules/lodash/sortedIndex.js create mode 100644 node_modules/lodash/sortedIndexBy.js create mode 100644 node_modules/lodash/sortedIndexOf.js create mode 100644 node_modules/lodash/sortedLastIndex.js create mode 100644 node_modules/lodash/sortedLastIndexBy.js create mode 100644 node_modules/lodash/sortedLastIndexOf.js create mode 100644 node_modules/lodash/sortedUniq.js create mode 100644 node_modules/lodash/sortedUniqBy.js create mode 100644 node_modules/lodash/split.js create mode 100644 node_modules/lodash/spread.js create mode 100644 node_modules/lodash/startCase.js create mode 100644 node_modules/lodash/startsWith.js create mode 100644 node_modules/lodash/string.js create mode 100644 node_modules/lodash/stubArray.js create mode 100644 node_modules/lodash/stubFalse.js create mode 100644 node_modules/lodash/stubObject.js create mode 100644 node_modules/lodash/stubString.js create mode 100644 node_modules/lodash/stubTrue.js create mode 100644 node_modules/lodash/subtract.js create mode 100644 node_modules/lodash/sum.js create mode 100644 node_modules/lodash/sumBy.js create mode 100644 node_modules/lodash/tail.js create mode 100644 node_modules/lodash/take.js create mode 100644 node_modules/lodash/takeRight.js create mode 100644 node_modules/lodash/takeRightWhile.js create mode 100644 node_modules/lodash/takeWhile.js create mode 100644 node_modules/lodash/tap.js create mode 100644 node_modules/lodash/template.js create mode 100644 node_modules/lodash/templateSettings.js create mode 100644 node_modules/lodash/throttle.js create mode 100644 node_modules/lodash/thru.js create mode 100644 node_modules/lodash/times.js create mode 100644 node_modules/lodash/toArray.js create mode 100644 node_modules/lodash/toFinite.js create mode 100644 node_modules/lodash/toInteger.js create mode 100644 node_modules/lodash/toIterator.js create mode 100644 node_modules/lodash/toJSON.js create mode 100644 node_modules/lodash/toLength.js create mode 100644 node_modules/lodash/toLower.js create mode 100644 node_modules/lodash/toNumber.js create mode 100644 node_modules/lodash/toPairs.js create mode 100644 node_modules/lodash/toPairsIn.js create mode 100644 node_modules/lodash/toPath.js create mode 100644 node_modules/lodash/toPlainObject.js create mode 100644 node_modules/lodash/toSafeInteger.js create mode 100644 node_modules/lodash/toString.js create mode 100644 node_modules/lodash/toUpper.js create mode 100644 node_modules/lodash/transform.js create mode 100644 node_modules/lodash/trim.js create mode 100644 node_modules/lodash/trimEnd.js create mode 100644 node_modules/lodash/trimStart.js create mode 100644 node_modules/lodash/truncate.js create mode 100644 node_modules/lodash/unary.js create mode 100644 node_modules/lodash/unescape.js create mode 100644 node_modules/lodash/union.js create mode 100644 node_modules/lodash/unionBy.js create mode 100644 node_modules/lodash/unionWith.js create mode 100644 node_modules/lodash/uniq.js create mode 100644 node_modules/lodash/uniqBy.js create mode 100644 node_modules/lodash/uniqWith.js create mode 100644 node_modules/lodash/uniqueId.js create mode 100644 node_modules/lodash/unset.js create mode 100644 node_modules/lodash/unzip.js create mode 100644 node_modules/lodash/unzipWith.js create mode 100644 node_modules/lodash/update.js create mode 100644 node_modules/lodash/updateWith.js create mode 100644 node_modules/lodash/upperCase.js create mode 100644 node_modules/lodash/upperFirst.js create mode 100644 node_modules/lodash/util.js create mode 100644 node_modules/lodash/value.js create mode 100644 node_modules/lodash/valueOf.js create mode 100644 node_modules/lodash/values.js create mode 100644 node_modules/lodash/valuesIn.js create mode 100644 node_modules/lodash/without.js create mode 100644 node_modules/lodash/words.js create mode 100644 node_modules/lodash/wrap.js create mode 100644 node_modules/lodash/wrapperAt.js create mode 100644 node_modules/lodash/wrapperChain.js create mode 100644 node_modules/lodash/wrapperLodash.js create mode 100644 node_modules/lodash/wrapperReverse.js create mode 100644 node_modules/lodash/wrapperValue.js create mode 100644 node_modules/lodash/xor.js create mode 100644 node_modules/lodash/xorBy.js create mode 100644 node_modules/lodash/xorWith.js create mode 100644 node_modules/lodash/zip.js create mode 100644 node_modules/lodash/zipObject.js create mode 100644 node_modules/lodash/zipObjectDeep.js create mode 100644 node_modules/lodash/zipWith.js create mode 100644 node_modules/log-symbols/browser.js create mode 100644 node_modules/log-symbols/index.d.ts create mode 100644 node_modules/log-symbols/index.js create mode 100644 node_modules/log-symbols/license create mode 100644 node_modules/log-symbols/package.json create mode 100644 node_modules/log-symbols/readme.md create mode 100644 node_modules/loose-envify/LICENSE create mode 100644 node_modules/loose-envify/README.md create mode 100755 node_modules/loose-envify/cli.js create mode 100644 node_modules/loose-envify/custom.js create mode 100644 node_modules/loose-envify/index.js create mode 100644 node_modules/loose-envify/loose-envify.js create mode 100644 node_modules/loose-envify/package.json create mode 100644 node_modules/loose-envify/replace.js create mode 100644 node_modules/marked-terminal/LICENSE create mode 100644 node_modules/marked-terminal/README.md create mode 100644 node_modules/marked-terminal/index.cjs create mode 100644 node_modules/marked-terminal/index.js create mode 100644 node_modules/marked-terminal/node_modules/ansi-escapes/index.d.ts create mode 100644 node_modules/marked-terminal/node_modules/ansi-escapes/index.js create mode 100644 node_modules/marked-terminal/node_modules/ansi-escapes/license create mode 100644 node_modules/marked-terminal/node_modules/ansi-escapes/package.json create mode 100644 node_modules/marked-terminal/node_modules/ansi-escapes/readme.md create mode 100644 node_modules/marked-terminal/node_modules/type-fest/base.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/index.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/license create mode 100644 node_modules/marked-terminal/node_modules/type-fest/package.json create mode 100644 node_modules/marked-terminal/node_modules/type-fest/readme.md create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/async-return-type.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/asyncify.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/basic.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/conditional-except.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/conditional-keys.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/conditional-pick.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/entries.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/entry.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/except.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/fixed-length-array.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/iterable-element.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/literal-union.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/merge-exclusive.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/merge.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/mutable.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/observable-like.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/opaque.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/package-json.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/partial-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/primitive.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/promisable.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/promise-value.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/readonly-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/require-at-least-one.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/require-exactly-one.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/set-optional.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/set-required.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/set-return-type.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/simplify.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/stringified.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/tsconfig-json.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/typed-array.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/union-to-intersection.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/utilities.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/source/value-of.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/camel-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/camel-cased-properties-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/camel-cased-properties.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/delimiter-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/delimiter-cased-properties-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/delimiter-cased-properties.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/get.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/includes.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/index.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/kebab-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/kebab-cased-properties-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/kebab-cased-properties.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/last-array-element.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/pascal-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/pascal-cased-properties-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/pascal-cased-properties.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/screaming-snake-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/snake-case.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/snake-cased-properties-deep.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/snake-cased-properties.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/split.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/trim.d.ts create mode 100644 node_modules/marked-terminal/node_modules/type-fest/ts41/utilities.d.ts create mode 100644 node_modules/marked-terminal/package.json create mode 100644 node_modules/marked/LICENSE.md create mode 100644 node_modules/marked/README.md create mode 100755 node_modules/marked/bin/marked.js create mode 100644 node_modules/marked/man/marked.1 create mode 100644 node_modules/marked/man/marked.1.txt create mode 100644 node_modules/marked/marked.min.js create mode 100644 node_modules/marked/package.json create mode 100644 node_modules/marked/src/Lexer.js create mode 100644 node_modules/marked/src/Parser.js create mode 100644 node_modules/marked/src/Renderer.js create mode 100644 node_modules/marked/src/Slugger.js create mode 100644 node_modules/marked/src/TextRenderer.js create mode 100644 node_modules/marked/src/Tokenizer.js create mode 100644 node_modules/marked/src/defaults.js create mode 100644 node_modules/marked/src/helpers.js create mode 100644 node_modules/marked/src/marked.js create mode 100644 node_modules/marked/src/rules.js create mode 100644 node_modules/match-sorter/CHANGELOG.md create mode 100644 node_modules/match-sorter/LICENSE create mode 100644 node_modules/match-sorter/README.md create mode 100644 node_modules/match-sorter/package.json create mode 100644 node_modules/microseconds/.prettierrc create mode 100644 node_modules/microseconds/README.md create mode 100644 node_modules/microseconds/index.js create mode 100644 node_modules/microseconds/now.js create mode 100644 node_modules/microseconds/package.json create mode 100644 node_modules/microseconds/parse.js create mode 100644 node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mime-db/LICENSE create mode 100644 node_modules/mime-db/README.md create mode 100644 node_modules/mime-db/db.json create mode 100644 node_modules/mime-db/index.js create mode 100644 node_modules/mime-db/package.json create mode 100644 node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mime-types/LICENSE create mode 100644 node_modules/mime-types/README.md create mode 100644 node_modules/mime-types/index.js create mode 100644 node_modules/mime-types/package.json create mode 100644 node_modules/mimic-fn/index.d.ts create mode 100644 node_modules/mimic-fn/index.js create mode 100644 node_modules/mimic-fn/license create mode 100644 node_modules/mimic-fn/package.json create mode 100644 node_modules/mimic-fn/readme.md create mode 100644 node_modules/minimatch/LICENSE create mode 100644 node_modules/minimatch/README.md create mode 100644 node_modules/minimatch/minimatch.js create mode 100644 node_modules/minimatch/package.json create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/mute-stream/LICENSE create mode 100644 node_modules/mute-stream/README.md create mode 100644 node_modules/mute-stream/mute.js create mode 100644 node_modules/mute-stream/package.json create mode 100644 node_modules/mz/HISTORY.md create mode 100644 node_modules/mz/LICENSE create mode 100644 node_modules/mz/README.md create mode 100644 node_modules/mz/child_process.js create mode 100644 node_modules/mz/crypto.js create mode 100644 node_modules/mz/dns.js create mode 100644 node_modules/mz/fs.js create mode 100644 node_modules/mz/index.js create mode 100644 node_modules/mz/package.json create mode 100644 node_modules/mz/readline.js create mode 100644 node_modules/mz/zlib.js create mode 100644 node_modules/nano-time/.npmignore create mode 100644 node_modules/nano-time/README.md create mode 100644 node_modules/nano-time/index.js create mode 100644 node_modules/nano-time/package.json create mode 100644 node_modules/node-emoji/.github/FUNDING.yml create mode 100644 node_modules/node-emoji/.travis.yml create mode 100644 node_modules/node-emoji/LICENSE create mode 100644 node_modules/node-emoji/README.md create mode 100644 node_modules/node-emoji/index.js create mode 100644 node_modules/node-emoji/package.json create mode 100644 node_modules/node-emoji/test/emoji.js create mode 100644 node_modules/object-assign/index.js create mode 100644 node_modules/object-assign/license create mode 100644 node_modules/object-assign/package.json create mode 100644 node_modules/object-assign/readme.md create mode 100644 node_modules/oblivious-set/.github/workflows/main.yml create mode 100644 node_modules/oblivious-set/LICENSE create mode 100644 node_modules/oblivious-set/README.md create mode 100644 node_modules/oblivious-set/package.json create mode 100644 node_modules/oblivious-set/src/index.ts create mode 100644 node_modules/oblivious-set/test/unit.test.ts create mode 100644 node_modules/oblivious-set/tsconfig.json create mode 100644 node_modules/oblivious-set/tslint.json create mode 100644 node_modules/once/LICENSE create mode 100644 node_modules/once/README.md create mode 100644 node_modules/once/once.js create mode 100644 node_modules/once/package.json create mode 100644 node_modules/onetime/index.d.ts create mode 100644 node_modules/onetime/index.js create mode 100644 node_modules/onetime/license create mode 100644 node_modules/onetime/package.json create mode 100644 node_modules/onetime/readme.md create mode 100644 node_modules/ora/index.d.ts create mode 100644 node_modules/ora/index.js create mode 100644 node_modules/ora/license create mode 100644 node_modules/ora/node_modules/cli-cursor/index.d.ts create mode 100644 node_modules/ora/node_modules/cli-cursor/index.js create mode 100644 node_modules/ora/node_modules/cli-cursor/license create mode 100644 node_modules/ora/node_modules/cli-cursor/package.json create mode 100644 node_modules/ora/node_modules/cli-cursor/readme.md create mode 100644 node_modules/ora/node_modules/restore-cursor/index.d.ts create mode 100644 node_modules/ora/node_modules/restore-cursor/index.js create mode 100644 node_modules/ora/node_modules/restore-cursor/license create mode 100644 node_modules/ora/node_modules/restore-cursor/package.json create mode 100644 node_modules/ora/node_modules/restore-cursor/readme.md create mode 100644 node_modules/ora/package.json create mode 100644 node_modules/ora/readme.md create mode 100644 node_modules/ora/utilities.js create mode 100644 node_modules/os-tmpdir/index.js create mode 100644 node_modules/os-tmpdir/license create mode 100644 node_modules/os-tmpdir/package.json create mode 100644 node_modules/os-tmpdir/readme.md create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/LICENSE create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/README.md create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5/LICENSE create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5/README.md create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5/package.json create mode 100644 node_modules/parse5-htmlparser2-tree-adapter/package.json create mode 100644 node_modules/parse5/LICENSE create mode 100644 node_modules/parse5/README.md create mode 100644 node_modules/parse5/package.json create mode 100644 node_modules/patch-console/package.json create mode 100644 node_modules/patch-console/readme.md create mode 100644 node_modules/path-is-absolute/index.js create mode 100644 node_modules/path-is-absolute/license create mode 100644 node_modules/path-is-absolute/package.json create mode 100644 node_modules/path-is-absolute/readme.md create mode 100644 node_modules/prop-types/LICENSE create mode 100644 node_modules/prop-types/README.md create mode 100644 node_modules/prop-types/checkPropTypes.js create mode 100644 node_modules/prop-types/factory.js create mode 100644 node_modules/prop-types/factoryWithThrowingShims.js create mode 100644 node_modules/prop-types/factoryWithTypeCheckers.js create mode 100644 node_modules/prop-types/index.js create mode 100644 node_modules/prop-types/package.json create mode 100644 node_modules/prop-types/prop-types.js create mode 100644 node_modules/prop-types/prop-types.min.js create mode 100644 node_modules/proxy-from-env/.eslintrc create mode 100644 node_modules/proxy-from-env/.travis.yml create mode 100644 node_modules/proxy-from-env/LICENSE create mode 100644 node_modules/proxy-from-env/README.md create mode 100644 node_modules/proxy-from-env/index.js create mode 100644 node_modules/proxy-from-env/package.json create mode 100644 node_modules/proxy-from-env/test.js create mode 100644 node_modules/radash/LICENSE.md create mode 100644 node_modules/radash/README.md create mode 100644 node_modules/radash/package.json create mode 100644 node_modules/react-devtools-core/README.md create mode 100644 node_modules/react-devtools-core/backend.js create mode 100644 node_modules/react-devtools-core/package.json create mode 100644 node_modules/react-devtools-core/standalone.js create mode 100644 node_modules/react-dom/LICENSE create mode 100644 node_modules/react-dom/README.md create mode 100644 node_modules/react-dom/build-info.json create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.development.js create mode 100644 node_modules/react-dom/cjs/react-dom.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.profiling.min.js create mode 100644 node_modules/react-dom/index.js create mode 100644 node_modules/react-dom/package.json create mode 100644 node_modules/react-dom/profiling.js create mode 100644 node_modules/react-dom/server.browser.js create mode 100644 node_modules/react-dom/server.js create mode 100644 node_modules/react-dom/server.node.js create mode 100644 node_modules/react-dom/test-utils.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.development.js create mode 100644 node_modules/react-dom/umd/react-dom.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.profiling.min.js create mode 100644 node_modules/react-is/LICENSE create mode 100644 node_modules/react-is/README.md create mode 100644 node_modules/react-is/build-info.json create mode 100644 node_modules/react-is/cjs/react-is.development.js create mode 100644 node_modules/react-is/cjs/react-is.production.min.js create mode 100644 node_modules/react-is/index.js create mode 100644 node_modules/react-is/package.json create mode 100644 node_modules/react-is/umd/react-is.development.js create mode 100644 node_modules/react-is/umd/react-is.production.min.js create mode 100644 node_modules/react-query/LICENSE create mode 100644 node_modules/react-query/README.md create mode 100644 node_modules/react-query/broadcastQueryClient-experimental/package.json create mode 100644 node_modules/react-query/core/package.json create mode 100644 node_modules/react-query/createAsyncStoragePersistor-experimental/package.json create mode 100644 node_modules/react-query/createWebStoragePersistor-experimental/package.json create mode 100644 node_modules/react-query/devtools/development/package.json create mode 100644 node_modules/react-query/devtools/index.js create mode 100644 node_modules/react-query/devtools/package.json create mode 100644 node_modules/react-query/es/broadcastQueryClient-experimental/index.js create mode 100644 node_modules/react-query/es/core/focusManager.js create mode 100644 node_modules/react-query/es/core/hydration.js create mode 100644 node_modules/react-query/es/core/index.js create mode 100644 node_modules/react-query/es/core/infiniteQueryBehavior.js create mode 100644 node_modules/react-query/es/core/infiniteQueryObserver.js create mode 100644 node_modules/react-query/es/core/logger.js create mode 100644 node_modules/react-query/es/core/mutation.js create mode 100644 node_modules/react-query/es/core/mutationCache.js create mode 100644 node_modules/react-query/es/core/mutationObserver.js create mode 100644 node_modules/react-query/es/core/notifyManager.js create mode 100644 node_modules/react-query/es/core/onlineManager.js create mode 100644 node_modules/react-query/es/core/queriesObserver.js create mode 100644 node_modules/react-query/es/core/query.js create mode 100644 node_modules/react-query/es/core/queryCache.js create mode 100644 node_modules/react-query/es/core/queryClient.js create mode 100644 node_modules/react-query/es/core/queryObserver.js create mode 100644 node_modules/react-query/es/core/retryer.js create mode 100644 node_modules/react-query/es/core/subscribable.js create mode 100644 node_modules/react-query/es/core/types.js create mode 100644 node_modules/react-query/es/core/utils.js create mode 100644 node_modules/react-query/es/createAsyncStoragePersistor-experimental/index.js create mode 100644 node_modules/react-query/es/createWebStoragePersistor-experimental/index.js create mode 100644 node_modules/react-query/es/devtools/Explorer.js create mode 100644 node_modules/react-query/es/devtools/Logo.js create mode 100644 node_modules/react-query/es/devtools/devtools.js create mode 100644 node_modules/react-query/es/devtools/index.js create mode 100644 node_modules/react-query/es/devtools/styledComponents.js create mode 100644 node_modules/react-query/es/devtools/theme.js create mode 100644 node_modules/react-query/es/devtools/useLocalStorage.js create mode 100644 node_modules/react-query/es/devtools/useMediaQuery.js create mode 100644 node_modules/react-query/es/devtools/utils.js create mode 100644 node_modules/react-query/es/hydration/index.js create mode 100644 node_modules/react-query/es/index.js create mode 100644 node_modules/react-query/es/persistQueryClient-experimental/index.js create mode 100644 node_modules/react-query/es/react/Hydrate.js create mode 100644 node_modules/react-query/es/react/QueryClientProvider.js create mode 100644 node_modules/react-query/es/react/QueryErrorResetBoundary.js create mode 100644 node_modules/react-query/es/react/index.js create mode 100644 node_modules/react-query/es/react/logger.js create mode 100644 node_modules/react-query/es/react/logger.native.js create mode 100644 node_modules/react-query/es/react/reactBatchedUpdates.js create mode 100644 node_modules/react-query/es/react/reactBatchedUpdates.native.js create mode 100644 node_modules/react-query/es/react/setBatchUpdatesFn.js create mode 100644 node_modules/react-query/es/react/setLogger.js create mode 100644 node_modules/react-query/es/react/types.js create mode 100644 node_modules/react-query/es/react/useBaseQuery.js create mode 100644 node_modules/react-query/es/react/useInfiniteQuery.js create mode 100644 node_modules/react-query/es/react/useIsFetching.js create mode 100644 node_modules/react-query/es/react/useIsMutating.js create mode 100644 node_modules/react-query/es/react/useMutation.js create mode 100644 node_modules/react-query/es/react/useQueries.js create mode 100644 node_modules/react-query/es/react/useQuery.js create mode 100644 node_modules/react-query/es/react/utils.js create mode 100644 node_modules/react-query/es/ts3.8/index.js create mode 100644 node_modules/react-query/es/ts3.8/useQueries.js create mode 100644 node_modules/react-query/hydration/package.json create mode 100644 node_modules/react-query/package.json create mode 100644 node_modules/react-query/persistQueryClient-experimental/package.json create mode 100644 node_modules/react-query/react/package.json create mode 100644 node_modules/react-query/types/broadcastQueryClient-experimental/index.d.ts create mode 100644 node_modules/react-query/types/core/focusManager.d.ts create mode 100644 node_modules/react-query/types/core/hydration.d.ts create mode 100644 node_modules/react-query/types/core/index.d.ts create mode 100644 node_modules/react-query/types/core/infiniteQueryBehavior.d.ts create mode 100644 node_modules/react-query/types/core/infiniteQueryObserver.d.ts create mode 100644 node_modules/react-query/types/core/logger.d.ts create mode 100644 node_modules/react-query/types/core/mutation.d.ts create mode 100644 node_modules/react-query/types/core/mutationCache.d.ts create mode 100644 node_modules/react-query/types/core/mutationObserver.d.ts create mode 100644 node_modules/react-query/types/core/notifyManager.d.ts create mode 100644 node_modules/react-query/types/core/onlineManager.d.ts create mode 100644 node_modules/react-query/types/core/queriesObserver.d.ts create mode 100644 node_modules/react-query/types/core/query.d.ts create mode 100644 node_modules/react-query/types/core/queryCache.d.ts create mode 100644 node_modules/react-query/types/core/queryClient.d.ts create mode 100644 node_modules/react-query/types/core/queryObserver.d.ts create mode 100644 node_modules/react-query/types/core/retryer.d.ts create mode 100644 node_modules/react-query/types/core/subscribable.d.ts create mode 100644 node_modules/react-query/types/core/types.d.ts create mode 100644 node_modules/react-query/types/core/utils.d.ts create mode 100644 node_modules/react-query/types/createAsyncStoragePersistor-experimental/index.d.ts create mode 100644 node_modules/react-query/types/createWebStoragePersistor-experimental/index.d.ts create mode 100644 node_modules/react-query/types/devtools/Explorer.d.ts create mode 100644 node_modules/react-query/types/devtools/Logo.d.ts create mode 100644 node_modules/react-query/types/devtools/devtools.d.ts create mode 100644 node_modules/react-query/types/devtools/index.d.ts create mode 100644 node_modules/react-query/types/devtools/styledComponents.d.ts create mode 100644 node_modules/react-query/types/devtools/theme.d.ts create mode 100644 node_modules/react-query/types/devtools/useLocalStorage.d.ts create mode 100644 node_modules/react-query/types/devtools/useMediaQuery.d.ts create mode 100644 node_modules/react-query/types/devtools/utils.d.ts create mode 100644 node_modules/react-query/types/hydration/index.d.ts create mode 100644 node_modules/react-query/types/index.d.ts create mode 100644 node_modules/react-query/types/persistQueryClient-experimental/index.d.ts create mode 100644 node_modules/react-query/types/react/Hydrate.d.ts create mode 100644 node_modules/react-query/types/react/QueryClientProvider.d.ts create mode 100644 node_modules/react-query/types/react/QueryErrorResetBoundary.d.ts create mode 100644 node_modules/react-query/types/react/index.d.ts create mode 100644 node_modules/react-query/types/react/logger.d.ts create mode 100644 node_modules/react-query/types/react/reactBatchedUpdates.d.ts create mode 100644 node_modules/react-query/types/react/setBatchUpdatesFn.d.ts create mode 100644 node_modules/react-query/types/react/setLogger.d.ts create mode 100644 node_modules/react-query/types/react/types.d.ts create mode 100644 node_modules/react-query/types/react/useBaseQuery.d.ts create mode 100644 node_modules/react-query/types/react/useInfiniteQuery.d.ts create mode 100644 node_modules/react-query/types/react/useIsFetching.d.ts create mode 100644 node_modules/react-query/types/react/useIsMutating.d.ts create mode 100644 node_modules/react-query/types/react/useMutation.d.ts create mode 100644 node_modules/react-query/types/react/useQueries.d.ts create mode 100644 node_modules/react-query/types/react/useQuery.d.ts create mode 100644 node_modules/react-query/types/react/utils.d.ts create mode 100644 node_modules/react-query/types/ts3.8/index.d.ts create mode 100644 node_modules/react-query/types/ts3.8/useQueries.d.ts create mode 100644 node_modules/react-reconciler/LICENSE create mode 100644 node_modules/react-reconciler/README.md create mode 100644 node_modules/react-reconciler/build-info.json create mode 100644 node_modules/react-reconciler/cjs/react-reconciler-reflection.development.js create mode 100644 node_modules/react-reconciler/cjs/react-reconciler-reflection.production.min.js create mode 100644 node_modules/react-reconciler/cjs/react-reconciler.development.js create mode 100644 node_modules/react-reconciler/cjs/react-reconciler.production.min.js create mode 100644 node_modules/react-reconciler/cjs/react-reconciler.profiling.min.js create mode 100644 node_modules/react-reconciler/index.js create mode 100644 node_modules/react-reconciler/package.json create mode 100644 node_modules/react-reconciler/reflection.js create mode 100644 node_modules/react/LICENSE create mode 100644 node_modules/react/README.md create mode 100644 node_modules/react/build-info.json create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react.development.js create mode 100644 node_modules/react/cjs/react.production.min.js create mode 100644 node_modules/react/index.js create mode 100644 node_modules/react/jsx-dev-runtime.js create mode 100644 node_modules/react/jsx-runtime.js create mode 100644 node_modules/react/package.json create mode 100644 node_modules/react/umd/react.development.js create mode 100644 node_modules/react/umd/react.production.min.js create mode 100644 node_modules/react/umd/react.profiling.min.js create mode 100644 node_modules/readable-stream/CONTRIBUTING.md create mode 100644 node_modules/readable-stream/GOVERNANCE.md create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/errors-browser.js create mode 100644 node_modules/readable-stream/errors.js create mode 100644 node_modules/readable-stream/experimentalWarning.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/readable-browser.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/redeyed/.npmignore create mode 100644 node_modules/redeyed/.travis.yml create mode 100644 node_modules/redeyed/LICENSE create mode 100644 node_modules/redeyed/README.md create mode 100644 node_modules/redeyed/config-es5.js create mode 100644 node_modules/redeyed/config.js create mode 100644 node_modules/redeyed/examples/browser/index.css create mode 100644 node_modules/redeyed/examples/browser/index.html create mode 100644 node_modules/redeyed/examples/browser/index.js create mode 100644 node_modules/redeyed/examples/browser/sample-config.js create mode 100644 node_modules/redeyed/examples/replace-log.js create mode 100644 node_modules/redeyed/examples/sources/log.js create mode 100644 node_modules/redeyed/package.json create mode 100644 node_modules/redeyed/redeyed.js create mode 100644 node_modules/redeyed/test/redeyed-before-after-config.js create mode 100644 node_modules/redeyed/test/redeyed-comments.js create mode 100644 node_modules/redeyed/test/redeyed-config-with-undefineds.js create mode 100644 node_modules/redeyed/test/redeyed-function-config-extra-params.js create mode 100644 node_modules/redeyed/test/redeyed-function-config-skipping-tokens.js create mode 100644 node_modules/redeyed/test/redeyed-function-config.js create mode 100644 node_modules/redeyed/test/redeyed-incomplete.js create mode 100644 node_modules/redeyed/test/redeyed-jsx.js create mode 100644 node_modules/redeyed/test/redeyed-keywords.js create mode 100644 node_modules/redeyed/test/redeyed-mixed.js create mode 100644 node_modules/redeyed/test/redeyed-result.js create mode 100644 node_modules/redeyed/test/redeyed-script-level-return.js create mode 100644 node_modules/redeyed/test/redeyed-shebang.js create mode 100644 node_modules/redeyed/test/redeyed-smoke.js create mode 100644 node_modules/redeyed/test/redeyed-string-config.js create mode 100644 node_modules/redeyed/test/redeyed-types.js create mode 100644 node_modules/redeyed/test/redeyed-upcoming.js create mode 100644 node_modules/regenerator-runtime/LICENSE create mode 100644 node_modules/regenerator-runtime/README.md create mode 100644 node_modules/regenerator-runtime/package.json create mode 100644 node_modules/regenerator-runtime/path.js create mode 100644 node_modules/regenerator-runtime/runtime.js create mode 100644 node_modules/remove-accents/.npmignore create mode 100644 node_modules/remove-accents/.travis.yml create mode 100644 node_modules/remove-accents/LICENSE create mode 100644 node_modules/remove-accents/README.md create mode 100644 node_modules/remove-accents/index.d.ts create mode 100644 node_modules/remove-accents/index.js create mode 100644 node_modules/remove-accents/package.json create mode 100644 node_modules/remove-accents/test.js create mode 100644 node_modules/require-directory/.jshintrc create mode 100644 node_modules/require-directory/.npmignore create mode 100644 node_modules/require-directory/.travis.yml create mode 100644 node_modules/require-directory/LICENSE create mode 100644 node_modules/require-directory/README.markdown create mode 100644 node_modules/require-directory/index.js create mode 100644 node_modules/require-directory/package.json create mode 100644 node_modules/restore-cursor/index.d.ts create mode 100644 node_modules/restore-cursor/index.js create mode 100644 node_modules/restore-cursor/license create mode 100644 node_modules/restore-cursor/package.json create mode 100644 node_modules/restore-cursor/readme.md create mode 100644 node_modules/rimraf/CHANGELOG.md create mode 100644 node_modules/rimraf/LICENSE create mode 100644 node_modules/rimraf/README.md create mode 100755 node_modules/rimraf/bin.js create mode 100644 node_modules/rimraf/package.json create mode 100644 node_modules/rimraf/rimraf.js create mode 100644 node_modules/run-async/LICENSE create mode 100644 node_modules/run-async/README.md create mode 100644 node_modules/run-async/index.js create mode 100644 node_modules/run-async/package.json create mode 100644 node_modules/rxjs/CHANGELOG.md create mode 100644 node_modules/rxjs/CODE_OF_CONDUCT.md create mode 100644 node_modules/rxjs/LICENSE.txt create mode 100644 node_modules/rxjs/README.md create mode 100644 node_modules/rxjs/ajax/package.json create mode 100644 node_modules/rxjs/fetch/package.json create mode 100644 node_modules/rxjs/operators/package.json create mode 100644 node_modules/rxjs/package.json create mode 100644 node_modules/rxjs/src/Rx.global.js create mode 100644 node_modules/rxjs/src/ajax/index.ts create mode 100644 node_modules/rxjs/src/fetch/index.ts create mode 100644 node_modules/rxjs/src/index.ts create mode 100644 node_modules/rxjs/src/internal/AnyCatcher.ts create mode 100644 node_modules/rxjs/src/internal/AsyncSubject.ts create mode 100644 node_modules/rxjs/src/internal/BehaviorSubject.ts create mode 100644 node_modules/rxjs/src/internal/Notification.ts create mode 100644 node_modules/rxjs/src/internal/NotificationFactories.ts create mode 100644 node_modules/rxjs/src/internal/Observable.ts create mode 100644 node_modules/rxjs/src/internal/Operator.ts create mode 100644 node_modules/rxjs/src/internal/ReplaySubject.ts create mode 100644 node_modules/rxjs/src/internal/Scheduler.ts create mode 100644 node_modules/rxjs/src/internal/Subject.ts create mode 100644 node_modules/rxjs/src/internal/Subscriber.ts create mode 100644 node_modules/rxjs/src/internal/Subscription.ts create mode 100644 node_modules/rxjs/src/internal/ajax/AjaxResponse.ts create mode 100644 node_modules/rxjs/src/internal/ajax/ajax.ts create mode 100644 node_modules/rxjs/src/internal/ajax/errors.ts create mode 100644 node_modules/rxjs/src/internal/ajax/getXHRResponse.ts create mode 100644 node_modules/rxjs/src/internal/ajax/types.ts create mode 100644 node_modules/rxjs/src/internal/config.ts create mode 100644 node_modules/rxjs/src/internal/firstValueFrom.ts create mode 100644 node_modules/rxjs/src/internal/lastValueFrom.ts create mode 100644 node_modules/rxjs/src/internal/observable/ConnectableObservable.ts create mode 100644 node_modules/rxjs/src/internal/observable/bindCallback.ts create mode 100644 node_modules/rxjs/src/internal/observable/bindCallbackInternals.ts create mode 100644 node_modules/rxjs/src/internal/observable/bindNodeCallback.ts create mode 100644 node_modules/rxjs/src/internal/observable/combineLatest.ts create mode 100644 node_modules/rxjs/src/internal/observable/concat.ts create mode 100644 node_modules/rxjs/src/internal/observable/connectable.ts create mode 100644 node_modules/rxjs/src/internal/observable/defer.ts create mode 100644 node_modules/rxjs/src/internal/observable/dom/WebSocketSubject.ts create mode 100644 node_modules/rxjs/src/internal/observable/dom/animationFrames.ts create mode 100644 node_modules/rxjs/src/internal/observable/dom/fetch.ts create mode 100644 node_modules/rxjs/src/internal/observable/dom/webSocket.ts create mode 100644 node_modules/rxjs/src/internal/observable/empty.ts create mode 100644 node_modules/rxjs/src/internal/observable/forkJoin.ts create mode 100644 node_modules/rxjs/src/internal/observable/from.ts create mode 100644 node_modules/rxjs/src/internal/observable/fromEvent.ts create mode 100644 node_modules/rxjs/src/internal/observable/fromEventPattern.ts create mode 100644 node_modules/rxjs/src/internal/observable/fromSubscribable.ts create mode 100644 node_modules/rxjs/src/internal/observable/generate.ts create mode 100644 node_modules/rxjs/src/internal/observable/iif.ts create mode 100644 node_modules/rxjs/src/internal/observable/innerFrom.ts create mode 100644 node_modules/rxjs/src/internal/observable/interval.ts create mode 100644 node_modules/rxjs/src/internal/observable/merge.ts create mode 100644 node_modules/rxjs/src/internal/observable/never.ts create mode 100644 node_modules/rxjs/src/internal/observable/of.ts create mode 100644 node_modules/rxjs/src/internal/observable/onErrorResumeNext.ts create mode 100644 node_modules/rxjs/src/internal/observable/pairs.ts create mode 100644 node_modules/rxjs/src/internal/observable/partition.ts create mode 100644 node_modules/rxjs/src/internal/observable/race.ts create mode 100644 node_modules/rxjs/src/internal/observable/range.ts create mode 100644 node_modules/rxjs/src/internal/observable/throwError.ts create mode 100644 node_modules/rxjs/src/internal/observable/timer.ts create mode 100644 node_modules/rxjs/src/internal/observable/using.ts create mode 100644 node_modules/rxjs/src/internal/observable/zip.ts create mode 100644 node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts create mode 100644 node_modules/rxjs/src/internal/operators/audit.ts create mode 100644 node_modules/rxjs/src/internal/operators/auditTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/buffer.ts create mode 100644 node_modules/rxjs/src/internal/operators/bufferCount.ts create mode 100644 node_modules/rxjs/src/internal/operators/bufferTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/bufferToggle.ts create mode 100644 node_modules/rxjs/src/internal/operators/bufferWhen.ts create mode 100644 node_modules/rxjs/src/internal/operators/catchError.ts create mode 100644 node_modules/rxjs/src/internal/operators/combineAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/combineLatest.ts create mode 100644 node_modules/rxjs/src/internal/operators/combineLatestAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/combineLatestWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/concat.ts create mode 100644 node_modules/rxjs/src/internal/operators/concatAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/concatMap.ts create mode 100644 node_modules/rxjs/src/internal/operators/concatMapTo.ts create mode 100644 node_modules/rxjs/src/internal/operators/concatWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/connect.ts create mode 100644 node_modules/rxjs/src/internal/operators/count.ts create mode 100644 node_modules/rxjs/src/internal/operators/debounce.ts create mode 100644 node_modules/rxjs/src/internal/operators/debounceTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts create mode 100644 node_modules/rxjs/src/internal/operators/delay.ts create mode 100644 node_modules/rxjs/src/internal/operators/delayWhen.ts create mode 100644 node_modules/rxjs/src/internal/operators/dematerialize.ts create mode 100644 node_modules/rxjs/src/internal/operators/distinct.ts create mode 100644 node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts create mode 100644 node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts create mode 100644 node_modules/rxjs/src/internal/operators/elementAt.ts create mode 100644 node_modules/rxjs/src/internal/operators/endWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/every.ts create mode 100644 node_modules/rxjs/src/internal/operators/exhaust.ts create mode 100644 node_modules/rxjs/src/internal/operators/exhaustAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/exhaustMap.ts create mode 100644 node_modules/rxjs/src/internal/operators/expand.ts create mode 100644 node_modules/rxjs/src/internal/operators/filter.ts create mode 100644 node_modules/rxjs/src/internal/operators/finalize.ts create mode 100644 node_modules/rxjs/src/internal/operators/find.ts create mode 100644 node_modules/rxjs/src/internal/operators/findIndex.ts create mode 100644 node_modules/rxjs/src/internal/operators/first.ts create mode 100644 node_modules/rxjs/src/internal/operators/flatMap.ts create mode 100644 node_modules/rxjs/src/internal/operators/groupBy.ts create mode 100644 node_modules/rxjs/src/internal/operators/ignoreElements.ts create mode 100644 node_modules/rxjs/src/internal/operators/isEmpty.ts create mode 100644 node_modules/rxjs/src/internal/operators/joinAllInternals.ts create mode 100644 node_modules/rxjs/src/internal/operators/last.ts create mode 100644 node_modules/rxjs/src/internal/operators/map.ts create mode 100644 node_modules/rxjs/src/internal/operators/mapTo.ts create mode 100644 node_modules/rxjs/src/internal/operators/materialize.ts create mode 100644 node_modules/rxjs/src/internal/operators/max.ts create mode 100644 node_modules/rxjs/src/internal/operators/merge.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeInternals.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeMap.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeMapTo.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeScan.ts create mode 100644 node_modules/rxjs/src/internal/operators/mergeWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/min.ts create mode 100644 node_modules/rxjs/src/internal/operators/multicast.ts create mode 100644 node_modules/rxjs/src/internal/operators/observeOn.ts create mode 100644 node_modules/rxjs/src/internal/operators/onErrorResumeNextWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/pairwise.ts create mode 100644 node_modules/rxjs/src/internal/operators/partition.ts create mode 100644 node_modules/rxjs/src/internal/operators/pluck.ts create mode 100644 node_modules/rxjs/src/internal/operators/publish.ts create mode 100644 node_modules/rxjs/src/internal/operators/publishBehavior.ts create mode 100644 node_modules/rxjs/src/internal/operators/publishLast.ts create mode 100644 node_modules/rxjs/src/internal/operators/publishReplay.ts create mode 100644 node_modules/rxjs/src/internal/operators/race.ts create mode 100644 node_modules/rxjs/src/internal/operators/raceWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/reduce.ts create mode 100644 node_modules/rxjs/src/internal/operators/refCount.ts create mode 100644 node_modules/rxjs/src/internal/operators/repeat.ts create mode 100644 node_modules/rxjs/src/internal/operators/repeatWhen.ts create mode 100644 node_modules/rxjs/src/internal/operators/retry.ts create mode 100644 node_modules/rxjs/src/internal/operators/retryWhen.ts create mode 100644 node_modules/rxjs/src/internal/operators/sample.ts create mode 100644 node_modules/rxjs/src/internal/operators/sampleTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/scan.ts create mode 100644 node_modules/rxjs/src/internal/operators/scanInternals.ts create mode 100644 node_modules/rxjs/src/internal/operators/sequenceEqual.ts create mode 100644 node_modules/rxjs/src/internal/operators/share.ts create mode 100644 node_modules/rxjs/src/internal/operators/shareReplay.ts create mode 100644 node_modules/rxjs/src/internal/operators/single.ts create mode 100644 node_modules/rxjs/src/internal/operators/skip.ts create mode 100644 node_modules/rxjs/src/internal/operators/skipLast.ts create mode 100644 node_modules/rxjs/src/internal/operators/skipUntil.ts create mode 100644 node_modules/rxjs/src/internal/operators/skipWhile.ts create mode 100644 node_modules/rxjs/src/internal/operators/startWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/subscribeOn.ts create mode 100644 node_modules/rxjs/src/internal/operators/switchAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/switchMap.ts create mode 100644 node_modules/rxjs/src/internal/operators/switchMapTo.ts create mode 100644 node_modules/rxjs/src/internal/operators/switchScan.ts create mode 100644 node_modules/rxjs/src/internal/operators/take.ts create mode 100644 node_modules/rxjs/src/internal/operators/takeLast.ts create mode 100644 node_modules/rxjs/src/internal/operators/takeUntil.ts create mode 100644 node_modules/rxjs/src/internal/operators/takeWhile.ts create mode 100644 node_modules/rxjs/src/internal/operators/tap.ts create mode 100644 node_modules/rxjs/src/internal/operators/throttle.ts create mode 100644 node_modules/rxjs/src/internal/operators/throttleTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/throwIfEmpty.ts create mode 100644 node_modules/rxjs/src/internal/operators/timeInterval.ts create mode 100644 node_modules/rxjs/src/internal/operators/timeout.ts create mode 100644 node_modules/rxjs/src/internal/operators/timeoutWith.ts create mode 100644 node_modules/rxjs/src/internal/operators/timestamp.ts create mode 100644 node_modules/rxjs/src/internal/operators/toArray.ts create mode 100644 node_modules/rxjs/src/internal/operators/window.ts create mode 100644 node_modules/rxjs/src/internal/operators/windowCount.ts create mode 100644 node_modules/rxjs/src/internal/operators/windowTime.ts create mode 100644 node_modules/rxjs/src/internal/operators/windowToggle.ts create mode 100644 node_modules/rxjs/src/internal/operators/windowWhen.ts create mode 100644 node_modules/rxjs/src/internal/operators/withLatestFrom.ts create mode 100644 node_modules/rxjs/src/internal/operators/zip.ts create mode 100644 node_modules/rxjs/src/internal/operators/zipAll.ts create mode 100644 node_modules/rxjs/src/internal/operators/zipWith.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduleArray.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/schedulePromise.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts create mode 100644 node_modules/rxjs/src/internal/scheduled/scheduled.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/Action.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AsapAction.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AsapScheduler.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AsyncAction.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/QueueAction.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/VirtualTimeScheduler.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/animationFrame.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/asap.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/async.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/immediateProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/intervalProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/performanceTimestampProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/queue.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts create mode 100644 node_modules/rxjs/src/internal/scheduler/timerHandle.ts create mode 100644 node_modules/rxjs/src/internal/symbol/iterator.ts create mode 100644 node_modules/rxjs/src/internal/symbol/observable.ts create mode 100644 node_modules/rxjs/src/internal/testing/ColdObservable.ts create mode 100644 node_modules/rxjs/src/internal/testing/HotObservable.ts create mode 100644 node_modules/rxjs/src/internal/testing/SubscriptionLog.ts create mode 100644 node_modules/rxjs/src/internal/testing/SubscriptionLoggable.ts create mode 100644 node_modules/rxjs/src/internal/testing/TestMessage.ts create mode 100644 node_modules/rxjs/src/internal/testing/TestScheduler.ts create mode 100644 node_modules/rxjs/src/internal/types.ts create mode 100644 node_modules/rxjs/src/internal/umd.ts create mode 100644 node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts create mode 100644 node_modules/rxjs/src/internal/util/EmptyError.ts create mode 100644 node_modules/rxjs/src/internal/util/Immediate.ts create mode 100644 node_modules/rxjs/src/internal/util/NotFoundError.ts create mode 100644 node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts create mode 100644 node_modules/rxjs/src/internal/util/SequenceError.ts create mode 100644 node_modules/rxjs/src/internal/util/UnsubscriptionError.ts create mode 100644 node_modules/rxjs/src/internal/util/applyMixins.ts create mode 100644 node_modules/rxjs/src/internal/util/args.ts create mode 100644 node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts create mode 100644 node_modules/rxjs/src/internal/util/argsOrArgArray.ts create mode 100644 node_modules/rxjs/src/internal/util/arrRemove.ts create mode 100644 node_modules/rxjs/src/internal/util/createErrorClass.ts create mode 100644 node_modules/rxjs/src/internal/util/createObject.ts create mode 100644 node_modules/rxjs/src/internal/util/errorContext.ts create mode 100644 node_modules/rxjs/src/internal/util/executeSchedule.ts create mode 100644 node_modules/rxjs/src/internal/util/identity.ts create mode 100644 node_modules/rxjs/src/internal/util/isArrayLike.ts create mode 100644 node_modules/rxjs/src/internal/util/isAsyncIterable.ts create mode 100644 node_modules/rxjs/src/internal/util/isDate.ts create mode 100644 node_modules/rxjs/src/internal/util/isFunction.ts create mode 100644 node_modules/rxjs/src/internal/util/isInteropObservable.ts create mode 100644 node_modules/rxjs/src/internal/util/isIterable.ts create mode 100644 node_modules/rxjs/src/internal/util/isObservable.ts create mode 100644 node_modules/rxjs/src/internal/util/isPromise.ts create mode 100644 node_modules/rxjs/src/internal/util/isReadableStreamLike.ts create mode 100644 node_modules/rxjs/src/internal/util/isScheduler.ts create mode 100644 node_modules/rxjs/src/internal/util/lift.ts create mode 100644 node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts create mode 100644 node_modules/rxjs/src/internal/util/noop.ts create mode 100644 node_modules/rxjs/src/internal/util/not.ts create mode 100644 node_modules/rxjs/src/internal/util/pipe.ts create mode 100644 node_modules/rxjs/src/internal/util/reportUnhandledError.ts create mode 100644 node_modules/rxjs/src/internal/util/subscribeToArray.ts create mode 100644 node_modules/rxjs/src/internal/util/throwUnobservableError.ts create mode 100644 node_modules/rxjs/src/internal/util/workarounds.ts create mode 100644 node_modules/rxjs/src/operators/index.ts create mode 100644 node_modules/rxjs/src/testing/index.ts create mode 100644 node_modules/rxjs/src/tsconfig.base.json create mode 100644 node_modules/rxjs/src/tsconfig.cjs.json create mode 100644 node_modules/rxjs/src/tsconfig.cjs.spec.json create mode 100644 node_modules/rxjs/src/tsconfig.esm.json create mode 100644 node_modules/rxjs/src/tsconfig.esm5.json create mode 100644 node_modules/rxjs/src/tsconfig.esm5.rollup.json create mode 100644 node_modules/rxjs/src/tsconfig.types.json create mode 100644 node_modules/rxjs/src/tsconfig.types.spec.json create mode 100644 node_modules/rxjs/src/webSocket/index.ts create mode 100644 node_modules/rxjs/testing/package.json create mode 100644 node_modules/rxjs/tsconfig.json create mode 100644 node_modules/rxjs/webSocket/package.json create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/safer-buffer/LICENSE create mode 100644 node_modules/safer-buffer/Porting-Buffer.md create mode 100644 node_modules/safer-buffer/Readme.md create mode 100644 node_modules/safer-buffer/dangerous.js create mode 100644 node_modules/safer-buffer/package.json create mode 100644 node_modules/safer-buffer/safer.js create mode 100644 node_modules/safer-buffer/tests.js create mode 100644 node_modules/scheduler/LICENSE create mode 100644 node_modules/scheduler/README.md create mode 100644 node_modules/scheduler/build-info.json create mode 100644 node_modules/scheduler/cjs/scheduler-tracing.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-tracing.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler-tracing.profiling.min.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler.development.js create mode 100644 node_modules/scheduler/cjs/scheduler.production.min.js create mode 100644 node_modules/scheduler/index.js create mode 100644 node_modules/scheduler/package.json create mode 100644 node_modules/scheduler/tracing-profiling.js create mode 100644 node_modules/scheduler/tracing.js create mode 100644 node_modules/scheduler/umd/scheduler-tracing.development.js create mode 100644 node_modules/scheduler/umd/scheduler-tracing.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler-tracing.profiling.min.js create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.development.js create mode 100644 node_modules/scheduler/umd/scheduler.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.profiling.min.js create mode 100644 node_modules/scheduler/unstable_mock.js create mode 100644 node_modules/scheduler/unstable_post_task.js create mode 100644 node_modules/semver/CHANGELOG.md create mode 100644 node_modules/semver/LICENSE create mode 100644 node_modules/semver/README.md create mode 100755 node_modules/semver/bin/semver create mode 100644 node_modules/semver/package.json create mode 100644 node_modules/semver/range.bnf create mode 100644 node_modules/semver/semver.js create mode 100644 node_modules/shell-quote/.eslintrc create mode 100644 node_modules/shell-quote/.github/FUNDING.yml create mode 100644 node_modules/shell-quote/.nycrc create mode 100644 node_modules/shell-quote/CHANGELOG.md create mode 100644 node_modules/shell-quote/LICENSE create mode 100644 node_modules/shell-quote/README.md create mode 100644 node_modules/shell-quote/example/env.js create mode 100644 node_modules/shell-quote/example/op.js create mode 100644 node_modules/shell-quote/example/parse.js create mode 100644 node_modules/shell-quote/example/quote.js create mode 100644 node_modules/shell-quote/index.js create mode 100644 node_modules/shell-quote/package.json create mode 100644 node_modules/shell-quote/parse.js create mode 100644 node_modules/shell-quote/quote.js create mode 100644 node_modules/shell-quote/security.md create mode 100644 node_modules/shell-quote/test/comment.js create mode 100644 node_modules/shell-quote/test/env.js create mode 100644 node_modules/shell-quote/test/env_fn.js create mode 100644 node_modules/shell-quote/test/op.js create mode 100644 node_modules/shell-quote/test/parse.js create mode 100644 node_modules/shell-quote/test/quote.js create mode 100644 node_modules/shell-quote/test/set.js create mode 100644 node_modules/shimmer/.travis.yml create mode 100644 node_modules/shimmer/LICENSE create mode 100644 node_modules/shimmer/README.md create mode 100644 node_modules/shimmer/index.js create mode 100644 node_modules/shimmer/package.json create mode 100644 node_modules/shimmer/test/init.tap.js create mode 100644 node_modules/shimmer/test/massUnwrap.tap.js create mode 100644 node_modules/shimmer/test/massWrap.tap.js create mode 100644 node_modules/shimmer/test/unwrap.tap.js create mode 100644 node_modules/shimmer/test/wrap.tap.js create mode 100644 node_modules/signal-exit/LICENSE.txt create mode 100644 node_modules/signal-exit/README.md create mode 100644 node_modules/signal-exit/index.js create mode 100644 node_modules/signal-exit/package.json create mode 100644 node_modules/signal-exit/signals.js create mode 100755 node_modules/slice-ansi/index.js create mode 100644 node_modules/slice-ansi/license create mode 100644 node_modules/slice-ansi/package.json create mode 100644 node_modules/slice-ansi/readme.md create mode 100644 node_modules/stack-chain/.npmignore create mode 100644 node_modules/stack-chain/.travis.yml create mode 100644 node_modules/stack-chain/LICENSE.md create mode 100644 node_modules/stack-chain/README.md create mode 100644 node_modules/stack-chain/benchmark.js create mode 100644 node_modules/stack-chain/format.js create mode 100644 node_modules/stack-chain/index.js create mode 100644 node_modules/stack-chain/package.json create mode 100644 node_modules/stack-chain/stack-chain.js create mode 100644 node_modules/stack-chain/test/produce.js create mode 100644 node_modules/stack-chain/test/simple/callSite-function.js create mode 100644 node_modules/stack-chain/test/simple/callSite-property.js create mode 100644 node_modules/stack-chain/test/simple/conflict-format-delayed-circular.js create mode 100644 node_modules/stack-chain/test/simple/conflict-format-delayed.js create mode 100644 node_modules/stack-chain/test/simple/conflict-format-existing.js create mode 100644 node_modules/stack-chain/test/simple/conflict-version-first.js create mode 100644 node_modules/stack-chain/test/simple/conflict-version-match.js create mode 100644 node_modules/stack-chain/test/simple/conflict-version-mismatch.js create mode 100644 node_modules/stack-chain/test/simple/extend.js create mode 100644 node_modules/stack-chain/test/simple/filter.js create mode 100644 node_modules/stack-chain/test/simple/format-replace.js create mode 100644 node_modules/stack-chain/test/simple/format-tostring-non-generic.js create mode 100644 node_modules/stack-chain/test/simple/non-extensible-errors.js create mode 100644 node_modules/stack-chain/test/simple/order.js create mode 100644 node_modules/stack-chain/test/simple/uglify.js create mode 100644 node_modules/stack-utils/LICENSE.md create mode 100644 node_modules/stack-utils/index.js create mode 100644 node_modules/stack-utils/node_modules/escape-string-regexp/index.d.ts create mode 100644 node_modules/stack-utils/node_modules/escape-string-regexp/index.js create mode 100644 node_modules/stack-utils/node_modules/escape-string-regexp/license create mode 100644 node_modules/stack-utils/node_modules/escape-string-regexp/package.json create mode 100644 node_modules/stack-utils/node_modules/escape-string-regexp/readme.md create mode 100644 node_modules/stack-utils/package.json create mode 100644 node_modules/stack-utils/readme.md create mode 100644 node_modules/string-width/index.d.ts create mode 100644 node_modules/string-width/index.js create mode 100644 node_modules/string-width/license create mode 100644 node_modules/string-width/node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/string-width/node_modules/ansi-regex/index.js create mode 100644 node_modules/string-width/node_modules/ansi-regex/license create mode 100644 node_modules/string-width/node_modules/ansi-regex/package.json create mode 100644 node_modules/string-width/node_modules/ansi-regex/readme.md create mode 100644 node_modules/string-width/node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/string-width/node_modules/strip-ansi/index.js create mode 100644 node_modules/string-width/node_modules/strip-ansi/license create mode 100644 node_modules/string-width/node_modules/strip-ansi/package.json create mode 100644 node_modules/string-width/node_modules/strip-ansi/readme.md create mode 100644 node_modules/string-width/package.json create mode 100644 node_modules/string-width/readme.md create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/strip-ansi/index.js create mode 100644 node_modules/strip-ansi/license create mode 100644 node_modules/strip-ansi/package.json create mode 100644 node_modules/strip-ansi/readme.md create mode 100644 node_modules/supports-color/browser.js create mode 100644 node_modules/supports-color/index.js create mode 100644 node_modules/supports-color/license create mode 100644 node_modules/supports-color/package.json create mode 100644 node_modules/supports-color/readme.md create mode 100644 node_modules/supports-hyperlinks/browser.js create mode 100644 node_modules/supports-hyperlinks/index.js create mode 100644 node_modules/supports-hyperlinks/license create mode 100644 node_modules/supports-hyperlinks/package.json create mode 100644 node_modules/supports-hyperlinks/readme.md create mode 100644 node_modules/thenify-all/History.md create mode 100644 node_modules/thenify-all/LICENSE create mode 100644 node_modules/thenify-all/README.md create mode 100644 node_modules/thenify-all/index.js create mode 100644 node_modules/thenify-all/package.json create mode 100644 node_modules/thenify/History.md create mode 100644 node_modules/thenify/LICENSE create mode 100644 node_modules/thenify/README.md create mode 100644 node_modules/thenify/index.js create mode 100644 node_modules/thenify/package.json create mode 100644 node_modules/through/.travis.yml create mode 100644 node_modules/through/LICENSE.APACHE2 create mode 100644 node_modules/through/LICENSE.MIT create mode 100644 node_modules/through/index.js create mode 100644 node_modules/through/package.json create mode 100644 node_modules/through/readme.markdown create mode 100644 node_modules/through/test/async.js create mode 100644 node_modules/through/test/auto-destroy.js create mode 100644 node_modules/through/test/buffering.js create mode 100644 node_modules/through/test/end.js create mode 100644 node_modules/through/test/index.js create mode 100644 node_modules/tiny-invariant/LICENSE create mode 100644 node_modules/tiny-invariant/README.md create mode 100644 node_modules/tiny-invariant/package.json create mode 100644 node_modules/tiny-invariant/src/tiny-invariant.flow.js create mode 100644 node_modules/tiny-invariant/src/tiny-invariant.ts create mode 100644 node_modules/tmp/LICENSE create mode 100644 node_modules/tmp/README.md create mode 100644 node_modules/tmp/package.json create mode 100644 node_modules/ts-dedent/HISTORY.md create mode 100644 node_modules/ts-dedent/LICENSE create mode 100644 node_modules/ts-dedent/README.md create mode 100644 node_modules/ts-dedent/esm/index.d.ts create mode 100644 node_modules/ts-dedent/esm/index.js create mode 100644 node_modules/ts-dedent/esm/index.js.map create mode 100644 node_modules/ts-dedent/package.json create mode 100644 node_modules/ts-dedent/src/__tests__/index.spec.ts create mode 100644 node_modules/ts-dedent/src/__tests__/issue-21.spec.ts create mode 100644 node_modules/ts-dedent/src/index.ts create mode 100644 node_modules/tslib/CopyrightNotice.txt create mode 100644 node_modules/tslib/LICENSE.txt create mode 100644 node_modules/tslib/README.md create mode 100644 node_modules/tslib/SECURITY.md create mode 100644 node_modules/tslib/modules/index.js create mode 100644 node_modules/tslib/modules/package.json create mode 100644 node_modules/tslib/package.json create mode 100644 node_modules/tslib/tslib.d.ts create mode 100644 node_modules/tslib/tslib.es6.html create mode 100644 node_modules/tslib/tslib.es6.js create mode 100644 node_modules/tslib/tslib.html create mode 100644 node_modules/tslib/tslib.js create mode 100644 node_modules/type-fest/index.d.ts create mode 100644 node_modules/type-fest/license create mode 100644 node_modules/type-fest/package.json create mode 100644 node_modules/type-fest/readme.md create mode 100644 node_modules/type-fest/source/async-return-type.d.ts create mode 100644 node_modules/type-fest/source/basic.d.ts create mode 100644 node_modules/type-fest/source/conditional-except.d.ts create mode 100644 node_modules/type-fest/source/conditional-keys.d.ts create mode 100644 node_modules/type-fest/source/conditional-pick.d.ts create mode 100644 node_modules/type-fest/source/except.d.ts create mode 100644 node_modules/type-fest/source/literal-union.d.ts create mode 100644 node_modules/type-fest/source/merge-exclusive.d.ts create mode 100644 node_modules/type-fest/source/merge.d.ts create mode 100644 node_modules/type-fest/source/mutable.d.ts create mode 100644 node_modules/type-fest/source/opaque.d.ts create mode 100644 node_modules/type-fest/source/package-json.d.ts create mode 100644 node_modules/type-fest/source/partial-deep.d.ts create mode 100644 node_modules/type-fest/source/promisable.d.ts create mode 100644 node_modules/type-fest/source/promise-value.d.ts create mode 100644 node_modules/type-fest/source/readonly-deep.d.ts create mode 100644 node_modules/type-fest/source/require-at-least-one.d.ts create mode 100644 node_modules/type-fest/source/require-exactly-one.d.ts create mode 100644 node_modules/type-fest/source/set-optional.d.ts create mode 100644 node_modules/type-fest/source/set-required.d.ts create mode 100644 node_modules/type-fest/source/tsconfig-json.d.ts create mode 100644 node_modules/type-fest/source/union-to-intersection.d.ts create mode 100644 node_modules/unload/LICENSE create mode 100644 node_modules/unload/README.md create mode 100644 node_modules/unload/package.json create mode 100644 node_modules/unload/src/browser.js create mode 100644 node_modules/unload/src/index.browserify.js create mode 100644 node_modules/unload/src/index.d.ts create mode 100644 node_modules/unload/src/index.js create mode 100644 node_modules/unload/src/node.js create mode 100644 node_modules/use-sync-external-store/LICENSE create mode 100644 node_modules/use-sync-external-store/README.md create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.native.development.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.native.production.min.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.development.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store.development.js create mode 100644 node_modules/use-sync-external-store/cjs/use-sync-external-store.production.min.js create mode 100644 node_modules/use-sync-external-store/index.js create mode 100644 node_modules/use-sync-external-store/package.json create mode 100644 node_modules/use-sync-external-store/shim/index.js create mode 100644 node_modules/use-sync-external-store/shim/index.native.js create mode 100644 node_modules/use-sync-external-store/shim/with-selector.js create mode 100644 node_modules/use-sync-external-store/with-selector.js create mode 100644 node_modules/use-zustand/LICENSE create mode 100644 node_modules/use-zustand/README.md create mode 100644 node_modules/use-zustand/package.json create mode 100644 node_modules/use-zustand/src/index.ts create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/uuid/LICENSE.md create mode 100644 node_modules/uuid/README.md create mode 100644 node_modules/uuid/package.json create mode 100644 node_modules/uuid/wrapper.mjs create mode 100644 node_modules/wcwidth/.npmignore create mode 100644 node_modules/wcwidth/LICENSE create mode 100644 node_modules/wcwidth/Readme.md create mode 100644 node_modules/wcwidth/combining.js create mode 100644 node_modules/wcwidth/docs/index.md create mode 100644 node_modules/wcwidth/index.js create mode 100644 node_modules/wcwidth/package.json create mode 100644 node_modules/wcwidth/test/index.js create mode 100644 node_modules/widest-line/index.d.ts create mode 100644 node_modules/widest-line/index.js create mode 100644 node_modules/widest-line/license create mode 100644 node_modules/widest-line/package.json create mode 100644 node_modules/widest-line/readme.md create mode 100755 node_modules/wrap-ansi/index.js create mode 100644 node_modules/wrap-ansi/license create mode 100644 node_modules/wrap-ansi/node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/wrap-ansi/node_modules/ansi-regex/index.js create mode 100644 node_modules/wrap-ansi/node_modules/ansi-regex/license create mode 100644 node_modules/wrap-ansi/node_modules/ansi-regex/package.json create mode 100644 node_modules/wrap-ansi/node_modules/ansi-regex/readme.md create mode 100644 node_modules/wrap-ansi/node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/wrap-ansi/node_modules/strip-ansi/index.js create mode 100644 node_modules/wrap-ansi/node_modules/strip-ansi/license create mode 100644 node_modules/wrap-ansi/node_modules/strip-ansi/package.json create mode 100644 node_modules/wrap-ansi/node_modules/strip-ansi/readme.md create mode 100644 node_modules/wrap-ansi/package.json create mode 100644 node_modules/wrap-ansi/readme.md create mode 100644 node_modules/wrappy/LICENSE create mode 100644 node_modules/wrappy/README.md create mode 100644 node_modules/wrappy/package.json create mode 100644 node_modules/wrappy/wrappy.js create mode 100644 node_modules/ws/LICENSE create mode 100644 node_modules/ws/README.md create mode 100644 node_modules/ws/browser.js create mode 100644 node_modules/ws/index.js create mode 100644 node_modules/ws/package.json create mode 100644 node_modules/y18n/CHANGELOG.md create mode 100644 node_modules/y18n/LICENSE create mode 100644 node_modules/y18n/README.md create mode 100644 node_modules/y18n/index.mjs create mode 100644 node_modules/y18n/package.json create mode 100644 node_modules/yargs-parser/CHANGELOG.md create mode 100644 node_modules/yargs-parser/LICENSE.txt create mode 100644 node_modules/yargs-parser/README.md create mode 100644 node_modules/yargs-parser/browser.js create mode 100644 node_modules/yargs-parser/package.json create mode 100644 node_modules/yargs/CHANGELOG.md create mode 100644 node_modules/yargs/LICENSE create mode 100644 node_modules/yargs/README.md create mode 100644 node_modules/yargs/browser.mjs create mode 100644 node_modules/yargs/helpers/helpers.mjs create mode 100644 node_modules/yargs/helpers/index.js create mode 100644 node_modules/yargs/helpers/package.json create mode 100644 node_modules/yargs/index.cjs create mode 100644 node_modules/yargs/index.mjs create mode 100644 node_modules/yargs/locales/be.json create mode 100644 node_modules/yargs/locales/de.json create mode 100644 node_modules/yargs/locales/en.json create mode 100644 node_modules/yargs/locales/es.json create mode 100644 node_modules/yargs/locales/fi.json create mode 100644 node_modules/yargs/locales/fr.json create mode 100644 node_modules/yargs/locales/hi.json create mode 100644 node_modules/yargs/locales/hu.json create mode 100644 node_modules/yargs/locales/id.json create mode 100644 node_modules/yargs/locales/it.json create mode 100644 node_modules/yargs/locales/ja.json create mode 100644 node_modules/yargs/locales/ko.json create mode 100644 node_modules/yargs/locales/nb.json create mode 100644 node_modules/yargs/locales/nl.json create mode 100644 node_modules/yargs/locales/nn.json create mode 100644 node_modules/yargs/locales/pirate.json create mode 100644 node_modules/yargs/locales/pl.json create mode 100644 node_modules/yargs/locales/pt.json create mode 100644 node_modules/yargs/locales/pt_BR.json create mode 100644 node_modules/yargs/locales/ru.json create mode 100644 node_modules/yargs/locales/th.json create mode 100644 node_modules/yargs/locales/tr.json create mode 100644 node_modules/yargs/locales/zh_CN.json create mode 100644 node_modules/yargs/locales/zh_TW.json create mode 100644 node_modules/yargs/package.json create mode 100644 node_modules/yargs/yargs create mode 100644 node_modules/yoga-layout-prebuilt/index.d.ts create mode 100644 node_modules/yoga-layout-prebuilt/license create mode 100644 node_modules/yoga-layout-prebuilt/package.json create mode 100644 node_modules/yoga-layout-prebuilt/readme.md create mode 100644 node_modules/zustand/LICENSE create mode 100644 node_modules/zustand/context.d.ts create mode 100644 node_modules/zustand/context.js create mode 100644 node_modules/zustand/esm/context.d.mts create mode 100644 node_modules/zustand/esm/context.d.ts create mode 100644 node_modules/zustand/esm/context.js create mode 100644 node_modules/zustand/esm/context.mjs create mode 100644 node_modules/zustand/esm/index.d.mts create mode 100644 node_modules/zustand/esm/index.d.ts create mode 100644 node_modules/zustand/esm/index.js create mode 100644 node_modules/zustand/esm/index.mjs create mode 100644 node_modules/zustand/esm/middleware.d.mts create mode 100644 node_modules/zustand/esm/middleware.d.ts create mode 100644 node_modules/zustand/esm/middleware.js create mode 100644 node_modules/zustand/esm/middleware.mjs create mode 100644 node_modules/zustand/esm/middleware/combine.d.mts create mode 100644 node_modules/zustand/esm/middleware/combine.d.ts create mode 100644 node_modules/zustand/esm/middleware/devtools.d.mts create mode 100644 node_modules/zustand/esm/middleware/devtools.d.ts create mode 100644 node_modules/zustand/esm/middleware/immer.d.mts create mode 100644 node_modules/zustand/esm/middleware/immer.d.ts create mode 100644 node_modules/zustand/esm/middleware/immer.js create mode 100644 node_modules/zustand/esm/middleware/immer.mjs create mode 100644 node_modules/zustand/esm/middleware/persist.d.mts create mode 100644 node_modules/zustand/esm/middleware/persist.d.ts create mode 100644 node_modules/zustand/esm/middleware/redux.d.mts create mode 100644 node_modules/zustand/esm/middleware/redux.d.ts create mode 100644 node_modules/zustand/esm/middleware/subscribeWithSelector.d.mts create mode 100644 node_modules/zustand/esm/middleware/subscribeWithSelector.d.ts create mode 100644 node_modules/zustand/esm/react.d.mts create mode 100644 node_modules/zustand/esm/react.d.ts create mode 100644 node_modules/zustand/esm/shallow.d.mts create mode 100644 node_modules/zustand/esm/shallow.d.ts create mode 100644 node_modules/zustand/esm/shallow.js create mode 100644 node_modules/zustand/esm/shallow.mjs create mode 100644 node_modules/zustand/esm/vanilla.d.mts create mode 100644 node_modules/zustand/esm/vanilla.d.ts create mode 100644 node_modules/zustand/esm/vanilla.js create mode 100644 node_modules/zustand/esm/vanilla.mjs create mode 100644 node_modules/zustand/index.d.ts create mode 100644 node_modules/zustand/index.js create mode 100644 node_modules/zustand/middleware.d.ts create mode 100644 node_modules/zustand/middleware.js create mode 100644 node_modules/zustand/middleware/combine.d.ts create mode 100644 node_modules/zustand/middleware/devtools.d.ts create mode 100644 node_modules/zustand/middleware/immer.d.ts create mode 100644 node_modules/zustand/middleware/immer.js create mode 100644 node_modules/zustand/middleware/persist.d.ts create mode 100644 node_modules/zustand/middleware/redux.d.ts create mode 100644 node_modules/zustand/middleware/subscribeWithSelector.d.ts create mode 100644 node_modules/zustand/package.json create mode 100644 node_modules/zustand/react.d.ts create mode 100644 node_modules/zustand/readme.md create mode 100644 node_modules/zustand/shallow.d.ts create mode 100644 node_modules/zustand/shallow.js create mode 100644 node_modules/zustand/system/context.development.js create mode 100644 node_modules/zustand/system/context.production.js create mode 100644 node_modules/zustand/system/index.development.js create mode 100644 node_modules/zustand/system/index.production.js create mode 100644 node_modules/zustand/system/middleware.development.js create mode 100644 node_modules/zustand/system/middleware.production.js create mode 100644 node_modules/zustand/system/middleware/immer.development.js create mode 100644 node_modules/zustand/system/middleware/immer.production.js create mode 100644 node_modules/zustand/system/shallow.development.js create mode 100644 node_modules/zustand/system/shallow.production.js create mode 100644 node_modules/zustand/system/vanilla.development.js create mode 100644 node_modules/zustand/system/vanilla.production.js create mode 100644 node_modules/zustand/ts3.4/context.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/context.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/index.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/combine.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/devtools.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/immer.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/persist.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/redux.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/middleware/subscribeWithSelector.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/react.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/shallow.d.ts create mode 100644 node_modules/zustand/ts3.4/esm/vanilla.d.ts create mode 100644 node_modules/zustand/ts3.4/index.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/combine.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/devtools.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/immer.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/persist.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/redux.d.ts create mode 100644 node_modules/zustand/ts3.4/middleware/subscribeWithSelector.d.ts create mode 100644 node_modules/zustand/ts3.4/react.d.ts create mode 100644 node_modules/zustand/ts3.4/shallow.d.ts create mode 100644 node_modules/zustand/ts3.4/vanilla.d.ts create mode 100644 node_modules/zustand/umd/context.development.js create mode 100644 node_modules/zustand/umd/context.production.js create mode 100644 node_modules/zustand/umd/index.development.js create mode 100644 node_modules/zustand/umd/index.production.js create mode 100644 node_modules/zustand/umd/middleware.development.js create mode 100644 node_modules/zustand/umd/middleware.production.js create mode 100644 node_modules/zustand/umd/middleware/immer.development.js create mode 100644 node_modules/zustand/umd/middleware/immer.production.js create mode 100644 node_modules/zustand/umd/shallow.development.js create mode 100644 node_modules/zustand/umd/shallow.production.js create mode 100644 node_modules/zustand/umd/vanilla.development.js create mode 100644 node_modules/zustand/umd/vanilla.production.js create mode 100644 node_modules/zustand/vanilla.d.ts create mode 100644 node_modules/zustand/vanilla.js create mode 100644 package-lock.json create mode 100644 package.json diff --git a/jaxutils/parameters.py b/jaxutils/parameters.py index 1e15286..6f9ef88 100644 --- a/jaxutils/parameters.py +++ b/jaxutils/parameters.py @@ -18,11 +18,12 @@ import jax.tree_util as jtu import jax import jax.numpy as jnp -from typing import Dict, Any, Tuple +from typing import Dict, Any, Tuple, Callable from .bijectors import Identity from simple_pytree import Pytree, static_field from jax.tree_util import tree_flatten, tree_structure from jaxtyping import Float, Array +from distrax import Bijector, Distribution class Parameters(Pytree, dict): @@ -77,7 +78,7 @@ def __eq__(self, other: Parameters) -> bool: def params(self) -> Dict: return self._param_dict - # TODO: Benedict would make this awesome: `update_params(self, key, value)` e.g., `update_params('a.b.c', 1)` + # TODO: Benedict would make this awesome: `update_params(self, key, value)` e.g., `update_single_param('a.b.c', 1)` # TODO: This should throw an error if the key-structure changes def update_params(self, value: Dict) -> Parameters: self._validate_update(value, self.params, "params") @@ -90,10 +91,16 @@ def update_params(self, value: Dict) -> Parameters: ) @staticmethod - def _validate_update(value: dict, comparison: dict, name: str): - if tree_structure(comparison) != tree_structure(value): - print(tree_structure(comparison)) - print(tree_structure(value)) + def _validate_update( + value: dict, + comparison: dict, + name: str, + lambda_expression: Callable[[Any], bool] = None, + ): + # TODO: Use `is_leaf` argument -> Dan will share code + if tree_structure(comparison, lambda_expression) != tree_structure( + value, lambda_expression + ): raise ValueError( f"The structure of the {name} has changed. Please ensure" f" updates to {name} do not alter the strcuture." @@ -105,7 +112,12 @@ def bijectors(self) -> Dict: def update_bijectors(self, value: Dict) -> Parameters: # TODO: Traversal doesn't work for nested dicts where the value is a distrax object - # self._validate_update(value, self.bijectors, "bijectors") + self._validate_update( + value, + self.bijectors, + "bijectors", + lambda x: isinstance(x, Bijector), + ) return Parameters( self.params, value, @@ -134,7 +146,12 @@ def priors(self) -> Dict: def update_priors(self, value: Dict) -> Parameters: # TODO: Traversal doesn't work for nested dicts where the value is a distrax object - # self._validate_update(value, self.priors, "priors") + self._validate_update( + value, + self.priors, + "priors", + lambda x: isinstance(x, Distribution), + ) return Parameters( self.params, self.bijectors, @@ -156,6 +173,7 @@ def update_training_history(self, value: list) -> Parameters: value, ) + # TODO: Drop if not required in any notebooks. def unpack( self, ) -> Tuple[Dict[str, jax.Array], Dict[str, bool], Dict[str, Any]]: @@ -165,6 +183,7 @@ def unpack( Tuple[Dict, Dict, Dict]: The parameters, trainables and bijectors. """ # TODO: Should priors be returned here? + # TODO: Should we return a tuple or dict here? return self.params, self.trainables, self.bijectors def constrain(self) -> Parameters: @@ -224,7 +243,7 @@ def log_prior_density(self) -> Array[Float, "1"]: """ def log_density(param, prior): - # TODO: Should a jax.lax.cond be used here? The method does jit-compile right now. + # TODO: Use a jax.lax.cond be used here? if prior is not None: return jnp.sum(prior.log_prob(param)) else: diff --git a/node_modules/.bin/cdl b/node_modules/.bin/cdl new file mode 120000 index 0000000..00a4369 --- /dev/null +++ b/node_modules/.bin/cdl @@ -0,0 +1 @@ +../cardinal/bin/cdl.js \ No newline at end of file diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 120000 index 0000000..7423b18 --- /dev/null +++ b/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 120000 index 0000000..16069ef --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/node_modules/.bin/github-copilot-cli b/node_modules/.bin/github-copilot-cli new file mode 120000 index 0000000..a1f35eb --- /dev/null +++ b/node_modules/.bin/github-copilot-cli @@ -0,0 +1 @@ +../@githubnext/github-copilot-cli/cli.js \ No newline at end of file diff --git a/node_modules/.bin/highlight b/node_modules/.bin/highlight new file mode 120000 index 0000000..ff7bde0 --- /dev/null +++ b/node_modules/.bin/highlight @@ -0,0 +1 @@ +../cli-highlight/bin/highlight \ No newline at end of file diff --git a/node_modules/.bin/is-ci b/node_modules/.bin/is-ci new file mode 120000 index 0000000..fe6aca6 --- /dev/null +++ b/node_modules/.bin/is-ci @@ -0,0 +1 @@ +../is-ci/bin.js \ No newline at end of file diff --git a/node_modules/.bin/loose-envify b/node_modules/.bin/loose-envify new file mode 120000 index 0000000..ed9009c --- /dev/null +++ b/node_modules/.bin/loose-envify @@ -0,0 +1 @@ +../loose-envify/cli.js \ No newline at end of file diff --git a/node_modules/.bin/marked b/node_modules/.bin/marked new file mode 120000 index 0000000..6827ff3 --- /dev/null +++ b/node_modules/.bin/marked @@ -0,0 +1 @@ +../marked/bin/marked.js \ No newline at end of file diff --git a/node_modules/.bin/rimraf b/node_modules/.bin/rimraf new file mode 120000 index 0000000..4cd49a4 --- /dev/null +++ b/node_modules/.bin/rimraf @@ -0,0 +1 @@ +../rimraf/bin.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 120000 index 0000000..588f70e --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..61db00d --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,2318 @@ +{ + "name": "JaxUtils", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@azure/abort-controller": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-1.1.0.tgz", + "integrity": "sha512-TrRLIoSQVzfAJX9H1JeFjzAoDGcoK1IYX1UImfceTZpsyYfWr09Ss1aHW1y5TrrR3iq6RZLBwJ3E24uwPhwahw==", + "dependencies": { + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@azure/core-auth": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.4.0.tgz", + "integrity": "sha512-HFrcTgmuSuukRf/EdPmqBrc5l6Q5Uu+2TbuhaKbgaCpP2TfAeiNaQPAadxO+CYBRHGUzIDteMAjFspFLDLnKVQ==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.10.2.tgz", + "integrity": "sha512-e3WzAsRKLor5EgK2bQqR1OY5D7VBqzORHtlqtygZZQGCYOIBsynqrZBa8MFD1Ue9r8TPtofOLditalnlQHS45Q==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/core-auth": "^1.4.0", + "@azure/core-tracing": "^1.0.1", + "@azure/core-util": "^1.0.0", + "@azure/logger": "^1.0.0", + "form-data": "^4.0.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "tslib": "^2.2.0", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/@azure/core-tracing": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.0.1.tgz", + "integrity": "sha512-I5CGMoLtX+pI17ZdiFJZgxMJApsK6jjfm85hpgp3oazCdq5Wxgh4wMr7ge/TTWW1B5WBuvIOI1fMU/FrOAMKrw==", + "dependencies": { + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@azure/core-util": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.2.0.tgz", + "integrity": "sha512-ffGIw+Qs8bNKNLxz5UPkz4/VBM/EZY07mPve1ZYFqYUdPwFqRj0RPk0U7LZMOfT7GCck9YjuT1Rfp1PApNl1ng==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@azure/logger": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.4.tgz", + "integrity": "sha512-ustrPY8MryhloQj7OWGe+HrYx+aoiOxzbXTtgblbV3xwCqpzUK36phH3XNHQKj3EPonyFUuDTfR3qFhTEAuZEg==", + "dependencies": { + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", + "integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", + "dependencies": { + "regenerator-runtime": "^0.13.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@colors/colors": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", + "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "optional": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/@githubnext/github-copilot-cli": { + "version": "0.1.21", + "resolved": "https://registry.npmjs.org/@githubnext/github-copilot-cli/-/github-copilot-cli-0.1.21.tgz", + "integrity": "sha512-+GIGrl5MD8Mt5I/qbJkrqc746BFbdTg08D8kF8ni/jw/6B1MI0NW7zH86zRmiEN37vvBv/iccm6CXmu+16anqg==", + "dependencies": { + "applicationinsights": "^2.3.6", + "axios": "^1.1.3", + "chalk": "^5.1.0", + "cli-highlight": "^2.1.11", + "commander": "^9.4.1", + "get-stream": "^6.0.1", + "immer": "^9.0.16", + "ink": "^3.2.0", + "ink-divider": "^3.0.0", + "ink-select-input": "^4.2.1", + "ink-spinner": "^4.0.3", + "ink-text-input": "^4.0.3", + "inquirer": "^9.1.4", + "marked": "^4.2.12", + "marked-terminal": "^5.1.1", + "ora": "^6.1.2", + "radash": "^9.1.0", + "react": "17", + "react-dom": "17", + "react-query": "^3.39.2", + "tiny-invariant": "^1.3.1", + "ts-dedent": "^2.2.0", + "use-zustand": "^0.0.1", + "uuid": "^9.0.0", + "zustand": "^4.1.4" + }, + "bin": { + "github-copilot-cli": "cli.js" + } + }, + "node_modules/@microsoft/applicationinsights-web-snippet": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-web-snippet/-/applicationinsights-web-snippet-1.0.1.tgz", + "integrity": "sha512-2IHAOaLauc8qaAitvWS+U931T+ze+7MNWrDHY47IENP5y2UA0vqJDu67kWZDdpCN1fFC77sfgfB+HV7SrKshnQ==" + }, + "node_modules/@opentelemetry/api": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.4.1.tgz", + "integrity": "sha512-O2yRJce1GOc6PAy3QxFM4NzFiWzvScDC1/5ihYBL6BUEVdq0XMWN01sppE+H6bBXbaFYipjwFLEWLg5PaSOThA==", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.10.0.tgz", + "integrity": "sha512-H5/mfU3TsEBe/cnnLu3VCkzjqyRARmhxQGsT64KwafxjzkDh+c2Bk4n140Cg/xhgrjK2sFsxbJj6d0xZlVo/OQ==", + "dependencies": { + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.10.0.tgz", + "integrity": "sha512-bh4auHOdS0/cwSgviCPbkItLwLZRWCZKp/ns2soVwlWQMJH36FIHbcYJf7G9+Rthlc6u163VhUefho+eDrPVeA==", + "dependencies": { + "@opentelemetry/core": "1.10.0", + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.10.0.tgz", + "integrity": "sha512-X4rRShtVQ893LCU4GNKS1TKFua9nSjVmo0VJvigfSFSOmyyOLfiyTWmVL9MKV7Ws0HqLOIWJixJY0x28fw3Tzg==", + "dependencies": { + "@opentelemetry/core": "1.10.0", + "@opentelemetry/resources": "1.10.0", + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.10.0.tgz", + "integrity": "sha512-Mzo5IyrI59YuYWeNoOZRXfUCc3upjmxCmczSm+pUgWprvSNfdOX70SVde84UxmuzU7MF1MEkPXKXTYG3ymRw2w==", + "engines": { + "node": ">=14" + } + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "engines": { + "node": ">= 10" + } + }, + "node_modules/@types/yoga-layout": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@types/yoga-layout/-/yoga-layout-1.9.2.tgz", + "integrity": "sha512-S9q47ByT2pPvD65IvrWp7qppVMpk9WGMbVq9wbWZOHg6tnXSD4vyhao6nOSBwwfDdV2p3Kx9evA9vI+XWTfDvw==" + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-escapes/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", + "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ansicolors": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/ansicolors/-/ansicolors-0.3.2.tgz", + "integrity": "sha512-QXu7BPrP29VllRxH8GwB7x5iX5qWKAAMLqKQGWTeLWVlNHNOpVMJ91dsxQAIWXpjuW5wqvxu3Jd/nRjrJ+0pqg==" + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==" + }, + "node_modules/applicationinsights": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/applicationinsights/-/applicationinsights-2.5.0.tgz", + "integrity": "sha512-6kIFmpANRok+6FhCOmO7ZZ/mh7fdNKn17BaT13cg/RV5roLPJlA6q8srWexayHd3MPcwMb9072e8Zp0P47s/pw==", + "dependencies": { + "@azure/core-auth": "^1.4.0", + "@azure/core-rest-pipeline": "^1.10.0", + "@microsoft/applicationinsights-web-snippet": "^1.0.1", + "@opentelemetry/api": "^1.0.4", + "@opentelemetry/core": "^1.0.1", + "@opentelemetry/sdk-trace-base": "^1.0.1", + "@opentelemetry/semantic-conventions": "^1.0.1", + "cls-hooked": "^4.2.2", + "continuation-local-storage": "^3.2.1", + "diagnostic-channel": "1.1.0", + "diagnostic-channel-publishers": "1.0.5" + }, + "engines": { + "node": ">=8.0.0" + }, + "peerDependencies": { + "applicationinsights-native-metrics": "*" + }, + "peerDependenciesMeta": { + "applicationinsights-native-metrics": { + "optional": true + } + } + }, + "node_modules/arr-rotate": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/arr-rotate/-/arr-rotate-1.0.0.tgz", + "integrity": "sha512-yOzOZcR9Tn7enTF66bqKorGGH0F36vcPaSWg8fO0c0UYb3LX3VMXj5ZxEqQLNOecAhlRJ7wYZja5i4jTlnbIfQ==", + "engines": { + "node": ">=4" + } + }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/async-hook-jl": { + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/async-hook-jl/-/async-hook-jl-1.7.6.tgz", + "integrity": "sha512-gFaHkFfSxTjvoxDMYqDuGHlcRyUuamF8s+ZTtJdDzqjws4mCt7v0vuV79/E2Wr2/riMQgtG4/yUtXWs1gZ7JMg==", + "dependencies": { + "stack-chain": "^1.3.7" + }, + "engines": { + "node": "^4.7 || >=6.9 || >=7.3" + } + }, + "node_modules/async-listener": { + "version": "0.6.10", + "resolved": "https://registry.npmjs.org/async-listener/-/async-listener-0.6.10.tgz", + "integrity": "sha512-gpuo6xOyF4D5DE5WvyqZdPA3NGhiT6Qf07l7DCB0wwDEsLvDIbCr6j9S5aj5Ch96dLace5tXVzWBZkxU/c5ohw==", + "dependencies": { + "semver": "^5.3.0", + "shimmer": "^1.1.0" + }, + "engines": { + "node": "<=0.11.8 || >0.11.10" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/auto-bind": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-4.0.0.tgz", + "integrity": "sha512-Hdw8qdNiqdJ8LqT0iK0sVzkFbzg6fhnQqqfWhBDxcHZvU75+B+ayzTy8x+k5Ix0Y92XOhOUlx74ps+bA6BeYMQ==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/axios": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.3.4.tgz", + "integrity": "sha512-toYm+Bsyl6VC5wSkfkbbNB6ROv7KY93PEBBL6xyDczaIHasAiv4wPqQ/c4RjoQzipxRD2W5g21cOqQulZ7rHwQ==", + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/big-integer": { + "version": "1.6.51", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.51.tgz", + "integrity": "sha512-GPEid2Y9QU1Exl1rpO9B2IPJGHPSupF5GnVIP0blYvNOMer2bTvSWs1jGOUg04hTmu67nmLsQ9TBo1puaotBHg==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/bl": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-5.1.0.tgz", + "integrity": "sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==", + "dependencies": { + "buffer": "^6.0.3", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/broadcast-channel": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/broadcast-channel/-/broadcast-channel-3.7.0.tgz", + "integrity": "sha512-cIAKJXAxGJceNZGTZSBzMxzyOn72cVgPnKx4dc6LRjQgbaJUQqhy5rzL3zbMxkMWsGKkv2hSFkPRMEXfoMZ2Mg==", + "dependencies": { + "@babel/runtime": "^7.7.2", + "detect-node": "^2.1.0", + "js-sha3": "0.8.0", + "microseconds": "0.2.0", + "nano-time": "1.0.0", + "oblivious-set": "1.0.0", + "rimraf": "3.0.2", + "unload": "2.2.0" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/cardinal": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/cardinal/-/cardinal-2.1.1.tgz", + "integrity": "sha512-JSr5eOgoEymtYHBjNWyjrMqet9Am2miJhlfKNdqLp6zoeAh0KN5dRAcxlecj5mAJrmQomgiOBj35xHLrFjqBpw==", + "dependencies": { + "ansicolors": "~0.3.2", + "redeyed": "~2.1.0" + }, + "bin": { + "cdl": "bin/cdl.js" + } + }, + "node_modules/chalk": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.2.0.tgz", + "integrity": "sha512-ree3Gqw/nazQAPuJJEy+avdl7QfZMcUvmHIKgEZkGL+xOBzRvup5Hxo6LHuMceSxOabuJLJm5Yp/92R9eMmMvA==", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" + }, + "node_modules/ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==" + }, + "node_modules/cli-boxes": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", + "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-highlight": { + "version": "2.1.11", + "resolved": "https://registry.npmjs.org/cli-highlight/-/cli-highlight-2.1.11.tgz", + "integrity": "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg==", + "dependencies": { + "chalk": "^4.0.0", + "highlight.js": "^10.7.1", + "mz": "^2.4.0", + "parse5": "^5.1.1", + "parse5-htmlparser2-tree-adapter": "^6.0.0", + "yargs": "^16.0.0" + }, + "bin": { + "highlight": "bin/highlight" + }, + "engines": { + "node": ">=8.0.0", + "npm": ">=5.0.0" + } + }, + "node_modules/cli-highlight/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cli-spinners": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.7.0.tgz", + "integrity": "sha512-qu3pN8Y3qHNgE2AFweciB1IfMnmZ/fsNTEE+NOFjmGB2F/7rLhnhzppvpCnN4FovtP26k8lHyy9ptEbNwWFLzw==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-table3": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.3.tgz", + "integrity": "sha512-w5Jac5SykAeZJKntOxJCrm63Eg5/4dhMWIcuTbo9rpE+brgaSZo0RuNJZeOyMgsUdhDeojvgyQLmjI+K50ZGyg==", + "dependencies": { + "string-width": "^4.2.0" + }, + "engines": { + "node": "10.* || >= 12.*" + }, + "optionalDependencies": { + "@colors/colors": "1.5.0" + } + }, + "node_modules/cli-truncate": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", + "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "dependencies": { + "slice-ansi": "^3.0.0", + "string-width": "^4.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-width": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.0.0.tgz", + "integrity": "sha512-ZksGS2xpa/bYkNzN3BAw1wEjsLV/ZKOf/CCrJ/QOBsxx6fOARIkwTutxp1XIOIohi6HKmOFjMoK/XaqDVUpEEw==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/cls-hooked": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/cls-hooked/-/cls-hooked-4.2.2.tgz", + "integrity": "sha512-J4Xj5f5wq/4jAvcdgoGsL3G103BtWpZrMo8NEinRltN+xpTZdI+M38pyQqhuFU/P792xkMFvnKSf+Lm81U1bxw==", + "dependencies": { + "async-hook-jl": "^1.7.6", + "emitter-listener": "^1.0.1", + "semver": "^5.4.1" + }, + "engines": { + "node": "^4.7 || >=6.9 || >=7.3 || >=8.2.1" + } + }, + "node_modules/code-excerpt": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-3.0.0.tgz", + "integrity": "sha512-VHNTVhd7KsLGOqfX3SyeO8RyYPMp1GJOg194VITk04WMYCv4plV68YWe6TJZxd9MhobjtpMRnVky01gqZsalaw==", + "dependencies": { + "convert-to-spaces": "^1.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "engines": { + "node": "^12.20.0 || >=14" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/continuation-local-storage": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/continuation-local-storage/-/continuation-local-storage-3.2.1.tgz", + "integrity": "sha512-jx44cconVqkCEEyLSKWwkvUXwO561jXMa3LPjTPsm5QR22PA0/mhe33FT4Xb5y74JDvt/Cq+5lm8S8rskLv9ZA==", + "dependencies": { + "async-listener": "^0.6.0", + "emitter-listener": "^1.1.1" + } + }, + "node_modules/convert-to-spaces": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-1.0.2.tgz", + "integrity": "sha512-cj09EBuObp9gZNQCzc7hByQyrs6jVGE+o9kSJmeUoj+GiPiJvi5LYqEH/Hmme4+MTLHM+Ejtq+FChpjjEnsPdQ==", + "engines": { + "node": ">= 4" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/defaults": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", + "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", + "dependencies": { + "clone": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==" + }, + "node_modules/diagnostic-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/diagnostic-channel/-/diagnostic-channel-1.1.0.tgz", + "integrity": "sha512-fwujyMe1gj6rk6dYi9hMZm0c8Mz8NDMVl2LB4iaYh3+LIAThZC8RKFGXWG0IML2OxAit/ZFRgZhMkhQ3d/bobQ==", + "dependencies": { + "semver": "^5.3.0" + } + }, + "node_modules/diagnostic-channel-publishers": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/diagnostic-channel-publishers/-/diagnostic-channel-publishers-1.0.5.tgz", + "integrity": "sha512-dJwUS0915pkjjimPJVDnS/QQHsH0aOYhnZsLJdnZIMOrB+csj8RnZhWTuwnm8R5v3Z7OZs+ksv5luC14DGB7eg==", + "peerDependencies": { + "diagnostic-channel": "*" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" + }, + "node_modules/emitter-listener": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/emitter-listener/-/emitter-listener-1.1.2.tgz", + "integrity": "sha512-Bt1sBAGFHY9DKY+4/2cV6izcKJUf5T7/gkdmkxzX/qv9CcGH8xSwVRW5mtX03SWJtRTWSOpzCuWN9rBFYZepZQ==", + "dependencies": { + "shimmer": "^1.2.0" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", + "engines": { + "node": "*" + } + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/immer": { + "version": "9.0.19", + "resolved": "https://registry.npmjs.org/immer/-/immer-9.0.19.tgz", + "integrity": "sha512-eY+Y0qcsB4TZKwgQzLaE/lqYMlKhv5J9dyd2RhhtGhNo2njPXDqU9XPfcNfa3MIDsdtZt5KlkIsirlo4dHsWdQ==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ink": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ink/-/ink-3.2.0.tgz", + "integrity": "sha512-firNp1q3xxTzoItj/eOOSZQnYSlyrWks5llCTVX37nJ59K3eXbQ8PtzCguqo8YI19EELo5QxaKnJd4VxzhU8tg==", + "dependencies": { + "ansi-escapes": "^4.2.1", + "auto-bind": "4.0.0", + "chalk": "^4.1.0", + "cli-boxes": "^2.2.0", + "cli-cursor": "^3.1.0", + "cli-truncate": "^2.1.0", + "code-excerpt": "^3.0.0", + "indent-string": "^4.0.0", + "is-ci": "^2.0.0", + "lodash": "^4.17.20", + "patch-console": "^1.0.0", + "react-devtools-core": "^4.19.1", + "react-reconciler": "^0.26.2", + "scheduler": "^0.20.2", + "signal-exit": "^3.0.2", + "slice-ansi": "^3.0.0", + "stack-utils": "^2.0.2", + "string-width": "^4.2.2", + "type-fest": "^0.12.0", + "widest-line": "^3.1.0", + "wrap-ansi": "^6.2.0", + "ws": "^7.5.5", + "yoga-layout-prebuilt": "^1.9.6" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "@types/react": ">=16.8.0", + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/ink-divider": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ink-divider/-/ink-divider-3.0.0.tgz", + "integrity": "sha512-Mqb9WArtEZCtXw622aHhJqPK157QNc+8ssl9/RvAZlS6nZRCKyW4mYOYCudQh6dSuFGt9eG5yaqT1mJaGmwu+w==", + "dependencies": { + "prop-types": "^15.7.2", + "string-width": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "ink": ">=3.0.0", + "react": ">=16.8.0" + } + }, + "node_modules/ink-select-input": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/ink-select-input/-/ink-select-input-4.2.2.tgz", + "integrity": "sha512-E5AS2Vnd4CSzEa7Rm+hG47wxRQo1ASfh4msKxO7FHmn/ym+GKSSsFIfR+FonqjKNDPXYJClw8lM47RdN3Pi+nw==", + "dependencies": { + "arr-rotate": "^1.0.0", + "figures": "^3.2.0", + "lodash.isequal": "^4.5.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "ink": "^3.0.5", + "react": "^16.5.2 || ^17.0.0" + } + }, + "node_modules/ink-spinner": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/ink-spinner/-/ink-spinner-4.0.3.tgz", + "integrity": "sha512-uJ4nbH00MM9fjTJ5xdw0zzvtXMkeGb0WV6dzSWvFv2/+ks6FIhpkt+Ge/eLdh0Ah6Vjw5pLMyNfoHQpRDRVFbQ==", + "dependencies": { + "cli-spinners": "^2.3.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "ink": ">=3.0.5", + "react": ">=16.8.2" + } + }, + "node_modules/ink-text-input": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-4.0.3.tgz", + "integrity": "sha512-eQD01ik9ltmNoHmkeQ2t8LszYkv2XwuPSUz3ie/85qer6Ll/j0QSlSaLNl6ENHZakBHdCBVZY04iOXcLLXA0PQ==", + "dependencies": { + "chalk": "^4.1.0", + "type-fest": "^0.15.1" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "ink": "^3.0.0-3", + "react": "^16.5.2 || ^17.0.0" + } + }, + "node_modules/ink-text-input/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink-text-input/node_modules/type-fest": { + "version": "0.15.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.15.1.tgz", + "integrity": "sha512-n+UXrN8i5ioo7kqT/nF8xsEzLaqFra7k32SEsSPwvXVGyAcRgV/FUQN/sgfptJTR1oRmmq7z4IXMFSM7im7C9A==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/inquirer": { + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-9.1.4.tgz", + "integrity": "sha512-9hiJxE5gkK/cM2d1mTEnuurGTAoHebbkX0BYl3h7iEg7FYfuNIom+nDfBCSWtvSnoSrWCeBxqqBZu26xdlJlXA==", + "dependencies": { + "ansi-escapes": "^6.0.0", + "chalk": "^5.1.2", + "cli-cursor": "^4.0.0", + "cli-width": "^4.0.0", + "external-editor": "^3.0.3", + "figures": "^5.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^6.1.2", + "run-async": "^2.4.0", + "rxjs": "^7.5.7", + "string-width": "^5.1.2", + "strip-ansi": "^7.0.1", + "through": "^2.3.6", + "wrap-ansi": "^8.0.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-escapes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-6.0.0.tgz", + "integrity": "sha512-IG23inYII3dWlU2EyiAiGj6Bwal5GzsgPMwjYGvc1HPE2dgbj4ZB5ToWBKSquKw74nB3TIuOwaI6/jSULzfgrw==", + "dependencies": { + "type-fest": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, + "node_modules/inquirer/node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/figures": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-5.0.0.tgz", + "integrity": "sha512-ej8ksPF4x6e5wvK9yevct0UCXh8TTFlWGVLlgjZuoBH1HwjIfKE/IdL5mq89sFA7zELi1VhKpmtDnrs7zWyeyg==", + "dependencies": { + "escape-string-regexp": "^5.0.0", + "is-unicode-supported": "^1.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/type-fest": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.6.1.tgz", + "integrity": "sha512-htXWckxlT6U4+ilVgweNliPqlsVSSucbxVexRYllyMVJDtf5rTjv6kF/s+qAd4QSL1BZcnJPEJavYBPQiWuZDA==", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dependencies": { + "ci-info": "^2.0.0" + }, + "bin": { + "is-ci": "bin.js" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", + "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==" + }, + "node_modules/log-symbols": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-5.1.0.tgz", + "integrity": "sha512-l0x2DvrW294C9uDCoQe1VSU4gf529FkSZ6leBl4TiqZH/e+0R7hSfHQBNut2mNygDgHwvYHfFLn6Oxb3VWj2rA==", + "dependencies": { + "chalk": "^5.0.0", + "is-unicode-supported": "^1.1.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/marked": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.2.12.tgz", + "integrity": "sha512-yr8hSKa3Fv4D3jdZmtMMPghgVt6TWbk86WQaWhDloQjRSQhMMYCAro7jP7VDJrjjdV8pxVxMssXS8B8Y5DZ5aw==", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/marked-terminal": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/marked-terminal/-/marked-terminal-5.1.1.tgz", + "integrity": "sha512-+cKTOx9P4l7HwINYhzbrBSyzgxO2HaHKGZGuB1orZsMIgXYaJyfidT81VXRdpelW/PcHEWxywscePVgI/oUF6g==", + "dependencies": { + "ansi-escapes": "^5.0.0", + "cardinal": "^2.1.1", + "chalk": "^5.0.0", + "cli-table3": "^0.6.1", + "node-emoji": "^1.11.0", + "supports-hyperlinks": "^2.2.0" + }, + "engines": { + "node": ">=14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "marked": "^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0" + } + }, + "node_modules/marked-terminal/node_modules/ansi-escapes": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-5.0.0.tgz", + "integrity": "sha512-5GFMVX8HqE/TB+FuBJGuO5XG0WrsA6ptUqoODaT/n9mmUaZFkqnBueB4leqGBCmrUHnCnC4PCZTCd0E7QQ83bA==", + "dependencies": { + "type-fest": "^1.0.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/marked-terminal/node_modules/type-fest": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz", + "integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/match-sorter": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/match-sorter/-/match-sorter-6.3.1.tgz", + "integrity": "sha512-mxybbo3pPNuA+ZuCUhm5bwNkXrJTbsk5VWbR5wiwz/GC6LIiegBGn2w3O08UG/jdbYLinw51fSQ5xNU1U3MgBw==", + "dependencies": { + "@babel/runtime": "^7.12.5", + "remove-accents": "0.4.2" + } + }, + "node_modules/microseconds": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/microseconds/-/microseconds-0.2.0.tgz", + "integrity": "sha512-n7DHHMjR1avBbSpsTBj6fmMGh2AGrifVV4e+WYc3Q9lO+xnSZ3NyhcBND3vzzatt05LFhoKFRxrIyklmLlUtyA==" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nano-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/nano-time/-/nano-time-1.0.0.tgz", + "integrity": "sha512-flnngywOoQ0lLQOTRNexn2gGSNuM9bKj9RZAWSzhQ+UJYaAFG9bac4DW9VHjUAzrOaIcajHybCTHe/bkvozQqA==", + "dependencies": { + "big-integer": "^1.6.16" + } + }, + "node_modules/node-emoji": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", + "integrity": "sha512-wo2DpQkQp7Sjm2A0cq+sN7EHKO6Sl0ctXeBdFZrL9T9+UywORbufTcTZxom8YqpLQt/FqNMUkOpkZrJVYSKD3A==", + "dependencies": { + "lodash": "^4.17.21" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/oblivious-set": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/oblivious-set/-/oblivious-set-1.0.0.tgz", + "integrity": "sha512-z+pI07qxo4c2CulUHCDf9lcqDlMSo72N/4rLUpRXf6fu+q8vjt8y0xS+Tlf8NTJDdTXHbdeO1n3MlbctwEoXZw==" + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/ora/-/ora-6.1.2.tgz", + "integrity": "sha512-EJQ3NiP5Xo94wJXIzAyOtSb0QEIAUu7m8t6UZ9krbz0vAJqr92JpcK/lEXg91q6B9pEGqrykkd2EQplnifDSBw==", + "dependencies": { + "bl": "^5.0.0", + "chalk": "^5.0.0", + "cli-cursor": "^4.0.0", + "cli-spinners": "^2.6.1", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^1.1.0", + "log-symbols": "^5.1.0", + "strip-ansi": "^7.0.1", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/parse5": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz", + "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==" + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz", + "integrity": "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==", + "dependencies": { + "parse5": "^6.0.1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", + "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==" + }, + "node_modules/patch-console": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-1.0.0.tgz", + "integrity": "sha512-nxl9nrnLQmh64iTzMfyylSlRozL7kAXIaxw1fVcLYdyhNkJCRUzirRZTikXGJsg+hc4fqpneTK6iU2H1Q8THSA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/radash": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/radash/-/radash-9.5.0.tgz", + "integrity": "sha512-t0s8BJlvrk8YPaOS8X0J2xzqAsBlXAUkDEjoBXwlzaXsXNCpBILjT9OvWlabLa2KB/r4XrhThdXjxMs7SiCyIw==", + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/react": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", + "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-devtools-core": { + "version": "4.27.2", + "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-4.27.2.tgz", + "integrity": "sha512-8SzmIkpO87alD7Xr6gWIEa1jHkMjawOZ+6egjazlnjB4UUcbnzGDf/vBJ4BzGuWWEM+pzrxuzsPpcMqlQkYK2g==", + "dependencies": { + "shell-quote": "^1.6.1", + "ws": "^7" + } + }, + "node_modules/react-dom": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz", + "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "scheduler": "^0.20.2" + }, + "peerDependencies": { + "react": "17.0.2" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "node_modules/react-query": { + "version": "3.39.3", + "resolved": "https://registry.npmjs.org/react-query/-/react-query-3.39.3.tgz", + "integrity": "sha512-nLfLz7GiohKTJDuT4us4X3h/8unOh+00MLb2yJoGTPjxKs2bc1iDhkNx2bd5MKklXnOD3NrVZ+J2UXujA5In4g==", + "dependencies": { + "@babel/runtime": "^7.5.5", + "broadcast-channel": "^3.4.1", + "match-sorter": "^6.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, + "node_modules/react-reconciler": { + "version": "0.26.2", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.26.2.tgz", + "integrity": "sha512-nK6kgY28HwrMNwDnMui3dvm3rCFjZrcGiuwLc5COUipBK5hWHLOxMJhSnSomirqWwjPBJKV1QcbkI0VJr7Gl1Q==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1", + "scheduler": "^0.20.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^17.0.2" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/redeyed": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/redeyed/-/redeyed-2.1.1.tgz", + "integrity": "sha512-FNpGGo1DycYAdnrKFxCMmKYgo/mILAqtRYbkdQD8Ep/Hk2PQ5+aEAEx+IU713RTDmuBaH0c8P5ZozurNu5ObRQ==", + "dependencies": { + "esprima": "~4.0.0" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==" + }, + "node_modules/remove-accents": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/remove-accents/-/remove-accents-0.4.2.tgz", + "integrity": "sha512-7pXIJqJOq5tFgG1A2Zxti3Ht8jJF337m4sowbuHsW30ZnkQFnDzy9qBNhgzX8ZLW4+UBcXiiR7SwR6pokHsxiA==" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.0.tgz", + "integrity": "sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/scheduler": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz", + "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + } + }, + "node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/shell-quote": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.0.tgz", + "integrity": "sha512-QHsz8GgQIGKlRi24yFc6a6lN69Idnx634w49ay6+jA5yFh7a1UY+4Rp6HPx/L/1zcEDPEij8cIsiqR6bQsE5VQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/shimmer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", + "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/slice-ansi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", + "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/stack-chain": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/stack-chain/-/stack-chain-1.3.7.tgz", + "integrity": "sha512-D8cWtWVdIe/jBA7v5p5Hwl5yOSOrmZPWDPe2KxQ5UAGD+nxbxU0lKXA4h85Ta6+qgdKVL3vUxsbIZjc1kBG7ug==" + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz", + "integrity": "sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw==", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-hyperlinks": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-2.3.0.tgz", + "integrity": "sha512-RpsAZlpWcDwOPQA22aCH4J0t7L8JmAvsCxfOSEwm7cQs3LshN36QaTkwd70DnBOXDWGssw2eUoc8CaRWT0XunA==", + "dependencies": { + "has-flag": "^4.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" + }, + "node_modules/tiny-invariant": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.1.tgz", + "integrity": "sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==" + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/ts-dedent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz", + "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==", + "engines": { + "node": ">=6.10" + } + }, + "node_modules/tslib": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", + "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==" + }, + "node_modules/type-fest": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.12.0.tgz", + "integrity": "sha512-53RyidyjvkGpnWPMF9bQgFtWp+Sl8O2Rp13VavmJgfAP9WWG6q6TkrKU8iyJdnwnfgHI6k2hTlgqH4aSdjoTbg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/unload": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/unload/-/unload-2.2.0.tgz", + "integrity": "sha512-B60uB5TNBLtN6/LsgAf3udH9saB5p7gqJwcFfbOEZ8BcBHnGwCf6G/TGiEqkRAxX7zAFIUtzdrXQSdL3Q/wqNA==", + "dependencies": { + "@babel/runtime": "^7.6.2", + "detect-node": "^2.0.4" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz", + "integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/use-zustand": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/use-zustand/-/use-zustand-0.0.1.tgz", + "integrity": "sha512-axjswesUfXirTQ1CC1F4r0dkaI7g2nMEftyvg23Wq4PnAbLogswzj+o5gbnnnQaQOMXKHxNZIlYpKfuTnL466Q==", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/uuid": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz", + "integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/widest-line": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", + "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "dependencies": { + "string-width": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yoga-layout-prebuilt": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/yoga-layout-prebuilt/-/yoga-layout-prebuilt-1.10.0.tgz", + "integrity": "sha512-YnOmtSbv4MTf7RGJMK0FvZ+KD8OEe/J5BNnR0GHhD8J/XcG/Qvxgszm0Un6FTHWW4uHlTgP0IztiXQnGyIR45g==", + "dependencies": { + "@types/yoga-layout": "1.9.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/zustand": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.3.6.tgz", + "integrity": "sha512-6J5zDxjxLE+yukC2XZWf/IyWVKnXT9b9HUv09VJ/bwGCpKNcaTqp7Ws28Xr8jnbvnZcdRaidztAPsXFBIqufiw==", + "dependencies": { + "use-sync-external-store": "1.2.0" + }, + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "immer": ">=9.0", + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "immer": { + "optional": true + }, + "react": { + "optional": true + } + } + } + } +} diff --git a/node_modules/@azure/abort-controller/CHANGELOG.md b/node_modules/@azure/abort-controller/CHANGELOG.md new file mode 100644 index 0000000..b764523 --- /dev/null +++ b/node_modules/@azure/abort-controller/CHANGELOG.md @@ -0,0 +1,34 @@ +# Release History + +## 1.1.0 (2022-05-05) + +- Changed TS compilation target to ES2017 in order to produce smaller bundles and use more native platform features +- With the dropping of support for Node.js versions that are no longer in LTS, the dependency on `@types/node` has been updated to version 12. Read our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. + +## 1.0.4 (2021-03-04) + +Fixes issue [13985](https://github.com/Azure/azure-sdk-for-js/issues/13985) where abort event listeners that removed themselves when invoked could prevent other event listeners from being invoked. + +## 1.0.3 (2021-02-23) + +Support Typescript version < 3.6 by down-leveling the type definition files. ([PR 12793](https://github.com/Azure/azure-sdk-for-js/pull/12793)) + +## 1.0.2 (2020-01-07) + +Updates the `tslib` dependency to version 2.x. + +## 1.0.1 (2019-12-04) + +Fixes the [bug 6271](https://github.com/Azure/azure-sdk-for-js/issues/6271) that can occur with angular prod builds due to triple-slash directives. +([PR 6344](https://github.com/Azure/azure-sdk-for-js/pull/6344)) + +## 1.0.0 (2019-10-29) + +This release marks the general availability of the `@azure/abort-controller` package. + +Removed the browser bundle. A browser-compatible library can still be created through the use of a bundler such as Rollup, Webpack, or Parcel. +([#5860](https://github.com/Azure/azure-sdk-for-js/pull/5860)) + +## 1.0.0-preview.2 (2019-09-09) + +Listeners attached to an `AbortSignal` now receive an event with the type `abort`. (PR #4756) diff --git a/node_modules/@azure/abort-controller/LICENSE b/node_modules/@azure/abort-controller/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/abort-controller/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/abort-controller/README.md b/node_modules/@azure/abort-controller/README.md new file mode 100644 index 0000000..ce578d9 --- /dev/null +++ b/node_modules/@azure/abort-controller/README.md @@ -0,0 +1,110 @@ +# Azure Abort Controller client library for JavaScript + +The `@azure/abort-controller` package provides `AbortController` and `AbortSignal` classes. These classes are compatible +with the [AbortController](https://developer.mozilla.org/docs/Web/API/AbortController) built into modern browsers +and the `AbortSignal` used by [fetch](https://developer.mozilla.org/docs/Web/API/Fetch_API). +Use the `AbortController` class to create an instance of the `AbortSignal` class that can be used to cancel an operation +in an Azure SDK that accept a parameter of type `AbortSignalLike`. + +Key links: + +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/abort-controller) +- [Package (npm)](https://www.npmjs.com/package/@azure/abort-controller) +- [API Reference Documentation](https://docs.microsoft.com/javascript/api/overview/azure/abort-controller-readme) + +## Getting started + +### Installation + +Install this library using npm as follows + +``` +npm install @azure/abort-controller +``` + +## Key Concepts + +Use the `AbortController` to create an `AbortSignal` which can then be passed to Azure SDK operations to cancel +pending work. The `AbortSignal` can be accessed via the `signal` property on an instantiated `AbortController`. +An `AbortSignal` can also be returned directly from a static method, e.g. `AbortController.timeout(100)`. +that is cancelled after 100 milliseconds. + +Calling `abort()` on the instantiated `AbortController` invokes the registered `abort` +event listeners on the associated `AbortSignal`. +Any subsequent calls to `abort()` on the same controller will have no effect. + +The `AbortSignal.none` static property returns an `AbortSignal` that can not be aborted. + +Multiple instances of an `AbortSignal` can be linked so that calling `abort()` on the parent signal, +aborts all linked signals. +This linkage is one-way, meaning that a parent signal can affect a linked signal, but not the other way around. +To link `AbortSignals` together, pass in the parent signals to the `AbortController` constructor. + +## Examples + +The below examples assume that `doAsyncWork` is a function that takes a bag of properties, one of which is +of the abort signal. + +### Example 1 - basic usage + +```js +import { AbortController } from "@azure/abort-controller"; + +const controller = new AbortController(); +doAsyncWork({ abortSignal: controller.signal }); + +// at some point later +controller.abort(); +``` + +### Example 2 - Aborting with timeout + +```js +import { AbortController } from "@azure/abort-controller"; + +const signal = AbortController.timeout(1000); +doAsyncWork({ abortSignal: signal }); +``` + +### Example 3 - Aborting sub-tasks + +```js +import { AbortController } from "@azure/abort-controller"; + +const allTasksController = new AbortController(); + +const subTask1 = new AbortController(allTasksController.signal); +const subtask2 = new AbortController(allTasksController.signal); + +allTasksController.abort(); // aborts allTasksSignal, subTask1, subTask2 +subTask1.abort(); // aborts only subTask1 +``` + +### Example 4 - Aborting with parent signal or timeout + +```js +import { AbortController } from "@azure/abort-controller"; + +const allTasksController = new AbortController(); + +// create a subtask controller that can be aborted manually, +// or when either the parent task aborts or the timeout is reached. +const subTask = new AbortController(allTasksController.signal, AbortController.timeout(100)); + +allTasksController.abort(); // aborts allTasksSignal, subTask +subTask.abort(); // aborts only subTask +``` + +## Next steps + +You can build and run the tests locally by executing `rushx test`. Explore the `test` folder to see advanced usage and behavior of the public classes. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Fabort-controller%2FREADME.png) diff --git a/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js b/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js new file mode 100644 index 0000000..0d260f3 --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { AbortSignal, abortSignal } from "./AbortSignal"; +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` + */ +export class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; + } +} +/** + * An AbortController provides an AbortSignal and the associated controls to signal + * that an asynchronous operation should be aborted. + * + * @example + * Abort an operation when another event fires + * ```ts + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * ``` + * + * @example + * Share aborter cross multiple operations in 30s + * ```ts + * // Upload the same data to 2 different data centers at the same time, + * // abort another when any of them is finished + * const controller = AbortController.withTimeout(30 * 1000); + * doAsyncWork(controller.signal).then(controller.abort); + * doAsyncWork(controller.signal).then(controller.abort); + *``` + * + * @example + * Cascaded aborting + * ```ts + * // All operations can't take more than 30 seconds + * const aborter = Aborter.timeout(30 * 1000); + * + * // Following 2 operations can't take more than 25 seconds + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * ``` + */ +export class AbortController { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor(parentSignals) { + this._signal = new AbortSignal(); + if (!parentSignals) { + return; + } + // coerce parentSignals into an array + if (!Array.isArray(parentSignals)) { + // eslint-disable-next-line prefer-rest-params + parentSignals = arguments; + } + for (const parentSignal of parentSignals) { + // if the parent signal has already had abort() called, + // then call abort on this signal as well. + if (parentSignal.aborted) { + this.abort(); + } + else { + // when the parent signal aborts, this signal should as well. + parentSignal.addEventListener("abort", () => { + this.abort(); + }); + } + } + } + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal() { + return this._signal; + } + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + abort() { + abortSignal(this._signal); + } + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. + */ + static timeout(ms) { + const signal = new AbortSignal(); + const timer = setTimeout(abortSignal, ms, signal); + // Prevent the active Timer from keeping the Node.js event loop active. + if (typeof timer.unref === "function") { + timer.unref(); + } + return signal; + } +} +//# sourceMappingURL=AbortController.js.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js.map b/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js.map new file mode 100644 index 0000000..8a6f7d0 --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/AbortController.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbortController.js","sourceRoot":"","sources":["../../src/AbortController.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,WAAW,EAAmB,WAAW,EAAE,MAAM,eAAe,CAAC;AAE1E;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IACnC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;IAC3B,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,eAAe;IAW1B,6EAA6E;IAC7E,YAAY,aAAmB;QAC7B,IAAI,CAAC,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;QAEjC,IAAI,CAAC,aAAa,EAAE;YAClB,OAAO;SACR;QACD,qCAAqC;QACrC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YACjC,8CAA8C;YAC9C,aAAa,GAAG,SAAS,CAAC;SAC3B;QACD,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE;YACxC,uDAAuD;YACvD,0CAA0C;YAC1C,IAAI,YAAY,CAAC,OAAO,EAAE;gBACxB,IAAI,CAAC,KAAK,EAAE,CAAC;aACd;iBAAM;gBACL,6DAA6D;gBAC7D,YAAY,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;oBAC1C,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,CAAC,CAAC,CAAC;aACJ;SACF;IACH,CAAC;IAED;;;;;OAKG;IACH,IAAW,MAAM;QACf,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC5B,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,OAAO,CAAC,EAAU;QAC9B,MAAM,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QACjC,MAAM,KAAK,GAAG,UAAU,CAAC,WAAW,EAAE,EAAE,EAAE,MAAM,CAAC,CAAC;QAClD,uEAAuE;QACvE,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,UAAU,EAAE;YACrC,KAAK,CAAC,KAAK,EAAE,CAAC;SACf;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignal, AbortSignalLike, abortSignal } from \"./AbortSignal\";\n\n/**\n * This error is thrown when an asynchronous operation has been aborted.\n * Check for this error by testing the `name` that the name property of the\n * error matches `\"AbortError\"`.\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n * controller.abort();\n * try {\n * doAsyncWork(controller.signal)\n * } catch (e) {\n * if (e.name === 'AbortError') {\n * // handle abort error here.\n * }\n * }\n * ```\n */\nexport class AbortError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"AbortError\";\n }\n}\n\n/**\n * An AbortController provides an AbortSignal and the associated controls to signal\n * that an asynchronous operation should be aborted.\n *\n * @example\n * Abort an operation when another event fires\n * ```ts\n * const controller = new AbortController();\n * const signal = controller.signal;\n * doAsyncWork(signal);\n * button.addEventListener('click', () => controller.abort());\n * ```\n *\n * @example\n * Share aborter cross multiple operations in 30s\n * ```ts\n * // Upload the same data to 2 different data centers at the same time,\n * // abort another when any of them is finished\n * const controller = AbortController.withTimeout(30 * 1000);\n * doAsyncWork(controller.signal).then(controller.abort);\n * doAsyncWork(controller.signal).then(controller.abort);\n *```\n *\n * @example\n * Cascaded aborting\n * ```ts\n * // All operations can't take more than 30 seconds\n * const aborter = Aborter.timeout(30 * 1000);\n *\n * // Following 2 operations can't take more than 25 seconds\n * await doAsyncWork(aborter.withTimeout(25 * 1000));\n * await doAsyncWork(aborter.withTimeout(25 * 1000));\n * ```\n */\nexport class AbortController {\n private _signal: AbortSignal;\n\n /**\n * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller.\n */\n constructor(parentSignals?: AbortSignalLike[]);\n /**\n * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller.\n */\n constructor(...parentSignals: AbortSignalLike[]);\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n constructor(parentSignals?: any) {\n this._signal = new AbortSignal();\n\n if (!parentSignals) {\n return;\n }\n // coerce parentSignals into an array\n if (!Array.isArray(parentSignals)) {\n // eslint-disable-next-line prefer-rest-params\n parentSignals = arguments;\n }\n for (const parentSignal of parentSignals) {\n // if the parent signal has already had abort() called,\n // then call abort on this signal as well.\n if (parentSignal.aborted) {\n this.abort();\n } else {\n // when the parent signal aborts, this signal should as well.\n parentSignal.addEventListener(\"abort\", () => {\n this.abort();\n });\n }\n }\n }\n\n /**\n * The AbortSignal associated with this controller that will signal aborted\n * when the abort method is called on this controller.\n *\n * @readonly\n */\n public get signal(): AbortSignal {\n return this._signal;\n }\n\n /**\n * Signal that any operations passed this controller's associated abort signal\n * to cancel any remaining work and throw an `AbortError`.\n */\n abort(): void {\n abortSignal(this._signal);\n }\n\n /**\n * Creates a new AbortSignal instance that will abort after the provided ms.\n * @param ms - Elapsed time in milliseconds to trigger an abort.\n */\n public static timeout(ms: number): AbortSignal {\n const signal = new AbortSignal();\n const timer = setTimeout(abortSignal, ms, signal);\n // Prevent the active Timer from keeping the Node.js event loop active.\n if (typeof timer.unref === \"function\") {\n timer.unref();\n }\n return signal;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js b/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js new file mode 100644 index 0000000..e97336a --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/// +const listenersMap = new WeakMap(); +const abortedMap = new WeakMap(); +/** + * An aborter instance implements AbortSignal interface, can abort HTTP requests. + * + * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. + * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation + * cannot or will not ever be cancelled. + * + * @example + * Abort without timeout + * ```ts + * await doAsyncWork(AbortSignal.none); + * ``` + */ +export class AbortSignal { + constructor() { + /** + * onabort event listener. + */ + this.onabort = null; + listenersMap.set(this, []); + abortedMap.set(this, false); + } + /** + * Status of whether aborted or not. + * + * @readonly + */ + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); + } + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static get none() { + return new AbortSignal(); + } + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added + */ + addEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + const listeners = listenersMap.get(this); + listeners.push(listener); + } + /** + * Remove "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be removed + */ + removeEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + } + /** + * Dispatches a synthetic event to the AbortSignal. + */ + dispatchEvent(_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); + } +} +/** + * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. + * Will try to trigger abort event for all linked AbortSignal nodes. + * + * - If there is a timeout, the timer will be cancelled. + * - If aborted is true, nothing will happen. + * + * @internal + */ +// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters +export function abortSignal(signal) { + if (signal.aborted) { + return; + } + if (signal.onabort) { + signal.onabort.call(signal); + } + const listeners = listenersMap.get(signal); + if (listeners) { + // Create a copy of listeners so mutations to the array + // (e.g. via removeListener calls) don't affect the listeners + // we invoke. + listeners.slice().forEach((listener) => { + listener.call(signal, { type: "abort" }); + }); + } + abortedMap.set(signal, true); +} +//# sourceMappingURL=AbortSignal.js.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js.map b/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js.map new file mode 100644 index 0000000..1ca33bd --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/AbortSignal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbortSignal.js","sourceRoot":"","sources":["../../src/AbortSignal.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,6CAA6C;AAI7C,MAAM,YAAY,GAAG,IAAI,OAAO,EAAqC,CAAC;AACtE,MAAM,UAAU,GAAG,IAAI,OAAO,EAAwB,CAAC;AA6BvD;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,WAAW;IACtB;QA2BA;;WAEG;QACI,YAAO,GAAiC,IAAI,CAAC;QA7BlD,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC3B,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED;;;;OAIG;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AAM,CAAC,OAAO,EAAE;QAClB,OAAO;KACR;IAED,IAAI,MAAM,CAAC,OAAO,EAAE;QAClB,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KAC7B;IAED,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAE,CAAC;IAC5C,IAAI,SAAS,EAAE;QACb,uDAAuD;QACvD,6DAA6D;QAC7D,aAAa;QACb,SAAS,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;YACrC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QAC3C,CAAC,CAAC,CAAC;KACJ;IAED,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// \n\ntype AbortEventListener = (this: AbortSignalLike, ev?: any) => any;\n\nconst listenersMap = new WeakMap();\nconst abortedMap = new WeakMap();\n\n/**\n * Allows the request to be aborted upon firing of the \"abort\" event.\n * Compatible with the browser built-in AbortSignal and common polyfills.\n */\nexport interface AbortSignalLike {\n /**\n * Indicates if the signal has already been aborted.\n */\n readonly aborted: boolean;\n /**\n * Add new \"abort\" event listener, only support \"abort\" event.\n */\n addEventListener(\n type: \"abort\",\n listener: (this: AbortSignalLike, ev: any) => any,\n options?: any\n ): void;\n /**\n * Remove \"abort\" event listener, only support \"abort\" event.\n */\n removeEventListener(\n type: \"abort\",\n listener: (this: AbortSignalLike, ev: any) => any,\n options?: any\n ): void;\n}\n\n/**\n * An aborter instance implements AbortSignal interface, can abort HTTP requests.\n *\n * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled.\n * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation\n * cannot or will not ever be cancelled.\n *\n * @example\n * Abort without timeout\n * ```ts\n * await doAsyncWork(AbortSignal.none);\n * ```\n */\nexport class AbortSignal implements AbortSignalLike {\n constructor() {\n listenersMap.set(this, []);\n abortedMap.set(this, false);\n }\n\n /**\n * Status of whether aborted or not.\n *\n * @readonly\n */\n public get aborted(): boolean {\n if (!abortedMap.has(this)) {\n throw new TypeError(\"Expected `this` to be an instance of AbortSignal.\");\n }\n\n return abortedMap.get(this)!;\n }\n\n /**\n * Creates a new AbortSignal instance that will never be aborted.\n *\n * @readonly\n */\n public static get none(): AbortSignal {\n return new AbortSignal();\n }\n\n /**\n * onabort event listener.\n */\n public onabort: ((ev?: Event) => any) | null = null;\n\n /**\n * Added new \"abort\" event listener, only support \"abort\" event.\n *\n * @param _type - Only support \"abort\" event\n * @param listener - The listener to be added\n */\n public addEventListener(\n // tslint:disable-next-line:variable-name\n _type: \"abort\",\n listener: (this: AbortSignalLike, ev: any) => any\n ): void {\n if (!listenersMap.has(this)) {\n throw new TypeError(\"Expected `this` to be an instance of AbortSignal.\");\n }\n\n const listeners = listenersMap.get(this)!;\n listeners.push(listener);\n }\n\n /**\n * Remove \"abort\" event listener, only support \"abort\" event.\n *\n * @param _type - Only support \"abort\" event\n * @param listener - The listener to be removed\n */\n public removeEventListener(\n // tslint:disable-next-line:variable-name\n _type: \"abort\",\n listener: (this: AbortSignalLike, ev: any) => any\n ): void {\n if (!listenersMap.has(this)) {\n throw new TypeError(\"Expected `this` to be an instance of AbortSignal.\");\n }\n\n const listeners = listenersMap.get(this)!;\n\n const index = listeners.indexOf(listener);\n if (index > -1) {\n listeners.splice(index, 1);\n }\n }\n\n /**\n * Dispatches a synthetic event to the AbortSignal.\n */\n dispatchEvent(_event: Event): boolean {\n throw new Error(\n \"This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes.\"\n );\n }\n}\n\n/**\n * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered.\n * Will try to trigger abort event for all linked AbortSignal nodes.\n *\n * - If there is a timeout, the timer will be cancelled.\n * - If aborted is true, nothing will happen.\n *\n * @internal\n */\n// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters\nexport function abortSignal(signal: AbortSignal): void {\n if (signal.aborted) {\n return;\n }\n\n if (signal.onabort) {\n signal.onabort.call(signal);\n }\n\n const listeners = listenersMap.get(signal)!;\n if (listeners) {\n // Create a copy of listeners so mutations to the array\n // (e.g. via removeListener calls) don't affect the listeners\n // we invoke.\n listeners.slice().forEach((listener) => {\n listener.call(signal, { type: \"abort\" });\n });\n }\n\n abortedMap.set(signal, true);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/dist-esm/src/index.js b/node_modules/@azure/abort-controller/dist-esm/src/index.js new file mode 100644 index 0000000..ddbf505 --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/index.js @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// Changes to Aborter +// * Rename Aborter to AbortSignal +// * Remove withValue and getValue - async context should be solved differently/wholistically, not tied to cancellation +// * Remove withTimeout, it's moved to the controller +// * AbortSignal constructor no longer takes a parent. Cancellation graphs are created from the controller. +// Potential changes to align with DOM Spec +// * dispatchEvent on Signal +export { AbortController, AbortError } from "./AbortController"; +export { AbortSignal } from "./AbortSignal"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/dist-esm/src/index.js.map b/node_modules/@azure/abort-controller/dist-esm/src/index.js.map new file mode 100644 index 0000000..def556e --- /dev/null +++ b/node_modules/@azure/abort-controller/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,qBAAqB;AACrB,kCAAkC;AAClC,uHAAuH;AACvH,qDAAqD;AACrD,2GAA2G;AAE3G,2CAA2C;AAC3C,4BAA4B;AAE5B,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAmB,MAAM,eAAe,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// Changes to Aborter\n// * Rename Aborter to AbortSignal\n// * Remove withValue and getValue - async context should be solved differently/wholistically, not tied to cancellation\n// * Remove withTimeout, it's moved to the controller\n// * AbortSignal constructor no longer takes a parent. Cancellation graphs are created from the controller.\n\n// Potential changes to align with DOM Spec\n// * dispatchEvent on Signal\n\nexport { AbortController, AbortError } from \"./AbortController\";\nexport { AbortSignal, AbortSignalLike } from \"./AbortSignal\";\n"]} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/package.json b/node_modules/@azure/abort-controller/package.json new file mode 100644 index 0000000..6126bc2 --- /dev/null +++ b/node_modules/@azure/abort-controller/package.json @@ -0,0 +1,104 @@ +{ + "name": "@azure/abort-controller", + "sdk-type": "client", + "version": "1.1.0", + "description": "Microsoft Azure SDK for JavaScript - Aborter", + "main": "./dist/index.js", + "module": "dist-esm/src/index.js", + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build:types": "downlevel-dts types/src types/3.1", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local && npm run build:types", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "karma start --single-run", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "types": "./types/src/index.d.ts", + "typesVersions": { + "<3.6": { + "types/src/*": [ + "types/3.1/*" + ] + } + }, + "files": [ + "dist/", + "dist-esm/src/", + "shims-public.d.ts", + "types/src", + "types/3.1", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=12.0.0" + }, + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "aborter", + "abortsignal", + "cancellation", + "node.js", + "typescript", + "javascript", + "browser", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/abort-controller/README.md", + "sideEffects": false, + "dependencies": { + "tslib": "^2.2.0" + }, + "devDependencies": { + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@microsoft/api-extractor": "7.18.11", + "@types/chai": "^4.1.6", + "@types/mocha": "^7.0.2", + "@types/node": "^12.0.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "downlevel-dts": "^0.8.0", + "eslint": "^7.15.0", + "karma": "^6.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-edge-launcher": "^0.4.2", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.3.8", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "nyc": "^15.0.0", + "prettier": "^2.5.1", + "rimraf": "^3.0.0", + "ts-node": "^10.0.0", + "typescript": "~4.6.0" + } +} diff --git a/node_modules/@azure/abort-controller/shims-public.d.ts b/node_modules/@azure/abort-controller/shims-public.d.ts new file mode 100644 index 0000000..002bec3 --- /dev/null +++ b/node_modules/@azure/abort-controller/shims-public.d.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// forward declaration of Event in case DOM libs are not present. +interface Event {} diff --git a/node_modules/@azure/abort-controller/types/3.1/AbortController.d.ts b/node_modules/@azure/abort-controller/types/3.1/AbortController.d.ts new file mode 100644 index 0000000..6f935db --- /dev/null +++ b/node_modules/@azure/abort-controller/types/3.1/AbortController.d.ts @@ -0,0 +1,85 @@ +import { AbortSignal, AbortSignalLike } from "./AbortSignal"; +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` + */ +export declare class AbortError extends Error { + constructor(message?: string); +} +/** + * An AbortController provides an AbortSignal and the associated controls to signal + * that an asynchronous operation should be aborted. + * + * @example + * Abort an operation when another event fires + * ```ts + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * ``` + * + * @example + * Share aborter cross multiple operations in 30s + * ```ts + * // Upload the same data to 2 different data centers at the same time, + * // abort another when any of them is finished + * const controller = AbortController.withTimeout(30 * 1000); + * doAsyncWork(controller.signal).then(controller.abort); + * doAsyncWork(controller.signal).then(controller.abort); + *``` + * + * @example + * Cascaded aborting + * ```ts + * // All operations can't take more than 30 seconds + * const aborter = Aborter.timeout(30 * 1000); + * + * // Following 2 operations can't take more than 25 seconds + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * ``` + */ +export declare class AbortController { + private _signal; + /** + * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller. + */ + constructor(parentSignals?: AbortSignalLike[]); + /** + * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller. + */ + constructor(...parentSignals: AbortSignalLike[]); + /* + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + readonly signal: AbortSignal; + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + abort(): void; + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. + */ + static timeout(ms: number): AbortSignal; +} +//# sourceMappingURL=AbortController.d.ts.map diff --git a/node_modules/@azure/abort-controller/types/3.1/AbortSignal.d.ts b/node_modules/@azure/abort-controller/types/3.1/AbortSignal.d.ts new file mode 100644 index 0000000..53d6a77 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/3.1/AbortSignal.d.ts @@ -0,0 +1,80 @@ +/// +/** + * Allows the request to be aborted upon firing of the "abort" event. + * Compatible with the browser built-in AbortSignal and common polyfills. + */ +export interface AbortSignalLike { + /** + * Indicates if the signal has already been aborted. + */ + readonly aborted: boolean; + /** + * Add new "abort" event listener, only support "abort" event. + */ + addEventListener(type: "abort", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void; + /** + * Remove "abort" event listener, only support "abort" event. + */ + removeEventListener(type: "abort", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void; +} +/** + * An aborter instance implements AbortSignal interface, can abort HTTP requests. + * + * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. + * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation + * cannot or will not ever be cancelled. + * + * @example + * Abort without timeout + * ```ts + * await doAsyncWork(AbortSignal.none); + * ``` + */ +export declare class AbortSignal implements AbortSignalLike { + constructor(); + /* + * Status of whether aborted or not. + * + * @readonly + */ + readonly aborted: boolean; + /* + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static readonly none: AbortSignal; + /** + * onabort event listener. + */ + onabort: ((ev?: Event) => any) | null; + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added + */ + addEventListener(_type: "abort", listener: (this: AbortSignalLike, ev: any) => any): void; + /** + * Remove "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be removed + */ + removeEventListener(_type: "abort", listener: (this: AbortSignalLike, ev: any) => any): void; + /** + * Dispatches a synthetic event to the AbortSignal. + */ + dispatchEvent(_event: Event): boolean; +} +/** + * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. + * Will try to trigger abort event for all linked AbortSignal nodes. + * + * - If there is a timeout, the timer will be cancelled. + * - If aborted is true, nothing will happen. + * + * @internal + */ +export declare function abortSignal(signal: AbortSignal): void; +//# sourceMappingURL=AbortSignal.d.ts.map diff --git a/node_modules/@azure/abort-controller/types/3.1/index.d.ts b/node_modules/@azure/abort-controller/types/3.1/index.d.ts new file mode 100644 index 0000000..1345f47 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/3.1/index.d.ts @@ -0,0 +1,3 @@ +export { AbortController, AbortError } from "./AbortController"; +export { AbortSignal, AbortSignalLike } from "./AbortSignal"; +//# sourceMappingURL=index.d.ts.map diff --git a/node_modules/@azure/abort-controller/types/src/AbortController.d.ts b/node_modules/@azure/abort-controller/types/src/AbortController.d.ts new file mode 100644 index 0000000..c07beb9 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/AbortController.d.ts @@ -0,0 +1,85 @@ +import { AbortSignal, AbortSignalLike } from "./AbortSignal"; +/** + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` + */ +export declare class AbortError extends Error { + constructor(message?: string); +} +/** + * An AbortController provides an AbortSignal and the associated controls to signal + * that an asynchronous operation should be aborted. + * + * @example + * Abort an operation when another event fires + * ```ts + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * ``` + * + * @example + * Share aborter cross multiple operations in 30s + * ```ts + * // Upload the same data to 2 different data centers at the same time, + * // abort another when any of them is finished + * const controller = AbortController.withTimeout(30 * 1000); + * doAsyncWork(controller.signal).then(controller.abort); + * doAsyncWork(controller.signal).then(controller.abort); + *``` + * + * @example + * Cascaded aborting + * ```ts + * // All operations can't take more than 30 seconds + * const aborter = Aborter.timeout(30 * 1000); + * + * // Following 2 operations can't take more than 25 seconds + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * ``` + */ +export declare class AbortController { + private _signal; + /** + * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller. + */ + constructor(parentSignals?: AbortSignalLike[]); + /** + * @param parentSignals - The AbortSignals that will signal aborted on the AbortSignal associated with this controller. + */ + constructor(...parentSignals: AbortSignalLike[]); + /** + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly + */ + get signal(): AbortSignal; + /** + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. + */ + abort(): void; + /** + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. + */ + static timeout(ms: number): AbortSignal; +} +//# sourceMappingURL=AbortController.d.ts.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/AbortController.d.ts.map b/node_modules/@azure/abort-controller/types/src/AbortController.d.ts.map new file mode 100644 index 0000000..cb855af --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/AbortController.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbortController.d.ts","sourceRoot":"","sources":["../../src/AbortController.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAe,MAAM,eAAe,CAAC;AAE1E;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,UAAW,SAAQ,KAAK;gBACvB,OAAO,CAAC,EAAE,MAAM;CAI7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,OAAO,CAAc;IAE7B;;OAEG;gBACS,aAAa,CAAC,EAAE,eAAe,EAAE;IAC7C;;OAEG;gBACS,GAAG,aAAa,EAAE,eAAe,EAAE;IA2B/C;;;;;OAKG;IACH,IAAW,MAAM,IAAI,WAAW,CAE/B;IAED;;;OAGG;IACH,KAAK,IAAI,IAAI;IAIb;;;OAGG;WACW,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW;CAS/C"} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts b/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts new file mode 100644 index 0000000..7d31cb1 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts @@ -0,0 +1,80 @@ +/// +/** + * Allows the request to be aborted upon firing of the "abort" event. + * Compatible with the browser built-in AbortSignal and common polyfills. + */ +export interface AbortSignalLike { + /** + * Indicates if the signal has already been aborted. + */ + readonly aborted: boolean; + /** + * Add new "abort" event listener, only support "abort" event. + */ + addEventListener(type: "abort", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void; + /** + * Remove "abort" event listener, only support "abort" event. + */ + removeEventListener(type: "abort", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void; +} +/** + * An aborter instance implements AbortSignal interface, can abort HTTP requests. + * + * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. + * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation + * cannot or will not ever be cancelled. + * + * @example + * Abort without timeout + * ```ts + * await doAsyncWork(AbortSignal.none); + * ``` + */ +export declare class AbortSignal implements AbortSignalLike { + constructor(); + /** + * Status of whether aborted or not. + * + * @readonly + */ + get aborted(): boolean; + /** + * Creates a new AbortSignal instance that will never be aborted. + * + * @readonly + */ + static get none(): AbortSignal; + /** + * onabort event listener. + */ + onabort: ((ev?: Event) => any) | null; + /** + * Added new "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be added + */ + addEventListener(_type: "abort", listener: (this: AbortSignalLike, ev: any) => any): void; + /** + * Remove "abort" event listener, only support "abort" event. + * + * @param _type - Only support "abort" event + * @param listener - The listener to be removed + */ + removeEventListener(_type: "abort", listener: (this: AbortSignalLike, ev: any) => any): void; + /** + * Dispatches a synthetic event to the AbortSignal. + */ + dispatchEvent(_event: Event): boolean; +} +/** + * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. + * Will try to trigger abort event for all linked AbortSignal nodes. + * + * - If there is a timeout, the timer will be cancelled. + * - If aborted is true, nothing will happen. + * + * @internal + */ +export declare function abortSignal(signal: AbortSignal): void; +//# sourceMappingURL=AbortSignal.d.ts.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts.map b/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts.map new file mode 100644 index 0000000..c82bea3 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/AbortSignal.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbortSignal.d.ts","sourceRoot":"","sources":["../../src/AbortSignal.ts"],"names":[],"mappings":";AAWA;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B;;OAEG;IACH,gBAAgB,CACd,IAAI,EAAE,OAAO,EACb,QAAQ,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,GAAG,KAAK,GAAG,EACjD,OAAO,CAAC,EAAE,GAAG,GACZ,IAAI,CAAC;IACR;;OAEG;IACH,mBAAmB,CACjB,IAAI,EAAE,OAAO,EACb,QAAQ,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,GAAG,KAAK,GAAG,EACjD,OAAO,CAAC,EAAE,GAAG,GACZ,IAAI,CAAC;CACT;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,WAAY,YAAW,eAAe;;IAMjD;;;;OAIG;IACH,IAAW,OAAO,IAAI,OAAO,CAM5B;IAED;;;;OAIG;IACH,WAAkB,IAAI,IAAI,WAAW,CAEpC;IAED;;OAEG;IACI,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,KAAK,GAAG,CAAC,GAAG,IAAI,CAAQ;IAEpD;;;;;OAKG;IACI,gBAAgB,CAErB,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,GAAG,KAAK,GAAG,GAChD,IAAI;IASP;;;;;OAKG;IACI,mBAAmB,CAExB,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,GAAG,KAAK,GAAG,GAChD,IAAI;IAaP;;OAEG;IACH,aAAa,CAAC,MAAM,EAAE,KAAK,GAAG,OAAO;CAKtC;AAED;;;;;;;;GAQG;AAEH,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAoBrD"} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/index.d.ts b/node_modules/@azure/abort-controller/types/src/index.d.ts new file mode 100644 index 0000000..e5afaf4 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/index.d.ts @@ -0,0 +1,3 @@ +export { AbortController, AbortError } from "./AbortController"; +export { AbortSignal, AbortSignalLike } from "./AbortSignal"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/index.d.ts.map b/node_modules/@azure/abort-controller/types/src/index.d.ts.map new file mode 100644 index 0000000..a062939 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/@azure/abort-controller/types/src/tsdoc-metadata.json b/node_modules/@azure/abort-controller/types/src/tsdoc-metadata.json new file mode 100644 index 0000000..7b5aee3 --- /dev/null +++ b/node_modules/@azure/abort-controller/types/src/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.18.11" + } + ] +} diff --git a/node_modules/@azure/core-auth/LICENSE b/node_modules/@azure/core-auth/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/core-auth/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/core-auth/README.md b/node_modules/@azure/core-auth/README.md new file mode 100644 index 0000000..31ccc7f --- /dev/null +++ b/node_modules/@azure/core-auth/README.md @@ -0,0 +1,78 @@ +# Azure Core Authentication client library for JavaScript + +The `@azure/core-auth` package provides core interfaces and helper methods for authenticating with Azure services using Azure Active Directory and other authentication schemes common across the Azure SDK. As a "core" library, it shouldn't need to be added as a dependency to any user code, only other Azure SDK libraries. + +## Getting started + +### Installation + +Install this library using npm as follows + +``` +npm install @azure/core-auth +``` + +## Key Concepts + +The `TokenCredential` interface represents a credential capable of providing an authentication token. The `@azure/identity` package contains various credentials that implement the `TokenCredential` interface. + +The `AzureKeyCredential` is a static key-based credential that supports key rotation via the `update` method. Use this when a single secret value is needed for authentication, e.g. when using a shared access key. + +The `AzureNamedKeyCredential` is a static name/key-based credential that supports name and key rotation via the `update` method. Use this when both a secret value and a label are needed, e.g. when using a shared access key and shared access key name. + +The `AzureSASCredential` is a static signature-based credential that supports updating the signature value via the `update` method. Use this when using a shared access signature. + +## Examples + +### AzureKeyCredential + +```js +const { AzureKeyCredential } = require("@azure/core-auth"); + +const credential = new AzureKeyCredential("secret value"); +// prints: "secret value" +console.log(credential.key); +credential.update("other secret value"); +// prints: "other secret value" +console.log(credential.key); +``` + +### AzureNamedKeyCredential + +```js +const { AzureNamedKeyCredential } = require("@azure/core-auth"); + +const credential = new AzureNamedKeyCredential("ManagedPolicy", "secret value"); +// prints: "ManagedPolicy, secret value" +console.log(`${credential.name}, ${credential.key}`); +credential.update("OtherManagedPolicy", "other secret value"); +// prints: "OtherManagedPolicy, other secret value" +console.log(`${credential.name}, ${credential.key}`); +``` + +### AzureSASCredential + +```js +const { AzureSASCredential } = require("@azure/core-auth"); + +const credential = new AzureSASCredential("signature1"); +// prints: "signature1" +console.log(credential.signature); +credential.update("signature2"); +// prints: "signature2" +console.log(credential.signature); +``` + +## Next steps + +You can build and run the tests locally by executing `rushx test`. Explore the `test` folder to see advanced usage and behavior of the public classes. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Fcore-auth%2FREADME.png) diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js b/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js new file mode 100644 index 0000000..bb9a9fe --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +export class AzureKeyCredential { + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + constructor(key) { + if (!key) { + throw new Error("key must be a non-empty string"); + } + this._key = key; + } + /** + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + update(newKey) { + this._key = newKey; + } +} +//# sourceMappingURL=azureKeyCredential.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js.map b/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js.map new file mode 100644 index 0000000..7b12951 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureKeyCredential.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azureKeyCredential.js","sourceRoot":"","sources":["../../src/azureKeyCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAU7B;;;;;OAKG;IACH,YAAY,GAAW;QACrB,IAAI,CAAC,GAAG,EAAE;YACR,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QAED,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IAClB,CAAC;IAnBD;;OAEG;IACH,IAAW,GAAG;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAgBD;;;;;;;OAOG;IACI,MAAM,CAAC,MAAc;QAC1B,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Represents a credential defined by a static API key.\n */\nexport interface KeyCredential {\n /**\n * The value of the API key represented as a string\n */\n readonly key: string;\n}\n\n/**\n * A static-key-based credential that supports updating\n * the underlying key value.\n */\nexport class AzureKeyCredential implements KeyCredential {\n private _key: string;\n\n /**\n * The value of the key to be used in authentication\n */\n public get key(): string {\n return this._key;\n }\n\n /**\n * Create an instance of an AzureKeyCredential for use\n * with a service client.\n *\n * @param key - The initial value of the key to use in authentication\n */\n constructor(key: string) {\n if (!key) {\n throw new Error(\"key must be a non-empty string\");\n }\n\n this._key = key;\n }\n\n /**\n * Change the value of the key.\n *\n * Updates will take effect upon the next request after\n * updating the key value.\n *\n * @param newKey - The new key value to be used\n */\n public update(newKey: string): void {\n this._key = newKey;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js b/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js new file mode 100644 index 0000000..31f9364 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { isObjectWithProperties } from "./typeguards"; +/** + * A static name/key-based credential that supports updating + * the underlying name and key values. + */ +export class AzureNamedKeyCredential { + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name, key) { + if (!name || !key) { + throw new TypeError("name and key must be non-empty strings"); + } + this._name = name; + this._key = key; + } + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; + } + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName, newKey) { + if (!newName || !newKey) { + throw new TypeError("newName and newKey must be non-empty strings"); + } + this._name = newName; + this._key = newKey; + } +} +/** + * Tests an object to determine whether it implements NamedKeyCredential. + * + * @param credential - The assumed NamedKeyCredential to be tested. + */ +export function isNamedKeyCredential(credential) { + return (isObjectWithProperties(credential, ["name", "key"]) && + typeof credential.key === "string" && + typeof credential.name === "string"); +} +//# sourceMappingURL=azureNamedKeyCredential.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js.map b/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js.map new file mode 100644 index 0000000..0288da5 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureNamedKeyCredential.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azureNamedKeyCredential.js","sourceRoot":"","sources":["../../src/azureNamedKeyCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAgBtD;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAkBlC;;;;;;OAMG;IACH,YAAY,IAAY,EAAE,GAAW;QACnC,IAAI,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE;YACjB,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;SAC/D;QAED,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IAClB,CAAC;IA5BD;;OAEG;IACH,IAAW,GAAG;QACZ,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,IAAW,IAAI;QACb,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAkBD;;;;;;;;OAQG;IACI,MAAM,CAAC,OAAe,EAAE,MAAc;QAC3C,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM,EAAE;YACvB,MAAM,IAAI,SAAS,CAAC,8CAA8C,CAAC,CAAC;SACrE;QAED,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC;IACrB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAmB;IACtD,OAAO,CACL,sBAAsB,CAAC,UAAU,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACnD,OAAO,UAAU,CAAC,GAAG,KAAK,QAAQ;QAClC,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,CACpC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isObjectWithProperties } from \"./typeguards\";\n\n/**\n * Represents a credential defined by a static API name and key.\n */\nexport interface NamedKeyCredential {\n /**\n * The value of the API key represented as a string\n */\n readonly key: string;\n /**\n * The value of the API name represented as a string.\n */\n readonly name: string;\n}\n\n/**\n * A static name/key-based credential that supports updating\n * the underlying name and key values.\n */\nexport class AzureNamedKeyCredential implements NamedKeyCredential {\n private _key: string;\n private _name: string;\n\n /**\n * The value of the key to be used in authentication.\n */\n public get key(): string {\n return this._key;\n }\n\n /**\n * The value of the name to be used in authentication.\n */\n public get name(): string {\n return this._name;\n }\n\n /**\n * Create an instance of an AzureNamedKeyCredential for use\n * with a service client.\n *\n * @param name - The initial value of the name to use in authentication.\n * @param key - The initial value of the key to use in authentication.\n */\n constructor(name: string, key: string) {\n if (!name || !key) {\n throw new TypeError(\"name and key must be non-empty strings\");\n }\n\n this._name = name;\n this._key = key;\n }\n\n /**\n * Change the value of the key.\n *\n * Updates will take effect upon the next request after\n * updating the key value.\n *\n * @param newName - The new name value to be used.\n * @param newKey - The new key value to be used.\n */\n public update(newName: string, newKey: string): void {\n if (!newName || !newKey) {\n throw new TypeError(\"newName and newKey must be non-empty strings\");\n }\n\n this._name = newName;\n this._key = newKey;\n }\n}\n\n/**\n * Tests an object to determine whether it implements NamedKeyCredential.\n *\n * @param credential - The assumed NamedKeyCredential to be tested.\n */\nexport function isNamedKeyCredential(credential: unknown): credential is NamedKeyCredential {\n return (\n isObjectWithProperties(credential, [\"name\", \"key\"]) &&\n typeof credential.key === \"string\" &&\n typeof credential.name === \"string\"\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js b/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js new file mode 100644 index 0000000..d2b3706 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { isObjectWithProperties } from "./typeguards"; +/** + * A static-signature-based credential that supports updating + * the underlying signature value. + */ +export class AzureSASCredential { + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature) { + if (!signature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = signature; + } + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; + } + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature) { + if (!newSignature) { + throw new Error("shared access signature must be a non-empty string"); + } + this._signature = newSignature; + } +} +/** + * Tests an object to determine whether it implements SASCredential. + * + * @param credential - The assumed SASCredential to be tested. + */ +export function isSASCredential(credential) { + return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string"); +} +//# sourceMappingURL=azureSASCredential.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js.map b/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js.map new file mode 100644 index 0000000..faa5d51 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/azureSASCredential.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azureSASCredential.js","sourceRoot":"","sources":["../../src/azureSASCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAYtD;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAU7B;;;;;OAKG;IACH,YAAY,SAAiB;QAC3B,IAAI,CAAC,SAAS,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QAED,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAnBD;;OAEG;IACH,IAAW,SAAS;QAClB,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAgBD;;;;;;;OAOG;IACI,MAAM,CAAC,YAAoB;QAChC,IAAI,CAAC,YAAY,EAAE;YACjB,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QAED,IAAI,CAAC,UAAU,GAAG,YAAY,CAAC;IACjC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,UAAmB;IACjD,OAAO,CACL,sBAAsB,CAAC,UAAU,EAAE,CAAC,WAAW,CAAC,CAAC,IAAI,OAAO,UAAU,CAAC,SAAS,KAAK,QAAQ,CAC9F,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isObjectWithProperties } from \"./typeguards\";\n\n/**\n * Represents a credential defined by a static shared access signature.\n */\nexport interface SASCredential {\n /**\n * The value of the shared access signature represented as a string\n */\n readonly signature: string;\n}\n\n/**\n * A static-signature-based credential that supports updating\n * the underlying signature value.\n */\nexport class AzureSASCredential implements SASCredential {\n private _signature: string;\n\n /**\n * The value of the shared access signature to be used in authentication\n */\n public get signature(): string {\n return this._signature;\n }\n\n /**\n * Create an instance of an AzureSASCredential for use\n * with a service client.\n *\n * @param signature - The initial value of the shared access signature to use in authentication\n */\n constructor(signature: string) {\n if (!signature) {\n throw new Error(\"shared access signature must be a non-empty string\");\n }\n\n this._signature = signature;\n }\n\n /**\n * Change the value of the signature.\n *\n * Updates will take effect upon the next request after\n * updating the signature value.\n *\n * @param newSignature - The new shared access signature value to be used\n */\n public update(newSignature: string): void {\n if (!newSignature) {\n throw new Error(\"shared access signature must be a non-empty string\");\n }\n\n this._signature = newSignature;\n }\n}\n\n/**\n * Tests an object to determine whether it implements SASCredential.\n *\n * @param credential - The assumed SASCredential to be tested.\n */\nexport function isSASCredential(credential: unknown): credential is SASCredential {\n return (\n isObjectWithProperties(credential, [\"signature\"]) && typeof credential.signature === \"string\"\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/index.js b/node_modules/@azure/core-auth/dist-esm/src/index.js new file mode 100644 index 0000000..c950a96 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/index.js @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export { AzureKeyCredential } from "./azureKeyCredential"; +export { AzureNamedKeyCredential, isNamedKeyCredential, } from "./azureNamedKeyCredential"; +export { AzureSASCredential, isSASCredential } from "./azureSASCredential"; +export { isTokenCredential, } from "./tokenCredential"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/index.js.map b/node_modules/@azure/core-auth/dist-esm/src/index.js.map new file mode 100644 index 0000000..8270542 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAiB,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,uBAAuB,EAEvB,oBAAoB,GACrB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAiB,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE1F,OAAO,EAIL,iBAAiB,GAClB,MAAM,mBAAmB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureKeyCredential, KeyCredential } from \"./azureKeyCredential\";\nexport {\n AzureNamedKeyCredential,\n NamedKeyCredential,\n isNamedKeyCredential,\n} from \"./azureNamedKeyCredential\";\nexport { AzureSASCredential, SASCredential, isSASCredential } from \"./azureSASCredential\";\n\nexport {\n TokenCredential,\n GetTokenOptions,\n AccessToken,\n isTokenCredential,\n} from \"./tokenCredential\";\n\nexport { TracingContext } from \"./tracing\";\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js b/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js new file mode 100644 index 0000000..5ca7f68 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Tests an object to determine whether it implements TokenCredential. + * + * @param credential - The assumed TokenCredential to be tested. + */ +export function isTokenCredential(credential) { + // Check for an object with a 'getToken' function and possibly with + // a 'signRequest' function. We do this check to make sure that + // a ServiceClientCredentials implementor (like TokenClientCredentials + // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if + // it doesn't actually implement TokenCredential also. + const castCredential = credential; + return (castCredential && + typeof castCredential.getToken === "function" && + (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); +} +//# sourceMappingURL=tokenCredential.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js.map b/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js.map new file mode 100644 index 0000000..b2a9293 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/tokenCredential.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tokenCredential.js","sourceRoot":"","sources":["../../src/tokenCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AA2ElC;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAmB;IACnD,mEAAmE;IACnE,gEAAgE;IAChE,sEAAsE;IACtE,qEAAqE;IACrE,sDAAsD;IACtD,MAAM,cAAc,GAAG,UAGtB,CAAC;IACF,OAAO,CACL,cAAc;QACd,OAAO,cAAc,CAAC,QAAQ,KAAK,UAAU;QAC7C,CAAC,cAAc,CAAC,WAAW,KAAK,SAAS,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CACjF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { TracingContext } from \"./tracing\";\n\n/**\n * Represents a credential capable of providing an authentication token.\n */\nexport interface TokenCredential {\n /**\n * Gets the token provided by this credential.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise;\n}\n\n/**\n * Defines options for TokenCredential.getToken.\n */\nexport interface GetTokenOptions {\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Options used when creating and sending HTTP requests for this operation.\n */\n requestOptions?: {\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n };\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: {\n /**\n * Tracing Context for the current request.\n */\n tracingContext?: TracingContext;\n };\n\n /**\n * Allows specifying a tenantId. Useful to handle challenges that provide tenant Id hints.\n */\n tenantId?: string;\n\n /**\n * Claim details to perform the Continuous Access Evaluation authentication flow\n */\n claims?: string;\n}\n\n/**\n * Represents an access token with an expiration time.\n */\nexport interface AccessToken {\n /**\n * The access token returned by the authentication service.\n */\n token: string;\n\n /**\n * The access token's expiration timestamp in milliseconds, UNIX epoch time.\n */\n expiresOnTimestamp: number;\n}\n\n/**\n * Tests an object to determine whether it implements TokenCredential.\n *\n * @param credential - The assumed TokenCredential to be tested.\n */\nexport function isTokenCredential(credential: unknown): credential is TokenCredential {\n // Check for an object with a 'getToken' function and possibly with\n // a 'signRequest' function. We do this check to make sure that\n // a ServiceClientCredentials implementor (like TokenClientCredentials\n // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if\n // it doesn't actually implement TokenCredential also.\n const castCredential = credential as {\n getToken: unknown;\n signRequest: unknown;\n };\n return (\n castCredential &&\n typeof castCredential.getToken === \"function\" &&\n (castCredential.signRequest === undefined || castCredential.getToken.length > 0)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/tracing.js b/node_modules/@azure/core-auth/dist-esm/src/tracing.js new file mode 100644 index 0000000..377718d --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/tracing.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export {}; +//# sourceMappingURL=tracing.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/tracing.js.map b/node_modules/@azure/core-auth/dist-esm/src/tracing.js.map new file mode 100644 index 0000000..fe00d40 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/tracing.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracing.js","sourceRoot":"","sources":["../../src/tracing.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// The interfaces in this file should be kept in sync with those\n// found in the `@azure/core-tracing` package.\n\n/**\n * An interface structurally compatible with OpenTelemetry.\n */\nexport interface TracingContext {\n /**\n * Get a value from the context.\n *\n * @param key - key which identifies a context value\n */\n getValue(key: symbol): unknown;\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key - context key for which to set the value\n * @param value - value to set for the given key\n */\n setValue(key: symbol, value: unknown): TracingContext;\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key - context key for which to clear a value\n */\n deleteValue(key: symbol): TracingContext;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/typeguards.js b/node_modules/@azure/core-auth/dist-esm/src/typeguards.js new file mode 100644 index 0000000..551fe89 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/typeguards.js @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + * @internal + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * Note: The properties may be inherited. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + * @internal + */ +export function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * Note: The property may be inherited. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + * @internal + */ +function objectHasProperty(thing, property) { + return typeof thing === "object" && property in thing; +} +//# sourceMappingURL=typeguards.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-auth/dist-esm/src/typeguards.js.map b/node_modules/@azure/core-auth/dist-esm/src/typeguards.js.map new file mode 100644 index 0000000..4d14430 --- /dev/null +++ b/node_modules/@azure/core-auth/dist-esm/src/typeguards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typeguards.js","sourceRoot":"","sources":["../../src/typeguards.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;GAIG;AACH,SAAS,SAAS,CAAI,KAA2B;IAC/C,OAAO,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,IAAI,CAAC;AACxD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAY,EACZ,UAA0B;IAE1B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE;QACjC,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE;YACvC,OAAO,KAAK,CAAC;SACd;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,KAAY,EACZ,QAAsB;IAEtB,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAK,KAAiC,CAAC;AACrF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Helper TypeGuard that checks if something is defined or not.\n * @param thing - Anything\n * @internal\n */\nfunction isDefined(thing: T | undefined | null): thing is T {\n return typeof thing !== \"undefined\" && thing !== null;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified properties.\n * Note: The properties may be inherited.\n * @param thing - Anything.\n * @param properties - The name of the properties that should appear in the object.\n * @internal\n */\nexport function isObjectWithProperties(\n thing: Thing,\n properties: PropertyName[]\n): thing is Thing & Record {\n if (!isDefined(thing) || typeof thing !== \"object\") {\n return false;\n }\n\n for (const property of properties) {\n if (!objectHasProperty(thing, property)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified property.\n * Note: The property may be inherited.\n * @param thing - Any object.\n * @param property - The name of the property that should appear in the object.\n * @internal\n */\nfunction objectHasProperty(\n thing: Thing,\n property: PropertyName\n): thing is Thing & Record {\n return typeof thing === \"object\" && property in (thing as Record);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-auth/package.json b/node_modules/@azure/core-auth/package.json new file mode 100644 index 0000000..55f9095 --- /dev/null +++ b/node_modules/@azure/core-auth/package.json @@ -0,0 +1,87 @@ +{ + "name": "@azure/core-auth", + "version": "1.4.0", + "description": "Provides low-level interfaces and helper methods for authentication in Azure SDK", + "sdk-type": "client", + "main": "dist/index.js", + "module": "dist-esm/src/index.js", + "types": "./types/latest/core-auth.d.ts", + "typesVersions": { + "<3.6": { + "types/latest/*": [ + "types/3.1/*" + ] + } + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build:types": "downlevel-dts types/latest/ types/3.1/", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local && npm run build:types", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "echo skipped", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/latest/core-auth.d.ts", + "types/3.1", + "README.md", + "LICENSE" + ], + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "authentication", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "engines": { + "node": ">=12.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-auth/README.md", + "sideEffects": false, + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "devDependencies": { + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@microsoft/api-extractor": "7.18.11", + "@types/chai": "^4.1.6", + "@types/mocha": "^7.0.2", + "@types/node": "^12.0.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "downlevel-dts": "^0.8.0", + "eslint": "^8.0.0", + "inherits": "^2.0.3", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "prettier": "^2.5.1", + "rimraf": "^3.0.0", + "typescript": "~4.6.0", + "util": "^0.12.1" + } +} diff --git a/node_modules/@azure/core-auth/types/3.1/core-auth.d.ts b/node_modules/@azure/core-auth/types/3.1/core-auth.d.ts new file mode 100644 index 0000000..cbdd1b4 --- /dev/null +++ b/node_modules/@azure/core-auth/types/3.1/core-auth.d.ts @@ -0,0 +1,229 @@ +import { AbortSignalLike } from '@azure/abort-controller'; +/** + * Represents an access token with an expiration time. + */ +export declare interface AccessToken { + /** + * The access token returned by the authentication service. + */ + token: string; + /** + * The access token's expiration timestamp in milliseconds, UNIX epoch time. + */ + expiresOnTimestamp: number; +} +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +export declare class AzureKeyCredential implements KeyCredential { + private _key; + /* + * The value of the key to be used in authentication + */ + readonly key: string; + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + constructor(key: string); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + update(newKey: string): void; +} +/** + * A static name/key-based credential that supports updating + * the underlying name and key values. + */ +export declare class AzureNamedKeyCredential implements NamedKeyCredential { + private _key; + private _name; + /* + * The value of the key to be used in authentication. + */ + readonly key: string; + /* + * The value of the name to be used in authentication. + */ + readonly name: string; + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name: string, key: string); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName: string, newKey: string): void; +} +/** + * A static-signature-based credential that supports updating + * the underlying signature value. + */ +export declare class AzureSASCredential implements SASCredential { + private _signature; + /* + * The value of the shared access signature to be used in authentication + */ + readonly signature: string; + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature: string); + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature: string): void; +} +/** + * Defines options for TokenCredential.getToken. + */ +export declare interface GetTokenOptions { + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * Options used when creating and sending HTTP requests for this operation. + */ + requestOptions?: { + /** + * The number of milliseconds a request can take before automatically being terminated. + */ + timeout?: number; + }; + /** + * Options used when tracing is enabled. + */ + tracingOptions?: { + /** + * Tracing Context for the current request. + */ + tracingContext?: TracingContext; + }; + /** + * Allows specifying a tenantId. Useful to handle challenges that provide tenant Id hints. + */ + tenantId?: string; + /** + * Claim details to perform the Continuous Access Evaluation authentication flow + */ + claims?: string; +} +/** + * Tests an object to determine whether it implements NamedKeyCredential. + * + * @param credential - The assumed NamedKeyCredential to be tested. + */ +export declare function isNamedKeyCredential(credential: unknown): credential is NamedKeyCredential; +/** + * Tests an object to determine whether it implements SASCredential. + * + * @param credential - The assumed SASCredential to be tested. + */ +export declare function isSASCredential(credential: unknown): credential is SASCredential; +/** + * Tests an object to determine whether it implements TokenCredential. + * + * @param credential - The assumed TokenCredential to be tested. + */ +export declare function isTokenCredential(credential: unknown): credential is TokenCredential; +/** + * Represents a credential defined by a static API key. + */ +export declare interface KeyCredential { + /** + * The value of the API key represented as a string + */ + readonly key: string; +} +/** + * Represents a credential defined by a static API name and key. + */ +export declare interface NamedKeyCredential { + /** + * The value of the API key represented as a string + */ + readonly key: string; + /** + * The value of the API name represented as a string. + */ + readonly name: string; +} +/** + * Represents a credential defined by a static shared access signature. + */ +export declare interface SASCredential { + /** + * The value of the shared access signature represented as a string + */ + readonly signature: string; +} +/** + * Represents a credential capable of providing an authentication token. + */ +export declare interface TokenCredential { + /** + * Gets the token provided by this credential. + * + * This method is called automatically by Azure SDK client libraries. You may call this method + * directly, but you must also handle token caching and token refreshing. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + getToken(scopes: string | string[], options?: GetTokenOptions): Promise; +} +/** + * An interface structurally compatible with OpenTelemetry. + */ +export declare interface TracingContext { + /** + * Get a value from the context. + * + * @param key - key which identifies a context value + */ + getValue(key: symbol): unknown; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key - context key for which to set the value + * @param value - value to set for the given key + */ + setValue(key: symbol, value: unknown): TracingContext; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key - context key for which to clear a value + */ + deleteValue(key: symbol): TracingContext; +} +export {}; diff --git a/node_modules/@azure/core-auth/types/latest/core-auth.d.ts b/node_modules/@azure/core-auth/types/latest/core-auth.d.ts new file mode 100644 index 0000000..d83804a --- /dev/null +++ b/node_modules/@azure/core-auth/types/latest/core-auth.d.ts @@ -0,0 +1,243 @@ +import { AbortSignalLike } from '@azure/abort-controller'; + +/** + * Represents an access token with an expiration time. + */ +export declare interface AccessToken { + /** + * The access token returned by the authentication service. + */ + token: string; + /** + * The access token's expiration timestamp in milliseconds, UNIX epoch time. + */ + expiresOnTimestamp: number; +} + +/** + * A static-key-based credential that supports updating + * the underlying key value. + */ +export declare class AzureKeyCredential implements KeyCredential { + private _key; + /** + * The value of the key to be used in authentication + */ + get key(): string; + /** + * Create an instance of an AzureKeyCredential for use + * with a service client. + * + * @param key - The initial value of the key to use in authentication + */ + constructor(key: string); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newKey - The new key value to be used + */ + update(newKey: string): void; +} + +/** + * A static name/key-based credential that supports updating + * the underlying name and key values. + */ +export declare class AzureNamedKeyCredential implements NamedKeyCredential { + private _key; + private _name; + /** + * The value of the key to be used in authentication. + */ + get key(): string; + /** + * The value of the name to be used in authentication. + */ + get name(): string; + /** + * Create an instance of an AzureNamedKeyCredential for use + * with a service client. + * + * @param name - The initial value of the name to use in authentication. + * @param key - The initial value of the key to use in authentication. + */ + constructor(name: string, key: string); + /** + * Change the value of the key. + * + * Updates will take effect upon the next request after + * updating the key value. + * + * @param newName - The new name value to be used. + * @param newKey - The new key value to be used. + */ + update(newName: string, newKey: string): void; +} + +/** + * A static-signature-based credential that supports updating + * the underlying signature value. + */ +export declare class AzureSASCredential implements SASCredential { + private _signature; + /** + * The value of the shared access signature to be used in authentication + */ + get signature(): string; + /** + * Create an instance of an AzureSASCredential for use + * with a service client. + * + * @param signature - The initial value of the shared access signature to use in authentication + */ + constructor(signature: string); + /** + * Change the value of the signature. + * + * Updates will take effect upon the next request after + * updating the signature value. + * + * @param newSignature - The new shared access signature value to be used + */ + update(newSignature: string): void; +} + +/** + * Defines options for TokenCredential.getToken. + */ +export declare interface GetTokenOptions { + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * Options used when creating and sending HTTP requests for this operation. + */ + requestOptions?: { + /** + * The number of milliseconds a request can take before automatically being terminated. + */ + timeout?: number; + }; + /** + * Options used when tracing is enabled. + */ + tracingOptions?: { + /** + * Tracing Context for the current request. + */ + tracingContext?: TracingContext; + }; + /** + * Allows specifying a tenantId. Useful to handle challenges that provide tenant Id hints. + */ + tenantId?: string; + /** + * Claim details to perform the Continuous Access Evaluation authentication flow + */ + claims?: string; +} + +/** + * Tests an object to determine whether it implements NamedKeyCredential. + * + * @param credential - The assumed NamedKeyCredential to be tested. + */ +export declare function isNamedKeyCredential(credential: unknown): credential is NamedKeyCredential; + +/** + * Tests an object to determine whether it implements SASCredential. + * + * @param credential - The assumed SASCredential to be tested. + */ +export declare function isSASCredential(credential: unknown): credential is SASCredential; + +/** + * Tests an object to determine whether it implements TokenCredential. + * + * @param credential - The assumed TokenCredential to be tested. + */ +export declare function isTokenCredential(credential: unknown): credential is TokenCredential; + +/** + * Represents a credential defined by a static API key. + */ +export declare interface KeyCredential { + /** + * The value of the API key represented as a string + */ + readonly key: string; +} + +/** + * Represents a credential defined by a static API name and key. + */ +export declare interface NamedKeyCredential { + /** + * The value of the API key represented as a string + */ + readonly key: string; + /** + * The value of the API name represented as a string. + */ + readonly name: string; +} + +/** + * Represents a credential defined by a static shared access signature. + */ +export declare interface SASCredential { + /** + * The value of the shared access signature represented as a string + */ + readonly signature: string; +} + +/** + * Represents a credential capable of providing an authentication token. + */ +export declare interface TokenCredential { + /** + * Gets the token provided by this credential. + * + * This method is called automatically by Azure SDK client libraries. You may call this method + * directly, but you must also handle token caching and token refreshing. + * + * @param scopes - The list of scopes for which the token will have access. + * @param options - The options used to configure any requests this + * TokenCredential implementation might make. + */ + getToken(scopes: string | string[], options?: GetTokenOptions): Promise; +} + +/** + * An interface structurally compatible with OpenTelemetry. + */ +export declare interface TracingContext { + /** + * Get a value from the context. + * + * @param key - key which identifies a context value + */ + getValue(key: symbol): unknown; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key - context key for which to set the value + * @param value - value to set for the given key + */ + setValue(key: symbol, value: unknown): TracingContext; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key - context key for which to clear a value + */ + deleteValue(key: symbol): TracingContext; +} + +export { } diff --git a/node_modules/@azure/core-rest-pipeline/LICENSE b/node_modules/@azure/core-rest-pipeline/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/core-rest-pipeline/README.md b/node_modules/@azure/core-rest-pipeline/README.md new file mode 100644 index 0000000..008f089 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/README.md @@ -0,0 +1,159 @@ +# Azure Core HTTP client library for JavaScript + +This is the core HTTP pipeline for Azure SDK JavaScript libraries which work in the browser and Node.js. This library is primarily intended to be used in code generated by [AutoRest](https://github.com/Azure/Autorest) and [`autorest.typescript`](https://github.com/Azure/autorest.typescript). + +## Getting started + +### Requirements + +### Currently supported environments + +- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) +- Latest versions of Safari, Chrome, Edge, and Firefox. + +See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. + +### Installation + +This package is primarily used in generated code and not meant to be consumed directly by end users. + +## Key concepts + +### PipelineRequest + +A `PipelineRequest` describes all the information necessary to make a request to an HTTP REST endpoint. + +### PipelineResponse + +A `PipelineResponse` describes the HTTP response (body, headers, and status code) from a REST endpoint that was returned after making an HTTP request. + +### SendRequest + +A `SendRequest` method is a method that given a `PipelineRequest` can asynchronously return a `PipelineResponse`. + +```ts +export type SendRequest = (request: PipelineRequest) => Promise; +``` + +### HttpClient + +An `HttpClient` is any object that satisfies the following interface to implement a `SendRequest` method: + +```ts +export interface HttpClient { + /** + * The method that makes the request and returns a response. + */ + sendRequest: SendRequest; +} +``` + +`HttpClient`s are expected to actually make the HTTP request to a server endpoint, using some platform-specific mechanism for doing so. + +### Pipeline Policies + +A `PipelinePolicy` is a simple object that implements the following interface: + +```ts +export interface PipelinePolicy { + /** + * The policy name. Must be a unique string in the pipeline. + */ + name: string; + /** + * The main method to implement that manipulates a request/response. + * @param request The request being performed. + * @param next The next policy in the pipeline. Must be called to continue the pipeline. + */ + sendRequest(request: PipelineRequest, next: SendRequest): Promise; +} +``` + +It is similar in shape to `HttpClient`, but includes a policy name as well as a slightly modified `SendRequest` signature that allows it to conditionally call the next policy in the pipeline. + +One can view the role of policies as that of `middleware`, a concept that is familiar to NodeJS developers who have worked with frameworks such as [Express](https://expressjs.com/). + +The `sendRequest` implementation can both transform the outgoing request as well as the incoming response: + +```ts +const customPolicy = { + name: "My wonderful policy", + async sendRequest(request: PipelineRequest, next: SendRequest): Promise { + // Change the outgoing request by adding a new header + request.headers.set("X-Cool-Header", 42); + const result = await next(request); + if (response.status === 403) { + // Do something special if this policy sees Forbidden + } + return result; + } +}; +``` + +Most policies only concern themselves with either the request or the response, but there are some exceptions such as the [LogPolicy](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-rest-pipeline/src/policies/logPolicy.ts) which logs information from each. + +### Pipelines + +A `Pipeline` is an object that manages a set of `PipelinePolicy` objects. Its main function is to ensure that policies are executed in a consistent and predictable order. + +You can think of policies being applied like a stack (first-in/last-out.) The first `PipelinePolicy` is able to modify the `PipelineRequest` before any other policies, and it is also the last to modify the `PipelineResponse`, making it the closest to the caller. The final policy is the last able to modify the outgoing request, and the first to handle the response, making it the closest to the network. + +A `Pipeline` satisfies the following interface: + +```ts +export interface Pipeline { + addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void; + removePolicy(options: { name?: string; phase?: PipelinePhase }): PipelinePolicy[]; + sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise; + getOrderedPolicies(): PipelinePolicy[]; + clone(): Pipeline; +} +``` + +As you can see it allows for policies to be added or removed and it is loosely coupled with `HttpClient` to perform the real request to the server endpoint. + +One important concept for `Pipeline`s is that they group policies into ordered phases: + +1. Serialize Phase +2. Policies not in a phase +3. Deserialize Phase +4. Retry Phase + +Phases occur in the above order, with serialization policies being applied first and retry policies being applied last. Most custom policies fall into the second bucket and are not given a phase name. + +When adding a policy to the pipeline you can specify not only what phase a policy is in, but also if it has any dependencies: + +```ts +export interface AddPolicyOptions { + beforePolicies?: string[]; + afterPolicies?: string[]; + afterPhase?: PipelinePhase; + phase?: PipelinePhase; +} +``` + +`beforePolicies` are policies that the new policy must execute before and `afterPolicies` are policies that the new policy must happen after. Similarly, `afterPhase` means the policy must only execute after the specified phase has occurred. + +This syntax allows custom policy authors to express any necessary relationships between their own policies and the built-in policies provided by `@azure/core-rest-pipeline` when creating a pipeline using `createPipelineFromOptions`. + +Implementers are also able to remove policies by name or phase, in the case that they wish to modify an existing `Pipeline` without having to create a new one using `createEmptyPipeline`. The `clone` method is particularly useful when recreating a `Pipeline` without modifying the original. + +After all other constraints have been satisfied, policies are applied in the order which they were added. + +## Examples + +Examples can be found in the `samples` folder. + +## Next steps + +You can build and run the tests locally by executing `rushx test`. Explore the `test` folder to see advanced usage and behavior of the public classes. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Fcore-rest-pipeline%2FREADME.png) diff --git a/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims-3_1.d.ts b/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims-3_1.d.ts new file mode 100644 index 0000000..abb8bf3 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims-3_1.d.ts @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +declare global { + interface FormData {} + interface Blob {} + interface File {} + interface ReadableStream {} + interface TransformStream {} +} + +export * from "./types/3.1/core-rest-pipeline"; diff --git a/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims.d.ts b/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims.d.ts new file mode 100644 index 0000000..718d5fd --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/core-rest-pipeline.shims.d.ts @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +declare global { + interface FormData {} + interface Blob {} + interface File {} + interface ReadableStream {} + interface TransformStream {} +} + +export * from "./types/latest/core-rest-pipeline"; diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js new file mode 100644 index 0000000..ff7dee1 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Defines the default token refresh buffer duration. + */ +export const DefaultTokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes +/** + * Provides an AccessTokenCache implementation which clears + * the cached AccessToken's after the expiresOnTimestamp has + * passed. + * @internal + */ +export class ExpiringAccessTokenCache { + /** + * Constructs an instance of ExpiringAccessTokenCache with + * an optional expiration buffer time. + */ + constructor(tokenRefreshBufferMs = DefaultTokenRefreshBufferMs) { + this.tokenRefreshBufferMs = tokenRefreshBufferMs; + } + setCachedToken(accessToken) { + this.cachedToken = accessToken; + } + getCachedToken() { + if (this.cachedToken && + Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { + this.cachedToken = undefined; + } + return this.cachedToken; + } +} +//# sourceMappingURL=accessTokenCache.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js.map new file mode 100644 index 0000000..f69e299 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/accessTokenCache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"accessTokenCache.js","sourceRoot":"","sources":["../../src/accessTokenCache.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC;;GAEG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAqBtE;;;;;GAKG;AACH,MAAM,OAAO,wBAAwB;IAInC;;;OAGG;IACH,YAAY,uBAA+B,2BAA2B;QACpE,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;IACnD,CAAC;IAED,cAAc,CAAC,WAAoC;QACjD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,cAAc;QACZ,IACE,IAAI,CAAC,WAAW;YAChB,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,oBAAoB,IAAI,IAAI,CAAC,WAAW,CAAC,kBAAkB,EAC7E;YACA,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;SAC9B;QAED,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken } from \"@azure/core-auth\";\n\n/**\n * Defines the default token refresh buffer duration.\n */\nexport const DefaultTokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes\n\n/**\n * Provides a cache for an AccessToken that was that\n * was returned from a TokenCredential.\n */\nexport interface AccessTokenCache {\n /**\n * Sets the cached token.\n *\n * @param accessToken - The AccessToken to be cached or null to\n * clear the cached token.\n */\n setCachedToken(accessToken: AccessToken | undefined): void;\n\n /**\n * Returns the cached AccessToken or undefined if nothing is cached.\n */\n getCachedToken(): AccessToken | undefined;\n}\n\n/**\n * Provides an AccessTokenCache implementation which clears\n * the cached AccessToken's after the expiresOnTimestamp has\n * passed.\n * @internal\n */\nexport class ExpiringAccessTokenCache implements AccessTokenCache {\n private tokenRefreshBufferMs: number;\n private cachedToken?: AccessToken;\n\n /**\n * Constructs an instance of ExpiringAccessTokenCache with\n * an optional expiration buffer time.\n */\n constructor(tokenRefreshBufferMs: number = DefaultTokenRefreshBufferMs) {\n this.tokenRefreshBufferMs = tokenRefreshBufferMs;\n }\n\n setCachedToken(accessToken: AccessToken | undefined): void {\n this.cachedToken = accessToken;\n }\n\n getCachedToken(): AccessToken | undefined {\n if (\n this.cachedToken &&\n Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp\n ) {\n this.cachedToken = undefined;\n }\n\n return this.cachedToken;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js new file mode 100644 index 0000000..94919b5 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export const SDK_VERSION = "1.10.2"; +export const DEFAULT_RETRY_POLICY_COUNT = 3; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js.map new file mode 100644 index 0000000..998828e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,CAAC,MAAM,WAAW,GAAW,QAAQ,CAAC;AAE5C,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const SDK_VERSION: string = \"1.10.2\";\n\nexport const DEFAULT_RETRY_POLICY_COUNT = 3;\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js new file mode 100644 index 0000000..3b198b9 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { logPolicy } from "./policies/logPolicy"; +import { createEmptyPipeline } from "./pipeline"; +import { redirectPolicy } from "./policies/redirectPolicy"; +import { userAgentPolicy } from "./policies/userAgentPolicy"; +import { decompressResponsePolicy } from "./policies/decompressResponsePolicy"; +import { defaultRetryPolicy } from "./policies/defaultRetryPolicy"; +import { formDataPolicy } from "./policies/formDataPolicy"; +import { isNode } from "@azure/core-util"; +import { proxyPolicy } from "./policies/proxyPolicy"; +import { setClientRequestIdPolicy } from "./policies/setClientRequestIdPolicy"; +import { tlsPolicy } from "./policies/tlsPolicy"; +import { tracingPolicy } from "./policies/tracingPolicy"; +/** + * Create a new pipeline with a default set of customizable policies. + * @param options - Options to configure a custom pipeline. + */ +export function createPipelineFromOptions(options) { + const pipeline = createEmptyPipeline(); + if (isNode) { + if (options.tlsOptions) { + pipeline.addPolicy(tlsPolicy(options.tlsOptions)); + } + pipeline.addPolicy(proxyPolicy(options.proxyOptions)); + pipeline.addPolicy(decompressResponsePolicy()); + } + pipeline.addPolicy(formDataPolicy()); + pipeline.addPolicy(userAgentPolicy(options.userAgentOptions)); + pipeline.addPolicy(setClientRequestIdPolicy()); + pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" }); + pipeline.addPolicy(tracingPolicy(options.userAgentOptions), { afterPhase: "Retry" }); + if (isNode) { + // Both XHR and Fetch expect to handle redirects automatically, + // so only include this policy when we're in Node. + pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline; +} +//# sourceMappingURL=createPipelineFromOptions.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js.map new file mode 100644 index 0000000..629e72e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/createPipelineFromOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createPipelineFromOptions.js","sourceRoot":"","sources":["../../src/createPipelineFromOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAoB,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAY,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE3D,OAAO,EAAyB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAA0B,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAGrF,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AA0CzD;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAgC;IACxE,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;IAEvC,IAAI,MAAM,EAAE;QACV,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;SACnD;QACD,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC;QACtD,QAAQ,CAAC,SAAS,CAAC,wBAAwB,EAAE,CAAC,CAAC;KAChD;IAED,QAAQ,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC,CAAC;IACrC,QAAQ,CAAC,SAAS,CAAC,eAAe,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAC9D,QAAQ,CAAC,SAAS,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC/C,QAAQ,CAAC,SAAS,CAAC,kBAAkB,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACjF,QAAQ,CAAC,SAAS,CAAC,aAAa,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IACrF,IAAI,MAAM,EAAE;QACV,+DAA+D;QAC/D,kDAAkD;QAClD,QAAQ,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;KACtF;IACD,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IAE9E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LogPolicyOptions, logPolicy } from \"./policies/logPolicy\";\nimport { Pipeline, createEmptyPipeline } from \"./pipeline\";\nimport { PipelineRetryOptions, TlsSettings } from \"./interfaces\";\nimport { RedirectPolicyOptions, redirectPolicy } from \"./policies/redirectPolicy\";\nimport { UserAgentPolicyOptions, userAgentPolicy } from \"./policies/userAgentPolicy\";\n\nimport { ProxySettings } from \".\";\nimport { decompressResponsePolicy } from \"./policies/decompressResponsePolicy\";\nimport { defaultRetryPolicy } from \"./policies/defaultRetryPolicy\";\nimport { formDataPolicy } from \"./policies/formDataPolicy\";\nimport { isNode } from \"@azure/core-util\";\nimport { proxyPolicy } from \"./policies/proxyPolicy\";\nimport { setClientRequestIdPolicy } from \"./policies/setClientRequestIdPolicy\";\nimport { tlsPolicy } from \"./policies/tlsPolicy\";\nimport { tracingPolicy } from \"./policies/tracingPolicy\";\n\n/**\n * Defines options that are used to configure the HTTP pipeline for\n * an SDK client.\n */\nexport interface PipelineOptions {\n /**\n * Options that control how to retry failed requests.\n */\n retryOptions?: PipelineRetryOptions;\n\n /**\n * Options to configure a proxy for outgoing requests.\n */\n proxyOptions?: ProxySettings;\n\n /** Options for configuring TLS authentication */\n tlsOptions?: TlsSettings;\n\n /**\n * Options for how redirect responses are handled.\n */\n redirectOptions?: RedirectPolicyOptions;\n\n /**\n * Options for adding user agent details to outgoing requests.\n */\n userAgentOptions?: UserAgentPolicyOptions;\n}\n\n/**\n * Defines options that are used to configure internal options of\n * the HTTP pipeline for an SDK client.\n */\nexport interface InternalPipelineOptions extends PipelineOptions {\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n}\n\n/**\n * Create a new pipeline with a default set of customizable policies.\n * @param options - Options to configure a custom pipeline.\n */\nexport function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline {\n const pipeline = createEmptyPipeline();\n\n if (isNode) {\n if (options.tlsOptions) {\n pipeline.addPolicy(tlsPolicy(options.tlsOptions));\n }\n pipeline.addPolicy(proxyPolicy(options.proxyOptions));\n pipeline.addPolicy(decompressResponsePolicy());\n }\n\n pipeline.addPolicy(formDataPolicy());\n pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));\n pipeline.addPolicy(setClientRequestIdPolicy());\n pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: \"Retry\" });\n pipeline.addPolicy(tracingPolicy(options.userAgentOptions), { afterPhase: \"Retry\" });\n if (isNode) {\n // Both XHR and Fetch expect to handle redirects automatically,\n // so only include this policy when we're in Node.\n pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: \"Retry\" });\n }\n pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: \"Sign\" });\n\n return pipeline;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js new file mode 100644 index 0000000..a0658ab --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createFetchHttpClient } from "./fetchHttpClient"; +/** + * Create the correct HttpClient for the current environment. + */ +export function createDefaultHttpClient() { + return createFetchHttpClient(); +} +//# sourceMappingURL=defaultHttpClient.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js.map new file mode 100644 index 0000000..0bec9d4 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaultHttpClient.browser.js","sourceRoot":"","sources":["../../src/defaultHttpClient.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAE1D;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,qBAAqB,EAAE,CAAC;AACjC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient } from \"./interfaces\";\nimport { createFetchHttpClient } from \"./fetchHttpClient\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n return createFetchHttpClient();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js new file mode 100644 index 0000000..7caa5e8 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createNodeHttpClient } from "./nodeHttpClient"; +/** + * Create the correct HttpClient for the current environment. + */ +export function createDefaultHttpClient() { + return createNodeHttpClient(); +} +//# sourceMappingURL=defaultHttpClient.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js.map new file mode 100644 index 0000000..252903b --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaultHttpClient.js","sourceRoot":"","sources":["../../src/defaultHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,oBAAoB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient } from \"./interfaces\";\nimport { createNodeHttpClient } from \"./nodeHttpClient\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n return createNodeHttpClient();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js new file mode 100644 index 0000000..56c22ea --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createXhrHttpClient } from "./xhrHttpClient"; +/** + * Create the correct HttpClient for the current environment. + */ +export function createDefaultHttpClient() { + return createXhrHttpClient(); +} +//# sourceMappingURL=defaultHttpClient.native.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js.map new file mode 100644 index 0000000..97f6a73 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/defaultHttpClient.native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaultHttpClient.native.js","sourceRoot":"","sources":["../../src/defaultHttpClient.native.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,mBAAmB,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient } from \"./interfaces\";\nimport { createXhrHttpClient } from \"./xhrHttpClient\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n return createXhrHttpClient();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js new file mode 100644 index 0000000..2384c69 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { AbortError } from "@azure/abort-controller"; +import { RestError } from "./restError"; +import { createHttpHeaders } from "./httpHeaders"; +/** + * Checks if the body is a NodeReadable stream which is not supported in Browsers + */ +function isNodeReadableStream(body) { + return body && typeof body.pipe === "function"; +} +/** + * Checks if the body is a ReadableStream supported by browsers + */ +function isReadableStream(body) { + return Boolean(body && + typeof body.getReader === "function" && + typeof body.tee === "function"); +} +/** + * Checks if the body is a Blob or Blob-like + */ +function isBlob(body) { + // File objects count as a type of Blob, so we want to use instanceof explicitly + return (typeof Blob === "function" || typeof Blob === "object") && body instanceof Blob; +} +/** + * A HttpClient implementation that uses window.fetch to send HTTP requests. + * @internal + */ +class FetchHttpClient { + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + if (request.proxySettings) { + throw new Error("HTTP proxy is not supported in browser environment"); + } + try { + return await makeRequest(request); + } + catch (e) { + throw getError(e, request); + } + } +} +/** + * Sends a request + */ +async function makeRequest(request) { + const { abortController, abortControllerCleanup } = setupAbortSignal(request); + try { + const headers = buildFetchHeaders(request.headers); + const requestBody = buildRequestBody(request); + /** + * Developers of the future: + * Do not set redirect: "manual" as part + * of request options. + * It will not work as you expect. + */ + const response = await fetch(request.url, { + body: requestBody, + method: request.method, + headers: headers, + signal: abortController.signal, + credentials: request.withCredentials ? "include" : "same-origin", + cache: "no-store", + }); + // If we're uploading a blob, we need to fire the progress event manually + if (isBlob(request.body) && request.onUploadProgress) { + request.onUploadProgress({ loadedBytes: request.body.size }); + } + return buildPipelineResponse(response, request); + } + finally { + if (abortControllerCleanup) { + abortControllerCleanup(); + } + } +} +/** + * Creates a pipeline response from a Fetch response; + */ +async function buildPipelineResponse(httpResponse, request) { + var _a, _b; + const headers = buildPipelineHeaders(httpResponse); + const response = { + request, + headers, + status: httpResponse.status, + }; + const bodyStream = isReadableStream(httpResponse.body) + ? buildBodyStream(httpResponse.body, request.onDownloadProgress) + : httpResponse.body; + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(Number.POSITIVE_INFINITY)) || + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(response.status))) { + if (request.enableBrowserStreams) { + response.browserStreamBody = bodyStream !== null && bodyStream !== void 0 ? bodyStream : undefined; + } + else { + const responseStream = new Response(bodyStream); + response.blobBody = responseStream.blob(); + } + } + else { + const responseStream = new Response(bodyStream); + response.bodyAsText = await responseStream.text(); + } + return response; +} +function setupAbortSignal(request) { + const abortController = new AbortController(); + // Cleanup function + let abortControllerCleanup; + /** + * Attach an abort listener to the request + */ + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + abortControllerCleanup = () => { + var _a; + if (abortListener) { + (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + } + }; + } + // If a timeout was passed, call the abort signal once the time elapses + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + return { abortController, abortControllerCleanup }; +} +/** + * Gets the specific error + */ +function getError(e, request) { + var _a; + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + return e; + } + else { + return new RestError(`Error sending request: ${e.message}`, { + code: (_a = e === null || e === void 0 ? void 0 : e.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, + request, + }); + } +} +/** + * Converts PipelineRequest headers to Fetch headers + */ +function buildFetchHeaders(pipelineHeaders) { + const headers = new Headers(); + for (const [name, value] of pipelineHeaders) { + headers.append(name, value); + } + return headers; +} +function buildPipelineHeaders(httpResponse) { + const responseHeaders = createHttpHeaders(); + for (const [name, value] of httpResponse.headers) { + responseHeaders.set(name, value); + } + return responseHeaders; +} +function buildRequestBody(request) { + const body = typeof request.body === "function" ? request.body() : request.body; + if (isNodeReadableStream(body)) { + throw new Error("Node streams are not supported in browser environment."); + } + return isReadableStream(body) ? buildBodyStream(body, request.onUploadProgress) : body; +} +/** + * Reads the request/response original stream and stream it through a new + * ReadableStream, this is done to be able to report progress in a way that + * all modern browsers support. TransformStreams would be an alternative, + * however they are not yet supported by all browsers i.e Firefox + */ +function buildBodyStream(readableStream, onProgress) { + let loadedBytes = 0; + // If the current browser supports pipeThrough we use a TransformStream + // to report progress + if (isTransformStreamSupported(readableStream)) { + return readableStream.pipeThrough(new TransformStream({ + transform(chunk, controller) { + if (chunk === null) { + controller.terminate(); + return; + } + controller.enqueue(chunk); + loadedBytes += chunk.length; + if (onProgress) { + onProgress({ loadedBytes }); + } + }, + })); + } + else { + // If we can't use transform streams, wrap the original stream in a new readable stream + // and use pull to enqueue each chunk and report progress. + const reader = readableStream.getReader(); + return new ReadableStream({ + async pull(controller) { + var _a; + const { done, value } = await reader.read(); + // When no more data needs to be consumed, break the reading + if (done || !value) { + // Close the stream + controller.close(); + reader.releaseLock(); + return; + } + loadedBytes += (_a = value === null || value === void 0 ? void 0 : value.length) !== null && _a !== void 0 ? _a : 0; + // Enqueue the next data chunk into our target stream + controller.enqueue(value); + if (onProgress) { + onProgress({ loadedBytes }); + } + }, + }); + } +} +/** + * Create a new HttpClient instance for the browser environment. + * @internal + */ +export function createFetchHttpClient() { + return new FetchHttpClient(); +} +function isTransformStreamSupported(readableStream) { + return readableStream.pipeThrough !== undefined && self.TransformStream !== undefined; +} +//# sourceMappingURL=fetchHttpClient.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js.map new file mode 100644 index 0000000..9531e8c --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/fetchHttpClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetchHttpClient.js","sourceRoot":"","sources":["../../src/fetchHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAQrD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD;;GAEG;AACH,SAAS,oBAAoB,CAAC,IAAS;IAC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AC5D,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE;oBAClB,mBAAmB;oBACnB,UAAU,CAAC,KAAK,EAAE,CAAC;oBACnB,MAAM,CAAC,WAAW,EAAE,CAAC;oBACrB,OAAO;iBACR;gBAED,WAAW,IAAI,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAAM,mCAAI,CAAC,CAAC;gBAElC,qDAAqD;gBACrD,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;gBAE1B,IAAI,UAAU,EAAE;oBACd,UAAU,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;iBAC7B;YACH,CAAC;SACF,CAAC,CAAC;KACJ;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC;AAED,SAAS,0BAA0B,CAAC,cAA8B;IAChE,OAAO,cAAc,CAAC,WAAW,KAAK,SAAS,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS,CAAC;AACxF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"@azure/abort-controller\";\nimport {\n HttpClient,\n HttpHeaders as PipelineHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { RestError } from \"./restError\";\nimport { createHttpHeaders } from \"./httpHeaders\";\n\n/**\n * Checks if the body is a NodeReadable stream which is not supported in Browsers\n */\nfunction isNodeReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\n/**\n * Checks if the body is a ReadableStream supported by browsers\n */\nfunction isReadableStream(body: unknown): body is ReadableStream {\n return Boolean(\n body &&\n typeof (body as ReadableStream).getReader === \"function\" &&\n typeof (body as ReadableStream).tee === \"function\"\n );\n}\n\n/**\n * Checks if the body is a Blob or Blob-like\n */\nfunction isBlob(body: unknown): body is Blob {\n // File objects count as a type of Blob, so we want to use instanceof explicitly\n return (typeof Blob === \"function\" || typeof Blob === \"object\") && body instanceof Blob;\n}\n\n/**\n * A HttpClient implementation that uses window.fetch to send HTTP requests.\n * @internal\n */\nclass FetchHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n try {\n return await makeRequest(request);\n } catch (e: any) {\n throw getError(e, request);\n }\n }\n}\n\n/**\n * Sends a request\n */\nasync function makeRequest(request: PipelineRequest): Promise {\n const { abortController, abortControllerCleanup } = setupAbortSignal(request);\n\n try {\n const headers = buildFetchHeaders(request.headers);\n const requestBody = buildRequestBody(request);\n\n /**\n * Developers of the future:\n * Do not set redirect: \"manual\" as part\n * of request options.\n * It will not work as you expect.\n */\n const response = await fetch(request.url, {\n body: requestBody,\n method: request.method,\n headers: headers,\n signal: abortController.signal,\n credentials: request.withCredentials ? \"include\" : \"same-origin\",\n cache: \"no-store\",\n });\n // If we're uploading a blob, we need to fire the progress event manually\n if (isBlob(request.body) && request.onUploadProgress) {\n request.onUploadProgress({ loadedBytes: request.body.size });\n }\n return buildPipelineResponse(response, request);\n } finally {\n if (abortControllerCleanup) {\n abortControllerCleanup();\n }\n }\n}\n\n/**\n * Creates a pipeline response from a Fetch response;\n */\nasync function buildPipelineResponse(httpResponse: Response, request: PipelineRequest) {\n const headers = buildPipelineHeaders(httpResponse);\n const response: PipelineResponse = {\n request,\n headers,\n status: httpResponse.status,\n };\n\n const bodyStream = isReadableStream(httpResponse.body)\n ? buildBodyStream(httpResponse.body, request.onDownloadProgress)\n : httpResponse.body;\n\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(response.status)\n ) {\n if (request.enableBrowserStreams) {\n response.browserStreamBody = bodyStream ?? undefined;\n } else {\n const responseStream = new Response(bodyStream);\n response.blobBody = responseStream.blob();\n }\n } else {\n const responseStream = new Response(bodyStream);\n\n response.bodyAsText = await responseStream.text();\n }\n\n return response;\n}\n\nfunction setupAbortSignal(request: PipelineRequest): {\n abortController: AbortController;\n abortControllerCleanup: (() => void) | undefined;\n} {\n const abortController = new AbortController();\n\n // Cleanup function\n let abortControllerCleanup: (() => void) | undefined;\n\n /**\n * Attach an abort listener to the request\n */\n let abortListener: ((event: any) => void) | undefined;\n if (request.abortSignal) {\n if (request.abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n abortListener = (event: Event) => {\n if (event.type === \"abort\") {\n abortController.abort();\n }\n };\n request.abortSignal.addEventListener(\"abort\", abortListener);\n abortControllerCleanup = () => {\n if (abortListener) {\n request.abortSignal?.removeEventListener(\"abort\", abortListener);\n }\n };\n }\n\n // If a timeout was passed, call the abort signal once the time elapses\n if (request.timeout > 0) {\n setTimeout(() => {\n abortController.abort();\n }, request.timeout);\n }\n\n return { abortController, abortControllerCleanup };\n}\n\n/**\n * Gets the specific error\n */\nfunction getError(e: RestError, request: PipelineRequest): RestError {\n if (e && e?.name === \"AbortError\") {\n return e;\n } else {\n return new RestError(`Error sending request: ${e.message}`, {\n code: e?.code ?? RestError.REQUEST_SEND_ERROR,\n request,\n });\n }\n}\n\n/**\n * Converts PipelineRequest headers to Fetch headers\n */\nfunction buildFetchHeaders(pipelineHeaders: PipelineHeaders) {\n const headers = new Headers();\n for (const [name, value] of pipelineHeaders) {\n headers.append(name, value);\n }\n\n return headers;\n}\n\nfunction buildPipelineHeaders(httpResponse: Response): PipelineHeaders {\n const responseHeaders = createHttpHeaders();\n for (const [name, value] of httpResponse.headers) {\n responseHeaders.set(name, value);\n }\n\n return responseHeaders;\n}\n\nfunction buildRequestBody(request: PipelineRequest) {\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isNodeReadableStream(body)) {\n throw new Error(\"Node streams are not supported in browser environment.\");\n }\n\n return isReadableStream(body) ? buildBodyStream(body, request.onUploadProgress) : body;\n}\n\n/**\n * Reads the request/response original stream and stream it through a new\n * ReadableStream, this is done to be able to report progress in a way that\n * all modern browsers support. TransformStreams would be an alternative,\n * however they are not yet supported by all browsers i.e Firefox\n */\nfunction buildBodyStream(\n readableStream: ReadableStream,\n onProgress?: (progress: TransferProgressEvent) => void\n): ReadableStream {\n let loadedBytes = 0;\n\n // If the current browser supports pipeThrough we use a TransformStream\n // to report progress\n if (isTransformStreamSupported(readableStream)) {\n return readableStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === null) {\n controller.terminate();\n return;\n }\n\n controller.enqueue(chunk);\n loadedBytes += chunk.length;\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n })\n );\n } else {\n // If we can't use transform streams, wrap the original stream in a new readable stream\n // and use pull to enqueue each chunk and report progress.\n const reader = readableStream.getReader();\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n // When no more data needs to be consumed, break the reading\n if (done || !value) {\n // Close the stream\n controller.close();\n reader.releaseLock();\n return;\n }\n\n loadedBytes += value?.length ?? 0;\n\n // Enqueue the next data chunk into our target stream\n controller.enqueue(value);\n\n if (onProgress) {\n onProgress({ loadedBytes });\n }\n },\n });\n }\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createFetchHttpClient(): HttpClient {\n return new FetchHttpClient();\n}\n\nfunction isTransformStreamSupported(readableStream: ReadableStream): boolean {\n return readableStream.pipeThrough !== undefined && self.TransformStream !== undefined;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js new file mode 100644 index 0000000..1a46c9d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function normalizeName(name) { + return name.toLowerCase(); +} +function* headerIterator(map) { + for (const entry of map.values()) { + yield [entry.name, entry.value]; + } +} +class HttpHeadersImpl { + constructor(rawHeaders) { + this._headersMap = new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name, value) { + this._headersMap.set(normalizeName(name), { name, value: String(value) }); + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name) { + var _a; + return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name) { + return this._headersMap.has(normalizeName(name)); + } + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name) { + this._headersMap.delete(normalizeName(name)); + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } + else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); + } + /** + * Iterate over tuples of header [name, value] pairs. + */ + [Symbol.iterator]() { + return headerIterator(this._headersMap); + } +} +/** + * Creates an object that satisfies the `HttpHeaders` interface. + * @param rawHeaders - A simple object representing initial headers + */ +export function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); +} +//# sourceMappingURL=httpHeaders.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js.map new file mode 100644 index 0000000..60298a0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/httpHeaders.js.map @@ -0,0 +1 @@ +{"version":3,"file":"httpHeaders.js","sourceRoot":"","sources":["../../src/httpHeaders.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,SAAS,aAAa,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,CAAC;AAED,QAAQ,CAAC,CAAC,cAAc,CAAC,GAA6B;IACpD,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,EAAE;QAChC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;KACjC;AACH,CAAC;AAED,MAAM,eAAe;IAGnB,YAAY,UAAiD;QAC3D,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAuB,CAAC;QAClD,IAAI,UAAU,EAAE;YACd,KAAK,MAAM,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;gBAChD,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;aAC9C;SACF;IACH,CAAC;IAED;;;;;OAKG;IACI,GAAG,CAAC,IAAY,EAAE,KAAgC;QACvD,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5E,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,IAAY;;QACrB,OAAO,MAAA,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,0CAAE,KAAK,CAAC;IAC1D,CAAC;IAED;;;OAGG;IACI,GAAG,CAAC,IAAY;QACrB,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,IAAY;QACxB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,UAAsC,EAAE;QACpD,MAAM,MAAM,GAAmB,EAAE,CAAC;QAClC,IAAI,OAAO,CAAC,YAAY,EAAE;YACxB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE;gBAC7C,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;aAClC;SACF;aAAM;YACL,KAAK,MAAM,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,WAAW,EAAE;gBACtD,MAAM,CAAC,cAAc,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;aACtC;SACF;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED;;OAEG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAC1C,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAgC;IAChE,OAAO,IAAI,eAAe,CAAC,UAAU,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpHeaders, RawHttpHeaders, RawHttpHeadersInput } from \"./interfaces\";\n\ninterface HeaderEntry {\n name: string;\n value: string;\n}\n\nfunction normalizeName(name: string): string {\n return name.toLowerCase();\n}\n\nfunction* headerIterator(map: Map): IterableIterator<[string, string]> {\n for (const entry of map.values()) {\n yield [entry.name, entry.value];\n }\n}\n\nclass HttpHeadersImpl implements HttpHeaders {\n private readonly _headersMap: Map;\n\n constructor(rawHeaders?: RawHttpHeaders | RawHttpHeadersInput) {\n this._headersMap = new Map();\n if (rawHeaders) {\n for (const headerName of Object.keys(rawHeaders)) {\n this.set(headerName, rawHeaders[headerName]);\n }\n }\n }\n\n /**\n * Set a header in this collection with the provided name and value. The name is\n * case-insensitive.\n * @param name - The name of the header to set. This value is case-insensitive.\n * @param value - The value of the header to set.\n */\n public set(name: string, value: string | number | boolean): void {\n this._headersMap.set(normalizeName(name), { name, value: String(value) });\n }\n\n /**\n * Get the header value for the provided header name, or undefined if no header exists in this\n * collection with the provided name.\n * @param name - The name of the header. This value is case-insensitive.\n */\n public get(name: string): string | undefined {\n return this._headersMap.get(normalizeName(name))?.value;\n }\n\n /**\n * Get whether or not this header collection contains a header entry for the provided header name.\n * @param name - The name of the header to set. This value is case-insensitive.\n */\n public has(name: string): boolean {\n return this._headersMap.has(normalizeName(name));\n }\n\n /**\n * Remove the header with the provided headerName.\n * @param name - The name of the header to remove.\n */\n public delete(name: string): void {\n this._headersMap.delete(normalizeName(name));\n }\n\n /**\n * Get the JSON object representation of this HTTP header collection.\n */\n public toJSON(options: { preserveCase?: boolean } = {}): RawHttpHeaders {\n const result: RawHttpHeaders = {};\n if (options.preserveCase) {\n for (const entry of this._headersMap.values()) {\n result[entry.name] = entry.value;\n }\n } else {\n for (const [normalizedName, entry] of this._headersMap) {\n result[normalizedName] = entry.value;\n }\n }\n\n return result;\n }\n\n /**\n * Get the string representation of this HTTP header collection.\n */\n public toString(): string {\n return JSON.stringify(this.toJSON({ preserveCase: true }));\n }\n\n /**\n * Iterate over tuples of header [name, value] pairs.\n */\n [Symbol.iterator](): Iterator<[string, string]> {\n return headerIterator(this._headersMap);\n }\n}\n\n/**\n * Creates an object that satisfies the `HttpHeaders` interface.\n * @param rawHeaders - A simple object representing initial headers\n */\nexport function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders {\n return new HttpHeadersImpl(rawHeaders);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js new file mode 100644 index 0000000..7107ba7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export { createEmptyPipeline, } from "./pipeline"; +export { createPipelineFromOptions, } from "./createPipelineFromOptions"; +export { createDefaultHttpClient } from "./defaultHttpClient"; +export { createHttpHeaders } from "./httpHeaders"; +export { createPipelineRequest } from "./pipelineRequest"; +export { RestError, isRestError } from "./restError"; +export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy"; +export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy"; +export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy"; +export { logPolicy, logPolicyName } from "./policies/logPolicy"; +export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy"; +export { redirectPolicy, redirectPolicyName, } from "./policies/redirectPolicy"; +export { systemErrorRetryPolicy, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy"; +export { throttlingRetryPolicy, throttlingRetryPolicyName, } from "./policies/throttlingRetryPolicy"; +export { retryPolicy } from "./policies/retryPolicy"; +export { tracingPolicy, tracingPolicyName } from "./policies/tracingPolicy"; +export { defaultRetryPolicy } from "./policies/defaultRetryPolicy"; +export { userAgentPolicy, userAgentPolicyName, } from "./policies/userAgentPolicy"; +export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy"; +export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy"; +export { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName, } from "./policies/bearerTokenAuthenticationPolicy"; +export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js.map new file mode 100644 index 0000000..3b0d739 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAsBlC,OAAO,EAKL,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,yBAAyB,GAG1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAA0B,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,SAAS,EAAoB,WAAW,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,GAC3B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,aAAa,EAAoB,MAAM,sBAAsB,CAAC;AAClF,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAC/F,OAAO,EACL,cAAc,EACd,kBAAkB,GAEnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,GAC3B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,yBAAyB,GAE1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAsB,MAAM,wBAAwB,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAwB,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAE,kBAAkB,EAA6B,MAAM,+BAA+B,CAAC;AAC9F,OAAO,EACL,eAAe,EACf,mBAAmB,GAEpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EACL,+BAA+B,EAE/B,mCAAmC,GAIpC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport {\n Agent,\n FormDataMap,\n FormDataValue,\n HttpClient,\n HttpHeaders,\n HttpMethods,\n KeyObject,\n PipelineRequest,\n PipelineResponse,\n PipelineRetryOptions,\n ProxySettings,\n PxfObject,\n RawHttpHeaders,\n RawHttpHeadersInput,\n RequestBodyType,\n SendRequest,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces\";\nexport {\n AddPolicyOptions as AddPipelineOptions,\n PipelinePhase,\n PipelinePolicy,\n Pipeline,\n createEmptyPipeline,\n} from \"./pipeline\";\nexport {\n createPipelineFromOptions,\n InternalPipelineOptions,\n PipelineOptions,\n} from \"./createPipelineFromOptions\";\nexport { createDefaultHttpClient } from \"./defaultHttpClient\";\nexport { createHttpHeaders } from \"./httpHeaders\";\nexport { createPipelineRequest, PipelineRequestOptions } from \"./pipelineRequest\";\nexport { RestError, RestErrorOptions, isRestError } from \"./restError\";\nexport {\n decompressResponsePolicy,\n decompressResponsePolicyName,\n} from \"./policies/decompressResponsePolicy\";\nexport {\n exponentialRetryPolicy,\n ExponentialRetryPolicyOptions,\n exponentialRetryPolicyName,\n} from \"./policies/exponentialRetryPolicy\";\nexport {\n setClientRequestIdPolicy,\n setClientRequestIdPolicyName,\n} from \"./policies/setClientRequestIdPolicy\";\nexport { logPolicy, logPolicyName, LogPolicyOptions } from \"./policies/logPolicy\";\nexport { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from \"./policies/proxyPolicy\";\nexport {\n redirectPolicy,\n redirectPolicyName,\n RedirectPolicyOptions,\n} from \"./policies/redirectPolicy\";\nexport {\n systemErrorRetryPolicy,\n SystemErrorRetryPolicyOptions,\n systemErrorRetryPolicyName,\n} from \"./policies/systemErrorRetryPolicy\";\nexport {\n throttlingRetryPolicy,\n throttlingRetryPolicyName,\n ThrottlingRetryPolicyOptions,\n} from \"./policies/throttlingRetryPolicy\";\nexport { retryPolicy, RetryPolicyOptions } from \"./policies/retryPolicy\";\nexport { RetryStrategy, RetryInformation, RetryModifiers } from \"./retryStrategies/retryStrategy\";\nexport { tracingPolicy, tracingPolicyName, TracingPolicyOptions } from \"./policies/tracingPolicy\";\nexport { defaultRetryPolicy, DefaultRetryPolicyOptions } from \"./policies/defaultRetryPolicy\";\nexport {\n userAgentPolicy,\n userAgentPolicyName,\n UserAgentPolicyOptions,\n} from \"./policies/userAgentPolicy\";\nexport { tlsPolicy, tlsPolicyName } from \"./policies/tlsPolicy\";\nexport { formDataPolicy, formDataPolicyName } from \"./policies/formDataPolicy\";\nexport {\n bearerTokenAuthenticationPolicy,\n BearerTokenAuthenticationPolicyOptions,\n bearerTokenAuthenticationPolicyName,\n ChallengeCallbacks,\n AuthorizeRequestOptions,\n AuthorizeRequestOnChallengeOptions,\n} from \"./policies/bearerTokenAuthenticationPolicy\";\nexport { ndJsonPolicy, ndJsonPolicyName } from \"./policies/ndJsonPolicy\";\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js new file mode 100644 index 0000000..c0a2e2e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export {}; +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js.map new file mode 100644 index 0000000..22e4a57 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { OperationTracingOptions } from \"@azure/core-tracing\";\n\n/**\n * A HttpHeaders collection represented as a simple JSON object.\n */\nexport type RawHttpHeaders = { [headerName: string]: string };\n\n/**\n * A HttpHeaders collection for input, represented as a simple JSON object.\n */\nexport type RawHttpHeadersInput = Record;\n\n/**\n * Represents a set of HTTP headers on a request/response.\n * Header names are treated as case insensitive.\n */\nexport interface HttpHeaders extends Iterable<[string, string]> {\n /**\n * Returns the value of a specific header or undefined if not set.\n * @param name - The name of the header to retrieve.\n */\n get(name: string): string | undefined;\n /**\n * Returns true if the specified header exists.\n * @param name - The name of the header to check.\n */\n has(name: string): boolean;\n /**\n * Sets a specific header with a given value.\n * @param name - The name of the header to set.\n * @param value - The value to use for the header.\n */\n set(name: string, value: string | number | boolean): void;\n /**\n * Removes a specific header from the collection.\n * @param name - The name of the header to delete.\n */\n delete(name: string): void;\n /**\n * Accesses a raw JS object that acts as a simple map\n * of header names to values.\n */\n toJSON(options?: { preserveCase?: boolean }): RawHttpHeaders;\n}\n\n/**\n * Types of bodies supported on the request.\n * NodeJS.ReadableStream and () =\\> NodeJS.ReadableStream is Node only.\n * Blob, ReadableStream, and () =\\> ReadableStream are browser only.\n */\nexport type RequestBodyType =\n | NodeJS.ReadableStream\n | (() => NodeJS.ReadableStream)\n | ReadableStream\n | (() => ReadableStream)\n | Blob\n | ArrayBuffer\n | ArrayBufferView\n | FormData\n | string\n | null;\n\n/**\n * An interface compatible with NodeJS's `http.Agent`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface Agent {\n /**\n * Destroy any sockets that are currently in use by the agent.\n */\n destroy(): void;\n /**\n * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.\n */\n maxFreeSockets: number;\n /**\n * Determines how many concurrent sockets the agent can have open per origin.\n */\n maxSockets: number;\n /**\n * An object which contains queues of requests that have not yet been assigned to sockets.\n */\n requests: unknown;\n /**\n * An object which contains arrays of sockets currently in use by the agent.\n */\n sockets: unknown;\n}\n\n/**\n * Metadata about a request being made by the pipeline.\n */\nexport interface PipelineRequest {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout: number;\n\n /**\n * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.\n * Defaults to false.\n */\n withCredentials: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n * When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream.\n */\n streamResponseStatusCodes?: Set;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Tracing options to use for any created Spans.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n\n /**\n * NODEJS ONLY\n *\n * A Node-only option to provide a custom `http.Agent`/`https.Agent`.\n * Does nothing when running in the browser.\n */\n agent?: Agent;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable browser Streams. If this option is set and a response is a stream\n * the response will have a property `browserStream` instead of `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /** Settings for configuring TLS authentication */\n tlsSettings?: TlsSettings;\n}\n\n/**\n * Metadata about a response received by the pipeline.\n */\nexport interface PipelineResponse {\n /**\n * The request that generated this response.\n */\n request: PipelineRequest;\n /**\n * The HTTP status code of the response.\n */\n status: number;\n /**\n * The HTTP response headers.\n */\n headers: HttpHeaders;\n\n /**\n * The response body as text (string format)\n */\n bodyAsText?: string | null;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser Blob.\n * Always undefined in node.js.\n */\n blobBody?: Promise;\n\n /**\n * BROWSER ONLY\n *\n * The response body as a browser ReadableStream.\n * Always undefined in node.js.\n */\n browserStreamBody?: ReadableStream;\n\n /**\n * NODEJS ONLY\n *\n * The response body as a node.js Readable stream.\n * Always undefined in the browser.\n */\n readableStreamBody?: NodeJS.ReadableStream;\n}\n\n/**\n * A simple interface for making a pipeline request and receiving a response.\n */\nexport type SendRequest = (request: PipelineRequest) => Promise;\n\n/**\n * The required interface for a client that makes HTTP requests\n * on behalf of a pipeline.\n */\nexport interface HttpClient {\n /**\n * The method that makes the request and returns a response.\n */\n sendRequest: SendRequest;\n}\n\n/**\n * Fired in response to upload or download progress.\n */\nexport type TransferProgressEvent = {\n /**\n * The number of bytes loaded so far.\n */\n loadedBytes: number;\n};\n\n/**\n * Supported HTTP methods to use when making requests.\n */\nexport type HttpMethods =\n | \"GET\"\n | \"PUT\"\n | \"POST\"\n | \"DELETE\"\n | \"PATCH\"\n | \"HEAD\"\n | \"OPTIONS\"\n | \"TRACE\";\n\n/**\n * Options to configure a proxy for outgoing requests (Node.js only).\n */\nexport interface ProxySettings {\n /**\n * The proxy's host address.\n */\n host: string;\n\n /**\n * The proxy host's port.\n */\n port: number;\n\n /**\n * The user name to authenticate with the proxy, if required.\n */\n username?: string;\n\n /**\n * The password to authenticate with the proxy, if required.\n */\n password?: string;\n}\n\n/**\n * Each form data entry can be a string or (in the browser) a Blob.\n */\nexport type FormDataValue = string | Blob;\n\n/**\n * A simple object that provides form data, as if from a browser form.\n */\nexport type FormDataMap = { [key: string]: FormDataValue | FormDataValue[] };\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface PipelineRetryOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second). The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * Represents a certificate credential for authentication.\n */\nexport interface CertificateCredential {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: [,passphrase: ]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: [,passphrase: ]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array | undefined;\n}\n\n/**\n * Represents a certificate for TLS authentication.\n */\nexport interface TlsSettings {\n /**\n * Optionally override the trusted CA certificates. Default is to trust\n * the well-known CAs curated by Mozilla. Mozilla's CAs are completely\n * replaced when CAs are explicitly specified using this option.\n */\n ca?: string | Buffer | Array | undefined;\n /**\n * Cert chains in PEM format. One cert chain should be provided per\n * private key. Each cert chain should consist of the PEM formatted\n * certificate for a provided private key, followed by the PEM\n * formatted intermediate certificates (if any), in order, and not\n * including the root CA (the root CA must be pre-known to the peer,\n * see ca). When providing multiple cert chains, they do not have to\n * be in the same order as their private keys in key. If the\n * intermediate certificates are not provided, the peer will not be\n * able to validate the certificate, and the handshake will fail.\n */\n cert?: string | Buffer | Array | undefined;\n /**\n * Private keys in PEM format. PEM allows the option of private keys\n * being encrypted. Encrypted keys will be decrypted with\n * options.passphrase. Multiple keys using different algorithms can be\n * provided either as an array of unencrypted key strings or buffers,\n * or an array of objects in the form `{pem: [,passphrase: ]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n key?: string | Buffer | Array | undefined;\n /**\n * Shared passphrase used for a single private key and/or a PFX.\n */\n passphrase?: string | undefined;\n /**\n * PFX or PKCS12 encoded private key and certificate chain. pfx is an\n * alternative to providing key and cert individually. PFX is usually\n * encrypted, if it is, passphrase will be used to decrypt it. Multiple\n * PFX can be provided either as an array of unencrypted PFX buffers,\n * or an array of objects in the form `{buf: [,passphrase: ]}`.\n * The object form can only occur in an array.object.passphrase is optional.\n * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.\n */\n pfx?: string | Buffer | Array | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.KeyObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface KeyObject {\n /**\n * Private keys in PEM format.\n */\n pem: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n\n/**\n * An interface compatible with NodeJS's `tls.PxfObject`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface PxfObject {\n /**\n * PFX or PKCS12 encoded private key and certificate chain.\n */\n buf: string | Buffer;\n /**\n * Optional passphrase.\n */\n passphrase?: string | undefined;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js new file mode 100644 index 0000000..10a0a4e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("core-rest-pipeline"); +//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js.map new file mode 100644 index 0000000..9490f3c --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/log.js.map @@ -0,0 +1 @@ +{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,oBAAoB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\nexport const logger = createClientLogger(\"core-rest-pipeline\");\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js new file mode 100644 index 0000000..cac73e3 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import * as http from "http"; +import * as https from "https"; +import * as zlib from "zlib"; +import { Transform } from "stream"; +import { AbortController, AbortError } from "@azure/abort-controller"; +import { createHttpHeaders } from "./httpHeaders"; +import { RestError } from "./restError"; +import { logger } from "./log"; +const DEFAULT_TLS_SETTINGS = {}; +function isReadableStream(body) { + return body && typeof body.pipe === "function"; +} +function isStreamComplete(stream) { + return new Promise((resolve) => { + stream.on("close", resolve); + stream.on("end", resolve); + stream.on("error", resolve); + }); +} +function isArrayBuffer(body) { + return body && typeof body.byteLength === "number"; +} +class ReportTransform extends Transform { + constructor(progressCallback) { + super(); + this.loadedBytes = 0; + this.progressCallback = progressCallback; + } + // eslint-disable-next-line @typescript-eslint/ban-types + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } + catch (e) { + callback(e); + } + } +} +/** + * A HttpClient implementation that uses Node's "https" module to send HTTPS requests. + * @internal + */ +class NodeHttpClient { + constructor() { + this.cachedHttpsAgents = new WeakMap(); + } + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a, _b, _c; + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController.abort(); + } + }; + request.abortSignal.addEventListener("abort", abortListener); + } + if (request.timeout > 0) { + setTimeout(() => { + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); + let body = typeof request.body === "function" ? request.body() : request.body; + if (body && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + logger.error("Error in upload progress", e); + }); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } + else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body); + const headers = getResponseHeaders(res); + const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; + const response = { + status, + headers, + request, + }; + // Responses to HEAD must not have a body. + // If they do return a body, that body must be ignored. + if (request.method === "HEAD") { + // call resume() and not destroy() to avoid closing the socket + // and losing keep alive + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || + ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) { + response.readableStreamBody = responseStream; + } + else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } + finally { + // clean up event listener + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(() => { + var _a; + // eslint-disable-next-line promise/always-return + if (abortListener) { + (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + } + }) + .catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url.hostname, + path: `${url.pathname}${url.search}`, + port: url.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }), + }; + return new Promise((resolve, reject) => { + const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve); + req.once("error", (err) => { + var _a; + reject(new RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new AbortError("The operation was aborted."); + req.destroy(abortError); + reject(abortError); + }); + if (body && isReadableStream(body)) { + body.pipe(req); + } + else if (body) { + if (typeof body === "string" || Buffer.isBuffer(body)) { + req.end(body); + } + else if (isArrayBuffer(body)) { + req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); + } + else { + logger.error("Unrecognized body type", body); + reject(new RestError("Unrecognized body type")); + } + } + else { + // streams don't like "undefined" being passed as data + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + var _a; + const disableKeepAlive = request.disableKeepAlive; + // Handle Insecure requests first + if (isInsecure) { + if (disableKeepAlive) { + // keepAlive:false is the default so we don't need a custom Agent + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + // If there is no cached agent create a new one and cache it. + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } + else { + if (disableKeepAlive && !request.tlsSettings) { + // When there are no tlsSettings and keepAlive is false + // we don't need a custom agent + return https.globalAgent; + } + // We use the tlsSettings to index cached clients + const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; + // Get the cached agent or create a new one with the + // provided values for keepAlive and tlsSettings + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https.Agent(Object.assign({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive }, tlsSettings)); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } +} +function getResponseHeaders(res) { + const headers = createHttpHeaders(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } + else if (value) { + headers.set(header, value); + } + } + return headers; +} +function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } + else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; + } + return stream; +} +function streamToText(stream) { + return new Promise((resolve, reject) => { + const buffer = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer.push(chunk); + } + else { + buffer.push(Buffer.from(chunk)); + } + }); + stream.on("end", () => { + resolve(Buffer.concat(buffer).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { + reject(e); + } + else { + reject(new RestError(`Error reading response as text: ${e.message}`, { + code: RestError.PARSE_ERROR, + })); + } + }); + }); +} +/** @internal */ +export function getBodyLength(body) { + if (!body) { + return 0; + } + else if (Buffer.isBuffer(body)) { + return body.length; + } + else if (isReadableStream(body)) { + return null; + } + else if (isArrayBuffer(body)) { + return body.byteLength; + } + else if (typeof body === "string") { + return Buffer.from(body).length; + } + else { + return null; + } +} +/** + * Create a new HttpClient instance for the NodeJS environment. + * @internal + */ +export function createNodeHttpClient() { + return new NodeHttpClient(); +} +//# sourceMappingURL=nodeHttpClient.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js.map new file mode 100644 index 0000000..88276c8 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/nodeHttpClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nodeHttpClient.js","sourceRoot":"","sources":["../../src/nodeHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAUtE,OAAO,EAA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,CAAC,MAAM,CAAC;KACpB;SAAM,IAAI,gBAAgB,CAAC,IAAI,CAAC,EAAE;QACjC,OAAO,IAAI,CAAC;KACb;SAAM,IAAI,aAAa,CAAC,IAAI,CAAC,EAAE;QAC9B,OAAO,IAAI,CAAC,UAAU,CAAC;KACxB;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QACnC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC;KACjC;SAAM;QACL,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,IAAI,cAAc,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as http from \"http\";\nimport * as https from \"https\";\nimport * as zlib from \"zlib\";\nimport { Transform } from \"stream\";\nimport { AbortController, AbortError } from \"@azure/abort-controller\";\nimport {\n HttpClient,\n HttpHeaders,\n PipelineRequest,\n PipelineResponse,\n RequestBodyType,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { RestError } from \"./restError\";\nimport { IncomingMessage } from \"http\";\nimport { logger } from \"./log\";\n\nconst DEFAULT_TLS_SETTINGS = {};\n\nfunction isReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\nfunction isStreamComplete(stream: NodeJS.ReadableStream): Promise {\n return new Promise((resolve) => {\n stream.on(\"close\", resolve);\n stream.on(\"end\", resolve);\n stream.on(\"error\", resolve);\n });\n}\n\nfunction isArrayBuffer(body: any): body is ArrayBuffer | ArrayBufferView {\n return body && typeof body.byteLength === \"number\";\n}\n\nclass ReportTransform extends Transform {\n private loadedBytes = 0;\n private progressCallback: (progress: TransferProgressEvent) => void;\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n _transform(chunk: string | Buffer, _encoding: string, callback: Function): void {\n this.push(chunk);\n this.loadedBytes += chunk.length;\n try {\n this.progressCallback({ loadedBytes: this.loadedBytes });\n callback();\n } catch (e: any) {\n callback(e);\n }\n }\n\n constructor(progressCallback: (progress: TransferProgressEvent) => void) {\n super();\n this.progressCallback = progressCallback;\n }\n}\n\n/**\n * A HttpClient implementation that uses Node's \"https\" module to send HTTPS requests.\n * @internal\n */\nclass NodeHttpClient implements HttpClient {\n private cachedHttpAgent?: http.Agent;\n private cachedHttpsAgents: WeakMap = new WeakMap();\n\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise {\n const abortController = new AbortController();\n let abortListener: ((event: any) => void) | undefined;\n if (request.abortSignal) {\n if (request.abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n abortListener = (event: Event) => {\n if (event.type === \"abort\") {\n abortController.abort();\n }\n };\n request.abortSignal.addEventListener(\"abort\", abortListener);\n }\n\n if (request.timeout > 0) {\n setTimeout(() => {\n abortController.abort();\n }, request.timeout);\n }\n\n const acceptEncoding = request.headers.get(\"Accept-Encoding\");\n const shouldDecompress =\n acceptEncoding?.includes(\"gzip\") || acceptEncoding?.includes(\"deflate\");\n\n let body = typeof request.body === \"function\" ? request.body() : request.body;\n if (body && !request.headers.has(\"Content-Length\")) {\n const bodyLength = getBodyLength(body);\n if (bodyLength !== null) {\n request.headers.set(\"Content-Length\", bodyLength);\n }\n }\n\n let responseStream: NodeJS.ReadableStream | undefined;\n try {\n if (body && request.onUploadProgress) {\n const onUploadProgress = request.onUploadProgress;\n const uploadReportStream = new ReportTransform(onUploadProgress);\n uploadReportStream.on(\"error\", (e) => {\n logger.error(\"Error in upload progress\", e);\n });\n if (isReadableStream(body)) {\n body.pipe(uploadReportStream);\n } else {\n uploadReportStream.end(body);\n }\n\n body = uploadReportStream;\n }\n\n const res = await this.makeRequest(request, abortController, body);\n\n const headers = getResponseHeaders(res);\n\n const status = res.statusCode ?? 0;\n const response: PipelineResponse = {\n status,\n headers,\n request,\n };\n\n // Responses to HEAD must not have a body.\n // If they do return a body, that body must be ignored.\n if (request.method === \"HEAD\") {\n // call resume() and not destroy() to avoid closing the socket\n // and losing keep alive\n res.resume();\n return response;\n }\n\n responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;\n\n const onDownloadProgress = request.onDownloadProgress;\n if (onDownloadProgress) {\n const downloadReportStream = new ReportTransform(onDownloadProgress);\n downloadReportStream.on(\"error\", (e) => {\n logger.error(\"Error in download progress\", e);\n });\n responseStream.pipe(downloadReportStream);\n responseStream = downloadReportStream;\n }\n\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(response.status)\n ) {\n response.readableStreamBody = responseStream;\n } else {\n response.bodyAsText = await streamToText(responseStream);\n }\n\n return response;\n } finally {\n // clean up event listener\n if (request.abortSignal && abortListener) {\n let uploadStreamDone = Promise.resolve();\n if (isReadableStream(body)) {\n uploadStreamDone = isStreamComplete(body as NodeJS.ReadableStream);\n }\n let downloadStreamDone = Promise.resolve();\n if (isReadableStream(responseStream)) {\n downloadStreamDone = isStreamComplete(responseStream);\n }\n\n Promise.all([uploadStreamDone, downloadStreamDone])\n .then(() => {\n // eslint-disable-next-line promise/always-return\n if (abortListener) {\n request.abortSignal?.removeEventListener(\"abort\", abortListener);\n }\n })\n .catch((e) => {\n logger.warning(\"Error when cleaning up abortListener on httpRequest\", e);\n });\n }\n }\n }\n\n private makeRequest(\n request: PipelineRequest,\n abortController: AbortController,\n body?: RequestBodyType\n ): Promise {\n const url = new URL(request.url);\n\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n const agent = (request.agent as http.Agent) ?? this.getOrCreateAgent(request, isInsecure);\n const options: http.RequestOptions = {\n agent,\n hostname: url.hostname,\n path: `${url.pathname}${url.search}`,\n port: url.port,\n method: request.method,\n headers: request.headers.toJSON({ preserveCase: true }),\n };\n\n return new Promise((resolve, reject) => {\n const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);\n\n req.once(\"error\", (err: Error & { code?: string }) => {\n reject(\n new RestError(err.message, { code: err.code ?? RestError.REQUEST_SEND_ERROR, request })\n );\n });\n\n abortController.signal.addEventListener(\"abort\", () => {\n const abortError = new AbortError(\"The operation was aborted.\");\n req.destroy(abortError);\n reject(abortError);\n });\n if (body && isReadableStream(body)) {\n body.pipe(req);\n } else if (body) {\n if (typeof body === \"string\" || Buffer.isBuffer(body)) {\n req.end(body);\n } else if (isArrayBuffer(body)) {\n req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));\n } else {\n logger.error(\"Unrecognized body type\", body);\n reject(new RestError(\"Unrecognized body type\"));\n }\n } else {\n // streams don't like \"undefined\" being passed as data\n req.end();\n }\n });\n }\n\n private getOrCreateAgent(request: PipelineRequest, isInsecure: boolean): http.Agent {\n const disableKeepAlive = request.disableKeepAlive;\n\n // Handle Insecure requests first\n if (isInsecure) {\n if (disableKeepAlive) {\n // keepAlive:false is the default so we don't need a custom Agent\n return http.globalAgent;\n }\n\n if (!this.cachedHttpAgent) {\n // If there is no cached agent create a new one and cache it.\n this.cachedHttpAgent = new http.Agent({ keepAlive: true });\n }\n return this.cachedHttpAgent;\n } else {\n if (disableKeepAlive && !request.tlsSettings) {\n // When there are no tlsSettings and keepAlive is false\n // we don't need a custom agent\n return https.globalAgent;\n }\n\n // We use the tlsSettings to index cached clients\n const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS;\n\n // Get the cached agent or create a new one with the\n // provided values for keepAlive and tlsSettings\n let agent = this.cachedHttpsAgents.get(tlsSettings);\n\n if (agent && agent.options.keepAlive === !disableKeepAlive) {\n return agent;\n }\n\n logger.info(\"No cached TLS Agent exist, creating a new Agent\");\n agent = new https.Agent({\n // keepAlive is true if disableKeepAlive is false.\n keepAlive: !disableKeepAlive,\n // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options.\n ...tlsSettings,\n });\n\n this.cachedHttpsAgents.set(tlsSettings, agent);\n return agent;\n }\n }\n}\n\nfunction getResponseHeaders(res: IncomingMessage): HttpHeaders {\n const headers = createHttpHeaders();\n for (const header of Object.keys(res.headers)) {\n const value = res.headers[header];\n if (Array.isArray(value)) {\n if (value.length > 0) {\n headers.set(header, value[0]);\n }\n } else if (value) {\n headers.set(header, value);\n }\n }\n return headers;\n}\n\nfunction getDecodedResponseStream(\n stream: IncomingMessage,\n headers: HttpHeaders\n): NodeJS.ReadableStream {\n const contentEncoding = headers.get(\"Content-Encoding\");\n if (contentEncoding === \"gzip\") {\n const unzip = zlib.createGunzip();\n stream.pipe(unzip);\n return unzip;\n } else if (contentEncoding === \"deflate\") {\n const inflate = zlib.createInflate();\n stream.pipe(inflate);\n return inflate;\n }\n\n return stream;\n}\n\nfunction streamToText(stream: NodeJS.ReadableStream): Promise {\n return new Promise((resolve, reject) => {\n const buffer: Buffer[] = [];\n\n stream.on(\"data\", (chunk) => {\n if (Buffer.isBuffer(chunk)) {\n buffer.push(chunk);\n } else {\n buffer.push(Buffer.from(chunk));\n }\n });\n stream.on(\"end\", () => {\n resolve(Buffer.concat(buffer).toString(\"utf8\"));\n });\n stream.on(\"error\", (e) => {\n if (e && e?.name === \"AbortError\") {\n reject(e);\n } else {\n reject(\n new RestError(`Error reading response as text: ${e.message}`, {\n code: RestError.PARSE_ERROR,\n })\n );\n }\n });\n });\n}\n\n/** @internal */\nexport function getBodyLength(body: RequestBodyType): number | null {\n if (!body) {\n return 0;\n } else if (Buffer.isBuffer(body)) {\n return body.length;\n } else if (isReadableStream(body)) {\n return null;\n } else if (isArrayBuffer(body)) {\n return body.byteLength;\n } else if (typeof body === \"string\") {\n return Buffer.from(body).length;\n } else {\n return null;\n }\n}\n\n/**\n * Create a new HttpClient instance for the NodeJS environment.\n * @internal\n */\nexport function createNodeHttpClient(): HttpClient {\n return new NodeHttpClient();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js new file mode 100644 index 0000000..07e8ced --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js @@ -0,0 +1,262 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]); +/** + * A private implementation of Pipeline. + * Do not export this class from the package. + * @internal + */ +class HttpPipeline { + constructor(policies) { + var _a; + this._policies = []; + this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; + this._orderedPolicies = undefined; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options, + }); + this._orderedPolicies = undefined; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if ((options.name && policyDescriptor.policy.name === options.name) || + (options.phase && policyDescriptor.options.phase === options.phase)) { + removedPolicies.push(policyDescriptor.policy); + return false; + } + else { + return true; + } + }); + this._orderedPolicies = undefined; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new HttpPipeline(this._policies); + } + static create() { + return new HttpPipeline(); + } + orderPolicies() { + /** + * The goal of this method is to reliably order pipeline policies + * based on their declared requirements when they were added. + * + * Order is first determined by phase: + * + * 1. Serialize Phase + * 2. Policies not in a phase + * 3. Deserialize Phase + * 4. Retry Phase + * 5. Sign Phase + * + * Within each phase, policies are executed in the order + * they were added unless they were specified to execute + * before/after other policies or after a particular phase. + * + * To determine the final order, we will walk the policy list + * in phase order multiple times until all dependencies are + * satisfied. + * + * `afterPolicies` are the set of policies that must be + * executed before a given policy. This requirement is + * considered satisfied when each of the listed policies + * have been scheduled. + * + * `beforePolicies` are the set of policies that must be + * executed after a given policy. Since this dependency + * can be expressed by converting it into a equivalent + * `afterPolicies` declarations, they are normalized + * into that form for simplicity. + * + * An `afterPhase` dependency is considered satisfied when all + * policies in that phase have scheduled. + * + */ + const result = []; + // Track all policies we know about. + const policyMap = new Map(); + function createPhase(name) { + return { + name, + policies: new Set(), + hasRun: false, + hasAfterPolicies: false, + }; + } + // Track policies for each phase. + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + // a list of phases in order + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + // Small helper function to map phase name to each Phase + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } + else if (phase === "Serialize") { + return serializePhase; + } + else if (phase === "Deserialize") { + return deserializePhase; + } + else if (phase === "Sign") { + return signPhase; + } + else { + return noPhase; + } + } + // First walk each policy and create a node to track metadata. + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: new Set(), + dependants: new Set(), + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + // Now that each policy has a node, connect dependency references. + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + // Linking in both directions helps later + // when we want to notify dependants. + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + // To execute before another node, make it + // depend on the current node. + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + // Sets iterate in insertion order + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + // If this node is waiting on a phase to complete, + // we need to skip it for now. + // Even if the phase is empty, we should wait for it + // to be walked to avoid re-ordering policies. + continue; + } + if (node.dependsOn.size === 0) { + // If there's nothing else we're waiting for, we can + // add this policy to the result list. + result.push(node.policy); + // Notify anything that depends on this policy that + // the policy has been scheduled. + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + // if the phase isn't complete + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + // Try running noPhase to see if that unblocks this phase next tick. + // This can happen if a phase that happens before noPhase + // is waiting on a noPhase policy to complete. + walkPhase(noPhase); + } + // Don't proceed to the next phase until this phase finishes. + return; + } + if (phase.hasAfterPolicies) { + // Run any policies unblocked by this phase + walkPhase(noPhase); + } + } + } + // Iterate until we've put every node in the result list. + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + // Keep walking each phase in order until we can order every node. + walkPhases(); + // The result list *should* get at least one larger each time + // after the first full pass. + // Otherwise, we're going to loop forever. + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } +} +/** + * Creates a totally empty pipeline. + * Useful for testing or creating a custom one. + */ +export function createEmptyPipeline() { + return HttpPipeline.create(); +} +//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js.map new file mode 100644 index 0000000..ea80891 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipeline.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/pipeline.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAelC,MAAM,eAAe,GAAG,IAAI,GAAG,CAAgB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AAiG9F;;;;GAIG;AACH,MAAM,YAAY;IAIhB,YAAoB,QAA+B;;QAH3C,cAAS,GAAyB,EAAE,CAAC;QAI3C,IAAI,CAAC,SAAS,GAAG,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,KAAK,CAAC,CAAC,CAAC,mCAAI,EAAE,CAAC;QAC1C,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;IACpC,CAAC;IAEM,SAAS,CAAC,MAAsB,EAAE,UAA4B,EAAE;QACrE,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,UAAU,EAAE;YACvC,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;SACvE;QACD,IAAI,OAAO,CAAC,KAAK,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACxD,MAAM,IAAI,KAAK,CAAC,uBAAuB,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;SACzD;QACD,IAAI,OAAO,CAAC,UAAU,IAAI,CAAC,eAAe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AC;YAC1C,kEAAkE;YAClE,UAAU,EAAE,CAAC;YACb,6DAA6D;YAC7D,6BAA6B;YAC7B,0CAA0C;YAC1C,IAAI,MAAM,CAAC,MAAM,IAAI,mBAAmB,IAAI,SAAS,GAAG,CAAC,EAAE;gBACzD,MAAM,IAAI,KAAK,CAAC,+DAA+D,CAAC,CAAC;aAClF;SACF;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,YAAY,CAAC,MAAM,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { HttpClient, PipelineRequest, PipelineResponse, SendRequest } from \"./interfaces\";\n\n/**\n * Policies are executed in phases.\n * The execution order is:\n * 1. Serialize Phase\n * 2. Policies not in a phase\n * 3. Deserialize Phase\n * 4. Retry Phase\n * 5. Sign Phase\n */\nexport type PipelinePhase = \"Deserialize\" | \"Serialize\" | \"Retry\" | \"Sign\";\n\nconst ValidPhaseNames = new Set([\"Deserialize\", \"Serialize\", \"Retry\", \"Sign\"]);\n\n/**\n * Options when adding a policy to the pipeline.\n * Used to express dependencies on other policies.\n */\nexport interface AddPolicyOptions {\n /**\n * Policies that this policy must come before.\n */\n beforePolicies?: string[];\n /**\n * Policies that this policy must come after.\n */\n afterPolicies?: string[];\n /**\n * The phase that this policy must come after.\n */\n afterPhase?: PipelinePhase;\n /**\n * The phase this policy belongs to.\n */\n phase?: PipelinePhase;\n}\n\n/**\n * A pipeline policy manipulates a request as it travels through the pipeline.\n * It is conceptually a middleware that is allowed to modify the request before\n * it is made as well as the response when it is received.\n */\nexport interface PipelinePolicy {\n /**\n * The policy name. Must be a unique string in the pipeline.\n */\n name: string;\n /**\n * The main method to implement that manipulates a request/response.\n * @param request - The request being performed.\n * @param next - The next policy in the pipeline. Must be called to continue the pipeline.\n */\n sendRequest(request: PipelineRequest, next: SendRequest): Promise;\n}\n\n/**\n * Represents a pipeline for making a HTTP request to a URL.\n * Pipelines can have multiple policies to manage manipulating each request\n * before and after it is made to the server.\n */\nexport interface Pipeline {\n /**\n * Add a new policy to the pipeline.\n * @param policy - A policy that manipulates a request.\n * @param options - A set of options for when the policy should run.\n */\n addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void;\n /**\n * Remove a policy from the pipeline.\n * @param options - Options that let you specify which policies to remove.\n */\n removePolicy(options: { name?: string; phase?: PipelinePhase }): PipelinePolicy[];\n /**\n * Uses the pipeline to make a HTTP request.\n * @param httpClient - The HttpClient that actually performs the request.\n * @param request - The request to be made.\n */\n sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise;\n /**\n * Returns the current set of policies in the pipeline in the order in which\n * they will be applied to the request. Later in the list is closer to when\n * the request is performed.\n */\n getOrderedPolicies(): PipelinePolicy[];\n /**\n * Duplicates this pipeline to allow for modifying an existing one without mutating it.\n */\n clone(): Pipeline;\n}\n\ninterface PipelineDescriptor {\n policy: PipelinePolicy;\n options: AddPolicyOptions;\n}\n\ninterface PolicyGraphNode {\n policy: PipelinePolicy;\n dependsOn: Set;\n dependants: Set;\n afterPhase?: Phase;\n}\n\ninterface Phase {\n name: PipelinePhase | \"None\";\n policies: Set;\n hasRun: boolean;\n hasAfterPolicies: boolean;\n}\n\n/**\n * A private implementation of Pipeline.\n * Do not export this class from the package.\n * @internal\n */\nclass HttpPipeline implements Pipeline {\n private _policies: PipelineDescriptor[] = [];\n private _orderedPolicies?: PipelinePolicy[];\n\n private constructor(policies?: PipelineDescriptor[]) {\n this._policies = policies?.slice(0) ?? [];\n this._orderedPolicies = undefined;\n }\n\n public addPolicy(policy: PipelinePolicy, options: AddPolicyOptions = {}): void {\n if (options.phase && options.afterPhase) {\n throw new Error(\"Policies inside a phase cannot specify afterPhase.\");\n }\n if (options.phase && !ValidPhaseNames.has(options.phase)) {\n throw new Error(`Invalid phase name: ${options.phase}`);\n }\n if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {\n throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);\n }\n this._policies.push({\n policy,\n options,\n });\n this._orderedPolicies = undefined;\n }\n\n public removePolicy(options: { name?: string; phase?: string }): PipelinePolicy[] {\n const removedPolicies: PipelinePolicy[] = [];\n\n this._policies = this._policies.filter((policyDescriptor) => {\n if (\n (options.name && policyDescriptor.policy.name === options.name) ||\n (options.phase && policyDescriptor.options.phase === options.phase)\n ) {\n removedPolicies.push(policyDescriptor.policy);\n return false;\n } else {\n return true;\n }\n });\n this._orderedPolicies = undefined;\n\n return removedPolicies;\n }\n\n public sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise {\n const policies = this.getOrderedPolicies();\n\n const pipeline = policies.reduceRight(\n (next, policy) => {\n return (req: PipelineRequest) => {\n return policy.sendRequest(req, next);\n };\n },\n (req: PipelineRequest) => httpClient.sendRequest(req)\n );\n\n return pipeline(request);\n }\n\n public getOrderedPolicies(): PipelinePolicy[] {\n if (!this._orderedPolicies) {\n this._orderedPolicies = this.orderPolicies();\n }\n return this._orderedPolicies;\n }\n\n public clone(): Pipeline {\n return new HttpPipeline(this._policies);\n }\n\n public static create(): Pipeline {\n return new HttpPipeline();\n }\n\n private orderPolicies(): PipelinePolicy[] {\n /**\n * The goal of this method is to reliably order pipeline policies\n * based on their declared requirements when they were added.\n *\n * Order is first determined by phase:\n *\n * 1. Serialize Phase\n * 2. Policies not in a phase\n * 3. Deserialize Phase\n * 4. Retry Phase\n * 5. Sign Phase\n *\n * Within each phase, policies are executed in the order\n * they were added unless they were specified to execute\n * before/after other policies or after a particular phase.\n *\n * To determine the final order, we will walk the policy list\n * in phase order multiple times until all dependencies are\n * satisfied.\n *\n * `afterPolicies` are the set of policies that must be\n * executed before a given policy. This requirement is\n * considered satisfied when each of the listed policies\n * have been scheduled.\n *\n * `beforePolicies` are the set of policies that must be\n * executed after a given policy. Since this dependency\n * can be expressed by converting it into a equivalent\n * `afterPolicies` declarations, they are normalized\n * into that form for simplicity.\n *\n * An `afterPhase` dependency is considered satisfied when all\n * policies in that phase have scheduled.\n *\n */\n const result: PipelinePolicy[] = [];\n\n // Track all policies we know about.\n const policyMap: Map = new Map();\n\n function createPhase(name: PipelinePhase | \"None\"): Phase {\n return {\n name,\n policies: new Set(),\n hasRun: false,\n hasAfterPolicies: false,\n };\n }\n\n // Track policies for each phase.\n const serializePhase = createPhase(\"Serialize\");\n const noPhase = createPhase(\"None\");\n const deserializePhase = createPhase(\"Deserialize\");\n const retryPhase = createPhase(\"Retry\");\n const signPhase = createPhase(\"Sign\");\n\n // a list of phases in order\n const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];\n\n // Small helper function to map phase name to each Phase\n function getPhase(phase: PipelinePhase | undefined): Phase {\n if (phase === \"Retry\") {\n return retryPhase;\n } else if (phase === \"Serialize\") {\n return serializePhase;\n } else if (phase === \"Deserialize\") {\n return deserializePhase;\n } else if (phase === \"Sign\") {\n return signPhase;\n } else {\n return noPhase;\n }\n }\n\n // First walk each policy and create a node to track metadata.\n for (const descriptor of this._policies) {\n const policy = descriptor.policy;\n const options = descriptor.options;\n const policyName = policy.name;\n if (policyMap.has(policyName)) {\n throw new Error(\"Duplicate policy names not allowed in pipeline\");\n }\n const node: PolicyGraphNode = {\n policy,\n dependsOn: new Set(),\n dependants: new Set(),\n };\n if (options.afterPhase) {\n node.afterPhase = getPhase(options.afterPhase);\n node.afterPhase.hasAfterPolicies = true;\n }\n policyMap.set(policyName, node);\n const phase = getPhase(options.phase);\n phase.policies.add(node);\n }\n\n // Now that each policy has a node, connect dependency references.\n for (const descriptor of this._policies) {\n const { policy, options } = descriptor;\n const policyName = policy.name;\n const node = policyMap.get(policyName);\n if (!node) {\n throw new Error(`Missing node for policy ${policyName}`);\n }\n\n if (options.afterPolicies) {\n for (const afterPolicyName of options.afterPolicies) {\n const afterNode = policyMap.get(afterPolicyName);\n if (afterNode) {\n // Linking in both directions helps later\n // when we want to notify dependants.\n node.dependsOn.add(afterNode);\n afterNode.dependants.add(node);\n }\n }\n }\n if (options.beforePolicies) {\n for (const beforePolicyName of options.beforePolicies) {\n const beforeNode = policyMap.get(beforePolicyName);\n if (beforeNode) {\n // To execute before another node, make it\n // depend on the current node.\n beforeNode.dependsOn.add(node);\n node.dependants.add(beforeNode);\n }\n }\n }\n }\n\n function walkPhase(phase: Phase): void {\n phase.hasRun = true;\n // Sets iterate in insertion order\n for (const node of phase.policies) {\n if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {\n // If this node is waiting on a phase to complete,\n // we need to skip it for now.\n // Even if the phase is empty, we should wait for it\n // to be walked to avoid re-ordering policies.\n continue;\n }\n if (node.dependsOn.size === 0) {\n // If there's nothing else we're waiting for, we can\n // add this policy to the result list.\n result.push(node.policy);\n // Notify anything that depends on this policy that\n // the policy has been scheduled.\n for (const dependant of node.dependants) {\n dependant.dependsOn.delete(node);\n }\n policyMap.delete(node.policy.name);\n phase.policies.delete(node);\n }\n }\n }\n\n function walkPhases(): void {\n for (const phase of orderedPhases) {\n walkPhase(phase);\n // if the phase isn't complete\n if (phase.policies.size > 0 && phase !== noPhase) {\n if (!noPhase.hasRun) {\n // Try running noPhase to see if that unblocks this phase next tick.\n // This can happen if a phase that happens before noPhase\n // is waiting on a noPhase policy to complete.\n walkPhase(noPhase);\n }\n // Don't proceed to the next phase until this phase finishes.\n return;\n }\n\n if (phase.hasAfterPolicies) {\n // Run any policies unblocked by this phase\n walkPhase(noPhase);\n }\n }\n }\n\n // Iterate until we've put every node in the result list.\n let iteration = 0;\n while (policyMap.size > 0) {\n iteration++;\n const initialResultLength = result.length;\n // Keep walking each phase in order until we can order every node.\n walkPhases();\n // The result list *should* get at least one larger each time\n // after the first full pass.\n // Otherwise, we're going to loop forever.\n if (result.length <= initialResultLength && iteration > 1) {\n throw new Error(\"Cannot satisfy policy dependencies due to requirements cycle.\");\n }\n }\n\n return result;\n }\n}\n\n/**\n * Creates a totally empty pipeline.\n * Useful for testing or creating a custom one.\n */\nexport function createEmptyPipeline(): Pipeline {\n return HttpPipeline.create();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js new file mode 100644 index 0000000..5a6d3d2 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createHttpHeaders } from "./httpHeaders"; +import { generateUuid } from "./util/uuid"; +class PipelineRequestImpl { + constructor(options) { + var _a, _b, _c, _d, _e, _f, _g; + this.url = options.url; + this.body = options.body; + this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders(); + this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; + this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; + this.formData = options.formData; + this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; + this.abortSignal = options.abortSignal; + this.tracingOptions = options.tracingOptions; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || generateUuid(); + this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; + this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; + } +} +/** + * Creates a new pipeline request with the given options. + * This method is to allow for the easy setting of default values and not required. + * @param options - The options to create the request with. + */ +export function createPipelineRequest(options) { + return new PipelineRequestImpl(options); +} +//# sourceMappingURL=pipelineRequest.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js.map new file mode 100644 index 0000000..d6659ea --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/pipelineRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pipelineRequest.js","sourceRoot":"","sources":["../../src/pipelineRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAWlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAmG3C,MAAM,mBAAmB;IAoBvB,YAAY,OAA+B;;QACzC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,iBAAiB,EAAE,CAAC;QACtD,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,KAAK,CAAC;QACtC,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,CAAC,CAAC;QACpC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,MAAA,OAAO,CAAC,gBAAgB,mCAAI,KAAK,CAAC;QAC1D,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;QACnE,IAAI,CAAC,eAAe,GAAG,MAAA,OAAO,CAAC,eAAe,mCAAI,KAAK,CAAC;QACxD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;QAC7C,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;QACjD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,YAAY,EAAE,CAAC;QACrD,IAAI,CAAC,uBAAuB,GAAG,MAAA,OAAO,CAAC,uBAAuB,mCAAI,KAAK,CAAC;QACxE,IAAI,CAAC,oBAAoB,GAAG,MAAA,OAAO,CAAC,oBAAoB,mCAAI,KAAK,CAAC;IACpE,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAA+B;IACnE,OAAO,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n FormDataMap,\n HttpHeaders,\n HttpMethods,\n PipelineRequest,\n ProxySettings,\n RequestBodyType,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { generateUuid } from \"./util/uuid\";\nimport { OperationTracingOptions } from \"@azure/core-tracing\";\n\n/**\n * Settings to initialize a request.\n * Almost equivalent to Partial, but url is mandatory.\n */\nexport interface PipelineRequestOptions {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method?: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers?: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout?: number;\n\n /**\n * If credentials (cookies) should be sent along during an XHR.\n * Defaults to false.\n */\n withCredentials?: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId?: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n */\n streamResponseStatusCodes?: Set;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable use of the Streams API. If this option is set and streaming is used\n * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of\n * `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used to create a span when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n}\n\nclass PipelineRequestImpl implements PipelineRequest {\n public url: string;\n public method: HttpMethods;\n public headers: HttpHeaders;\n public timeout: number;\n public withCredentials: boolean;\n public body?: RequestBodyType;\n public formData?: FormDataMap;\n public streamResponseStatusCodes?: Set;\n public enableBrowserStreams: boolean;\n\n public proxySettings?: ProxySettings;\n public disableKeepAlive: boolean;\n public abortSignal?: AbortSignalLike;\n public requestId: string;\n public tracingOptions?: OperationTracingOptions;\n public allowInsecureConnection?: boolean;\n public onUploadProgress?: (progress: TransferProgressEvent) => void;\n public onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n constructor(options: PipelineRequestOptions) {\n this.url = options.url;\n this.body = options.body;\n this.headers = options.headers ?? createHttpHeaders();\n this.method = options.method ?? \"GET\";\n this.timeout = options.timeout ?? 0;\n this.formData = options.formData;\n this.disableKeepAlive = options.disableKeepAlive ?? false;\n this.proxySettings = options.proxySettings;\n this.streamResponseStatusCodes = options.streamResponseStatusCodes;\n this.withCredentials = options.withCredentials ?? false;\n this.abortSignal = options.abortSignal;\n this.tracingOptions = options.tracingOptions;\n this.onUploadProgress = options.onUploadProgress;\n this.onDownloadProgress = options.onDownloadProgress;\n this.requestId = options.requestId || generateUuid();\n this.allowInsecureConnection = options.allowInsecureConnection ?? false;\n this.enableBrowserStreams = options.enableBrowserStreams ?? false;\n }\n}\n\n/**\n * Creates a new pipeline request with the given options.\n * This method is to allow for the easy setting of default values and not required.\n * @param options - The options to create the request with.\n */\nexport function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest {\n return new PipelineRequestImpl(options);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js new file mode 100644 index 0000000..57681d7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createTokenCycler } from "../util/tokenCycler"; +import { logger as coreLogger } from "../log"; +/** + * The programmatic identifier of the bearerTokenAuthenticationPolicy. + */ +export const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; +/** + * Default authorize request handler + */ +async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions, + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } +} +/** + * We will retrieve the challenge only if the response status code was 401, + * and if the response contained the header "WWW-Authenticate" with a non-empty value. + */ +function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; +} +/** + * A policy that can request a token from a TokenCredential implementation and + * then apply it to the Authorization header of a request as a Bearer token. + */ +export function bearerTokenAuthenticationPolicy(options) { + var _a; + const { credential, scopes, challengeCallbacks } = options; + const logger = options.logger || coreLogger; + const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks); + // This function encapsulates the entire process of reliably retrieving the token + // The options are left out of the public API until there's demand to configure this. + // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions` + // in order to pass through the `options` object. + const getAccessToken = credential + ? createTokenCycler(credential /* , options */) + : () => Promise.resolve(null); + return { + name: bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger, + }); + let response; + let error; + try { + response = await next(request); + } + catch (err) { + error = err; + response = err.response; + } + if (callbacks.authorizeRequestOnChallenge && + (response === null || response === void 0 ? void 0 : response.status) === 401 && + getChallenge(response)) { + // processes challenge + const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger, + }); + if (shouldSendRequest) { + return next(request); + } + } + if (error) { + throw error; + } + else { + return response; + } + }, + }; +} +//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js.map new file mode 100644 index 0000000..28571ba --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/bearerTokenAuthenticationPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerTokenAuthenticationPolicy.js","sourceRoot":"","sources":["../../../src/policies/bearerTokenAuthenticationPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,QAAQ,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,iCAAiC,CAAC;AA2FrF;;GAEG;AACH,KAAK,UAAU,uBAAuB,CAAC,OAAgC;IACrE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACpD,MAAM,eAAe,GAAoB;QACvC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE,OAAO,CAAC,cAAc;KACvC,CAAC;IACF,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAElE,IAAI,WAAW,EAAE;QACf,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;KAC7E;AACH,CAAC;AAED;;;GAGG;AACH,SAAS,YAAY,CAAC,QAA0B;IAC9C,MAAM,SAAS,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAC3D,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,SAAS,EAAE;QACxC,OAAO,SAAS,CAAC;KAClB;IACD,OAAO;AACT,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,+BAA+B,CAC7C,OAA+C;;IAE/C,MAAM,EAAE,UAAU,EAA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AAC,QAAQ,CAAC;aACzB;YAED,IACE,SAAS,CAAC,2BAA2B;gBACrC,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,MAAK,GAAG;gBACxB,YAAY,CAAC,QAAQ,CAAC,EACtB;gBACA,sBAAsB;gBACtB,MAAM,iBAAiB,GAAG,MAAM,SAAS,CAAC,2BAA2B,CAAC;oBACpE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;oBACjD,OAAO;oBACP,QAAQ;oBACR,cAAc;oBACd,MAAM;iBACP,CAAC,CAAC;gBAEH,IAAI,iBAAiB,EAAE;oBACrB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;iBACtB;aACF;YAED,IAAI,KAAK,EAAE;gBACT,MAAM,KAAK,CAAC;aACb;iBAAM;gBACL,OAAO,QAAQ,CAAC;aACjB;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { AzureLogger } from \"@azure/logger\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { createTokenCycler } from \"../util/tokenCycler\";\nimport { logger as coreLogger } from \"../log\";\n\n/**\n * The programmatic identifier of the bearerTokenAuthenticationPolicy.\n */\nexport const bearerTokenAuthenticationPolicyName = \"bearerTokenAuthenticationPolicy\";\n\n/**\n * Options sent to the authorizeRequest callback\n */\nexport interface AuthorizeRequestOptions {\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string[];\n /**\n * Function that retrieves either a cached access token or a new access token.\n */\n getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise;\n /**\n * Request that the policy is trying to fulfill.\n */\n request: PipelineRequest;\n /**\n * A logger, if one was sent through the HTTP pipeline.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Options sent to the authorizeRequestOnChallenge callback\n */\nexport interface AuthorizeRequestOnChallengeOptions {\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string[];\n /**\n * Function that retrieves either a cached access token or a new access token.\n */\n getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise;\n /**\n * Request that the policy is trying to fulfill.\n */\n request: PipelineRequest;\n /**\n * Response containing the challenge.\n */\n response: PipelineResponse;\n /**\n * A logger, if one was sent through the HTTP pipeline.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Options to override the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.\n */\nexport interface ChallengeCallbacks {\n /**\n * Allows for the authorization of the main request of this policy before it's sent.\n */\n authorizeRequest?(options: AuthorizeRequestOptions): Promise;\n /**\n * Allows to handle authentication challenges and to re-authorize the request.\n * The response containing the challenge is `options.response`.\n * If this method returns true, the underlying request will be sent once again.\n * The request may be modified before being sent.\n */\n authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise;\n}\n\n/**\n * Options to configure the bearerTokenAuthenticationPolicy\n */\nexport interface BearerTokenAuthenticationPolicyOptions {\n /**\n * The TokenCredential implementation that can supply the bearer token.\n */\n credential?: TokenCredential;\n /**\n * The scopes for which the bearer token applies.\n */\n scopes: string | string[];\n /**\n * Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.\n * If provided, it must contain at least the `authorizeRequestOnChallenge` method.\n * If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information.\n */\n challengeCallbacks?: ChallengeCallbacks;\n /**\n * A logger can be sent for debugging purposes.\n */\n logger?: AzureLogger;\n}\n\n/**\n * Default authorize request handler\n */\nasync function defaultAuthorizeRequest(options: AuthorizeRequestOptions): Promise {\n const { scopes, getAccessToken, request } = options;\n const getTokenOptions: GetTokenOptions = {\n abortSignal: request.abortSignal,\n tracingOptions: request.tracingOptions,\n };\n const accessToken = await getAccessToken(scopes, getTokenOptions);\n\n if (accessToken) {\n options.request.headers.set(\"Authorization\", `Bearer ${accessToken.token}`);\n }\n}\n\n/**\n * We will retrieve the challenge only if the response status code was 401,\n * and if the response contained the header \"WWW-Authenticate\" with a non-empty value.\n */\nfunction getChallenge(response: PipelineResponse): string | undefined {\n const challenge = response.headers.get(\"WWW-Authenticate\");\n if (response.status === 401 && challenge) {\n return challenge;\n }\n return;\n}\n\n/**\n * A policy that can request a token from a TokenCredential implementation and\n * then apply it to the Authorization header of a request as a Bearer token.\n */\nexport function bearerTokenAuthenticationPolicy(\n options: BearerTokenAuthenticationPolicyOptions\n): PipelinePolicy {\n const { credential, scopes, challengeCallbacks } = options;\n const logger = options.logger || coreLogger;\n const callbacks = {\n authorizeRequest: challengeCallbacks?.authorizeRequest ?? defaultAuthorizeRequest,\n authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge,\n // keep all other properties\n ...challengeCallbacks,\n };\n\n // This function encapsulates the entire process of reliably retrieving the token\n // The options are left out of the public API until there's demand to configure this.\n // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`\n // in order to pass through the `options` object.\n const getAccessToken = credential\n ? createTokenCycler(credential /* , options */)\n : () => Promise.resolve(null);\n\n return {\n name: bearerTokenAuthenticationPolicyName,\n /**\n * If there's no challenge parameter:\n * - It will try to retrieve the token using the cache, or the credential's getToken.\n * - Then it will try the next policy with or without the retrieved token.\n *\n * It uses the challenge parameters to:\n * - Skip a first attempt to get the token from the credential if there's no cached token,\n * since it expects the token to be retrievable only after the challenge.\n * - Prepare the outgoing request if the `prepareRequest` method has been provided.\n * - Send an initial request to receive the challenge if it fails.\n * - Process a challenge if the response contains it.\n * - Retrieve a token with the challenge information, then re-send the request.\n */\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (!request.url.toLowerCase().startsWith(\"https://\")) {\n throw new Error(\n \"Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.\"\n );\n }\n\n await callbacks.authorizeRequest({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n request,\n getAccessToken,\n logger,\n });\n\n let response: PipelineResponse;\n let error: Error | undefined;\n try {\n response = await next(request);\n } catch (err: any) {\n error = err;\n response = err.response;\n }\n\n if (\n callbacks.authorizeRequestOnChallenge &&\n response?.status === 401 &&\n getChallenge(response)\n ) {\n // processes challenge\n const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({\n scopes: Array.isArray(scopes) ? scopes : [scopes],\n request,\n response,\n getAccessToken,\n logger,\n });\n\n if (shouldSendRequest) {\n return next(request);\n }\n }\n\n if (error) {\n throw error;\n } else {\n return response;\n }\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js new file mode 100644 index 0000000..2b14e03 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/* + * NOTE: When moving this file, please update "browser" section in package.json + */ +const NotSupported = new Error("decompressResponsePolicy is not supported in browser environment"); +export const decompressResponsePolicyName = "decompressResponsePolicy"; +/** + * decompressResponsePolicy is not supported in the browser and attempting + * to use it will raise an error. + */ +export function decompressResponsePolicy() { + throw NotSupported; +} +//# sourceMappingURL=decompressResponsePolicy.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js.map new file mode 100644 index 0000000..81a241c --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decompressResponsePolicy.browser.js","sourceRoot":"","sources":["../../../src/policies/decompressResponsePolicy.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AAEH,MAAM,YAAY,GAAG,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;AAEnG,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;GAGG;AACH,MAAM,UAAU,wBAAwB;IACtC,MAAM,YAAY,CAAC;AACrB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n * NOTE: When moving this file, please update \"browser\" section in package.json\n */\n\nconst NotSupported = new Error(\"decompressResponsePolicy is not supported in browser environment\");\n\nexport const decompressResponsePolicyName = \"decompressResponsePolicy\";\n\n/**\n * decompressResponsePolicy is not supported in the browser and attempting\n * to use it will raise an error.\n */\nexport function decompressResponsePolicy(): never {\n throw NotSupported;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js new file mode 100644 index 0000000..40e4ac7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The programmatic identifier of the decompressResponsePolicy. + */ +export const decompressResponsePolicyName = "decompressResponsePolicy"; +/** + * A policy to enable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +export function decompressResponsePolicy() { + return { + name: decompressResponsePolicyName, + async sendRequest(request, next) { + // HEAD requests have no body + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); + }, + }; +} +//# sourceMappingURL=decompressResponsePolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js.map new file mode 100644 index 0000000..13aac89 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/decompressResponsePolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decompressResponsePolicy.js","sourceRoot":"","sources":["../../../src/policies/decompressResponsePolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;GAGG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,6BAA6B;YAC7B,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,EAAE;gBAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;aACxD;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the decompressResponsePolicy.\n */\nexport const decompressResponsePolicyName = \"decompressResponsePolicy\";\n\n/**\n * A policy to enable response decompression according to Accept-Encoding header\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding\n */\nexport function decompressResponsePolicy(): PipelinePolicy {\n return {\n name: decompressResponsePolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n // HEAD requests have no body\n if (request.method !== \"HEAD\") {\n request.headers.set(\"Accept-Encoding\", \"gzip,deflate\");\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js new file mode 100644 index 0000000..77317a5 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy"; +import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy"; +import { retryPolicy } from "./retryPolicy"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants"; +/** + * Name of the {@link defaultRetryPolicy} + */ +export const defaultRetryPolicyName = "defaultRetryPolicy"; +/** + * A policy that retries according to three strategies: + * - When the server sends a 429 response with a Retry-After header. + * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). + * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. + */ +export function defaultRetryPolicy(options = {}) { + var _a; + return { + name: defaultRetryPolicyName, + sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, + }).sendRequest, + }; +} +//# sourceMappingURL=defaultRetryPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js.map new file mode 100644 index 0000000..8fcd1ea --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/defaultRetryPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"defaultRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/defaultRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,oBAAoB,CAAC;AAO3D;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAqC,EAAE;;IACxE,OAAO;QACL,IAAI,EAAE,sBAAsB;QAC5B,WAAW,EAAE,WAAW,CAAC,CAAC,uBAAuB,EAAE,EAAE,wBAAwB,CAAC,OAAO,CAAC,CAAC,EAAE;YACvF,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CAAC,CAAC,WAAW;KACf,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRetryOptions } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link defaultRetryPolicy}\n */\nexport const defaultRetryPolicyName = \"defaultRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface DefaultRetryPolicyOptions extends PipelineRetryOptions {}\n\n/**\n * A policy that retries according to three strategies:\n * - When the server sends a 429 response with a Retry-After header.\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.\n */\nexport function defaultRetryPolicy(options: DefaultRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: defaultRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js new file mode 100644 index 0000000..a3161c0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy"; +import { retryPolicy } from "./retryPolicy"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants"; +/** + * The programmatic identifier of the exponentialRetryPolicy. + */ +export const exponentialRetryPolicyName = "exponentialRetryPolicy"; +/** + * A policy that attempts to retry requests while introducing an exponentially increasing delay. + * @param options - Options that configure retry logic. + */ +export function exponentialRetryPolicy(options = {}) { + var _a; + return retryPolicy([ + exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })), + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, + }); +} +//# sourceMappingURL=exponentialRetryPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js.map new file mode 100644 index 0000000..48c1be7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/exponentialRetryPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exponentialRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/exponentialRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,wBAAwB,CAAC;AAyBnE;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;;IAE3C,OAAO,WAAW,CAChB;QACE,wBAAwB,iCACnB,OAAO,KACV,kBAAkB,EAAE,IAAI,IACxB;KACH,EACD;QACE,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;KAC7D,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * The programmatic identifier of the exponentialRetryPolicy.\n */\nexport const exponentialRetryPolicyName = \"exponentialRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ExponentialRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A policy that attempts to retry requests while introducing an exponentially increasing delay.\n * @param options - Options that configure retry logic.\n */\nexport function exponentialRetryPolicy(\n options: ExponentialRetryPolicyOptions = {}\n): PipelinePolicy {\n return retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreSystemErrors: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js new file mode 100644 index 0000000..393bfe0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The programmatic identifier of the formDataPolicy. + */ +export const formDataPolicyName = "formDataPolicy"; +/** + * A policy that encodes FormData on the request into the body. + */ +export function formDataPolicy() { + return { + name: formDataPolicyName, + async sendRequest(request, next) { + if (request.formData) { + const formData = request.formData; + const requestForm = new FormData(); + for (const formKey of Object.keys(formData)) { + const formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (const subValue of formValue) { + requestForm.append(formKey, subValue); + } + } + else { + requestForm.append(formKey, formValue); + } + } + request.body = requestForm; + request.formData = undefined; + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = new URLSearchParams(requestForm).toString(); + } + else if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + // browser will automatically apply a suitable content-type header + request.headers.delete("Content-Type"); + } + } + return next(request); + }, + }; +} +//# sourceMappingURL=formDataPolicy.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js.map new file mode 100644 index 0000000..ae73969 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formDataPolicy.browser.js","sourceRoot":"","sources":["../../../src/policies/formDataPolicy.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAEnD;;G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F,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = \"formDataPolicy\";\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return {\n name: formDataPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (request.formData) {\n const formData = request.formData;\n const requestForm = new FormData();\n for (const formKey of Object.keys(formData)) {\n const formValue = formData[formKey];\n if (Array.isArray(formValue)) {\n for (const subValue of formValue) {\n requestForm.append(formKey, subValue);\n }\n } else {\n requestForm.append(formKey, formValue);\n }\n }\n\n request.body = requestForm;\n request.formData = undefined;\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1) {\n request.body = new URLSearchParams(requestForm as any).toString();\n } else if (contentType && contentType.indexOf(\"multipart/form-data\") !== -1) {\n // browser will automatically apply a suitable content-type header\n request.headers.delete(\"Content-Type\");\n }\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js new file mode 100644 index 0000000..4b492b5 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import FormData from "form-data"; +/** + * The programmatic identifier of the formDataPolicy. + */ +export const formDataPolicyName = "formDataPolicy"; +/** + * A policy that encodes FormData on the request into the body. + */ +export function formDataPolicy() { + return { + name: formDataPolicyName, + async sendRequest(request, next) { + if (request.formData) { + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + request.formData = undefined; + } + else { + await prepareFormData(request.formData, request); + } + } + return next(request); + }, + }; +} +function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } + else { + urlSearchParams.append(key, value.toString()); + } + } + return urlSearchParams.toString(); +} +async function prepareFormData(formData, request) { + const requestForm = new FormData(); + for (const formKey of Object.keys(formData)) { + const formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (const subValue of formValue) { + requestForm.append(formKey, subValue); + } + } + else { + requestForm.append(formKey, formValue); + } + } + request.body = requestForm; + request.formData = undefined; + const contentType = request.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + request.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); + } + try { + const contentLength = await new Promise((resolve, reject) => { + requestForm.getLength((err, length) => { + if (err) { + reject(err); + } + else { + resolve(length); + } + }); + }); + request.headers.set("Content-Length", contentLength); + } + catch (e) { + // ignore setting the length if this fails + } +} +//# sourceMappingURL=formDataPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js.map new file mode 100644 index 0000000..38e12fa --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/formDataPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formDataPolicy.js","sourceRoot":"","sources":["../../../src/policies/formDataPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,QAAQ,MAAM,WAAW,CAAC;AAIjC;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAEnD;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,O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\";\nimport { FormDataMap, PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = \"formDataPolicy\";\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return {\n name: formDataPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (request.formData) {\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1) {\n request.body = wwwFormUrlEncode(request.formData);\n request.formData = undefined;\n } else {\n await prepareFormData(request.formData, request);\n }\n }\n return next(request);\n },\n };\n}\n\nfunction wwwFormUrlEncode(formData: FormDataMap): string {\n const urlSearchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(formData)) {\n if (Array.isArray(value)) {\n for (const subValue of value) {\n urlSearchParams.append(key, subValue.toString());\n }\n } else {\n urlSearchParams.append(key, value.toString());\n }\n }\n return urlSearchParams.toString();\n}\n\nasync function prepareFormData(formData: FormDataMap, request: PipelineRequest): Promise {\n const requestForm = new FormData();\n for (const formKey of Object.keys(formData)) {\n const formValue = formData[formKey];\n if (Array.isArray(formValue)) {\n for (const subValue of formValue) {\n requestForm.append(formKey, subValue);\n }\n } else {\n requestForm.append(formKey, formValue);\n }\n }\n\n request.body = requestForm;\n request.formData = undefined;\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"multipart/form-data\") !== -1) {\n request.headers.set(\n \"Content-Type\",\n `multipart/form-data; boundary=${requestForm.getBoundary()}`\n );\n }\n try {\n const contentLength = await new Promise((resolve, reject) => {\n requestForm.getLength((err, length) => {\n if (err) {\n reject(err);\n } else {\n resolve(length);\n }\n });\n });\n request.headers.set(\"Content-Length\", contentLength);\n } catch (e: any) {\n // ignore setting the length if this fails\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js new file mode 100644 index 0000000..26576bc --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { logger as coreLogger } from "../log"; +import { Sanitizer } from "../util/sanitizer"; +/** + * The programmatic identifier of the logPolicy. + */ +export const logPolicyName = "logPolicy"; +/** + * A policy that logs all requests and responses. + * @param options - Options to configure logPolicy. + */ +export function logPolicy(options = {}) { + var _a; + const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : coreLogger.info; + const sanitizer = new Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters, + }); + return { + name: logPolicyName, + async sendRequest(request, next) { + if (!logger.enabled) { + return next(request); + } + logger(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger(`Response status code: ${response.status}`); + logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + return response; + }, + }; +} +//# sourceMappingURL=logPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js.map new file mode 100644 index 0000000..1c1e2d5 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/logPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logPolicy.js","sourceRoot":"","sources":["../../../src/policies/logPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAC;AA4BzC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;;IACtD,MAAM,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,UAAU,CAAC,IAAI,CAAC;IACjD,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;QAC9B,4BAA4B,EAAE,OAAO,CAAC,4BAA4B;QAClE,gCAAgC,EAAE,OAAO,CAAC,gCAAgC;KAC3E,CAAC,CAAC;IACH,OAAO;QACL,IAAI,EAAE,aAAa;QACnB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;gBACnB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;aACtB;YAED,MAAM,CAAC,YAAY,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAElD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC;YAErC,MAAM,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,MAAM,CAAC,YAAY,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAE3D,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Debugger } from \"@azure/logger\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { logger as coreLogger } from \"../log\";\nimport { Sanitizer } from \"../util/sanitizer\";\n\n/**\n * The programmatic identifier of the logPolicy.\n */\nexport const logPolicyName = \"logPolicy\";\n\n/**\n * Options to configure the logPolicy.\n */\nexport interface LogPolicyOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n\n /**\n * The log function to use for writing pipeline logs.\n * Defaults to core-http's built-in logger.\n * Compatible with the `debug` library.\n */\n logger?: Debugger;\n}\n\n/**\n * A policy that logs all requests and responses.\n * @param options - Options to configure logPolicy.\n */\nexport function logPolicy(options: LogPolicyOptions = {}): PipelinePolicy {\n const logger = options.logger ?? coreLogger.info;\n const sanitizer = new Sanitizer({\n additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,\n additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,\n });\n return {\n name: logPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (!logger.enabled) {\n return next(request);\n }\n\n logger(`Request: ${sanitizer.sanitize(request)}`);\n\n const response = await next(request);\n\n logger(`Response status code: ${response.status}`);\n logger(`Headers: ${sanitizer.sanitize(response.headers)}`);\n\n return response;\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js new file mode 100644 index 0000000..3b1fa6f --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The programmatic identifier of the ndJsonPolicy. + */ +export const ndJsonPolicyName = "ndJsonPolicy"; +/** + * ndJsonPolicy is a policy used to control keep alive settings for every request. + */ +export function ndJsonPolicy() { + return { + name: ndJsonPolicyName, + async sendRequest(request, next) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return next(request); + }, + }; +} +//# sourceMappingURL=ndJsonPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js.map new file mode 100644 index 0000000..246e2e6 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/ndJsonPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ndJsonPolicy.js","sourceRoot":"","sources":["../../../src/policies/ndJsonPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAE/C;;GAEG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,4DAA4D;YAC5D,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;gBACpE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACtC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;oBACvB,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;iBACzE;aACF;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the ndJsonPolicy.\n */\nexport const ndJsonPolicyName = \"ndJsonPolicy\";\n\n/**\n * ndJsonPolicy is a policy used to control keep alive settings for every request.\n */\nexport function ndJsonPolicy(): PipelinePolicy {\n return {\n name: ndJsonPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n // There currently isn't a good way to bypass the serializer\n if (typeof request.body === \"string\" && request.body.startsWith(\"[\")) {\n const body = JSON.parse(request.body);\n if (Array.isArray(body)) {\n request.body = body.map((item) => JSON.stringify(item) + \"\\n\").join(\"\");\n }\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js new file mode 100644 index 0000000..e10ab5e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/* + * NOTE: When moving this file, please update "browser" section in package.json + */ +const NotSupported = new Error("proxyPolicy is not supported in browser environment"); +export const proxyPolicyName = "proxyPolicy"; +export function getDefaultProxySettings() { + throw NotSupported; +} +/** + * proxyPolicy is not supported in the browser and attempting + * to use it will raise an error. + */ +export function proxyPolicy() { + throw NotSupported; +} +/** + * A function to reset the cached agents. + * proxyPolicy is not supported in the browser and attempting + * to use it will raise an error. + * @internal + */ +export function resetCachedProxyAgents() { + throw NotSupported; +} +//# sourceMappingURL=proxyPolicy.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js.map new file mode 100644 index 0000000..f30f00d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyPolicy.browser.js","sourceRoot":"","sources":["../../../src/policies/proxyPolicy.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AAEH,MAAM,YAAY,GAAG,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;AAEtF,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAC;AAE7C,MAAM,UAAU,uBAAuB;IACrC,MAAM,YAAY,CAAC;AACrB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,YAAY,CAAC;AACrB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB;IACpC,MAAM,YAAY,CAAC;AACrB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n * NOTE: When moving this file, please update \"browser\" section in package.json\n */\n\nconst NotSupported = new Error(\"proxyPolicy is not supported in browser environment\");\n\nexport const proxyPolicyName = \"proxyPolicy\";\n\nexport function getDefaultProxySettings(): never {\n throw NotSupported;\n}\n\n/**\n * proxyPolicy is not supported in the browser and attempting\n * to use it will raise an error.\n */\nexport function proxyPolicy(): never {\n throw NotSupported;\n}\n\n/**\n * A function to reset the cached agents.\n * proxyPolicy is not supported in the browser and attempting\n * to use it will raise an error.\n * @internal\n */\nexport function resetCachedProxyAgents(): never {\n throw NotSupported;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js new file mode 100644 index 0000000..512da41 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { HttpsProxyAgent } from "https-proxy-agent"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { logger } from "../log"; +const HTTPS_PROXY = "HTTPS_PROXY"; +const HTTP_PROXY = "HTTP_PROXY"; +const ALL_PROXY = "ALL_PROXY"; +const NO_PROXY = "NO_PROXY"; +/** + * The programmatic identifier of the proxyPolicy. + */ +export const proxyPolicyName = "proxyPolicy"; +/** + * Stores the patterns specified in NO_PROXY environment variable. + * @internal + */ +export const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); +function getEnvironmentValue(name) { + if (process.env[name]) { + return process.env[name]; + } + else if (process.env[name.toLowerCase()]) { + return process.env[name.toLowerCase()]; + } + return undefined; +} +function loadEnvironmentProxyValue() { + if (!process) { + return undefined; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn't have the proxy settings set. + * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 + */ +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } + else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } + else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; +} +export function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length); + } + return []; +} +/** + * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy. + * If no argument is given, it attempts to parse a proxy URL from the environment + * variables `HTTPS_PROXY` or `HTTP_PROXY`. + * @param proxyUrl - The url of the proxy to use. May contain authentication information. + */ +export function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return undefined; + } + } + const parsedUrl = new URL(proxyUrl); + const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password, + }; +} +/** + * @internal + */ +export function getProxyAgentOptions(proxySettings, { headers, tlsSettings }) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(proxySettings.host); + } + catch (_error) { + throw new Error(`Expecting a valid host string in proxy settings, but found "${proxySettings.host}".`); + } + if (tlsSettings) { + logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + const proxyAgentOptions = { + hostname: parsedProxyUrl.hostname, + port: proxySettings.port, + protocol: parsedProxyUrl.protocol, + headers: headers.toJSON(), + }; + if (proxySettings.username && proxySettings.password) { + proxyAgentOptions.auth = `${proxySettings.username}:${proxySettings.password}`; + } + else if (proxySettings.username) { + proxyAgentOptions.auth = `${proxySettings.username}`; + } + return proxyAgentOptions; +} +function setProxyAgentOnRequest(request, cachedAgents) { + // Custom Agent should take precedence so if one is present + // we should skip to avoid overwriting it. + if (request.agent) { + return; + } + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + const proxySettings = request.proxySettings; + if (proxySettings) { + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + const proxyAgentOptions = getProxyAgentOptions(proxySettings, request); + cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyAgentOptions); + } + request.agent = cachedAgents.httpProxyAgent; + } + else { + if (!cachedAgents.httpsProxyAgent) { + const proxyAgentOptions = getProxyAgentOptions(proxySettings, request); + cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyAgentOptions); + } + request.agent = cachedAgents.httpsProxyAgent; + } + } +} +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +export function proxyPolicy(proxySettings = getDefaultProxySettings(), options) { + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); + } + const cachedAgents = {}; + return { + name: proxyPolicyName, + async sendRequest(request, next) { + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) { + request.proxySettings = proxySettings; + } + if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents); + } + return next(request); + }, + }; +} +//# sourceMappingURL=proxyPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js.map new file mode 100644 index 0000000..6044a09 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/proxyPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyPolicy.js","sourceRoot":"","sources":["../../../src/policies/proxyPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,eAAe,EAA0B,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAyB,MAAM,kBAAkB,CAAC;AAGzE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,WAAW,GAAG,aAAa,CAAC;AAClC,MAAM,UAAU,GAAG,YAAY,CAAC;AAChC,MAAM,SAAS,GAAG,WAAW,CAAC;AAC9B,MAAM,QAAQ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AAe;QACrB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;;YAC3D,IACE,CAAC,OAAO,CAAC,aAAa;gBACtB,CAAC,UAAU,CACT,OAAO,CAAC,GAAG,EACX,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,mCAAI,iBAAiB,EAC/C,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,EAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,iBAAiB,CAC3D,EACD;gBACA,OAAO,CAAC,aAAa,GAAG,aAAa,CAAC;aACvC;YAED,IAAI,OAAO,CAAC,aAAa,EAAE;gBACzB,sBAAsB,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;aAC/C;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as http from \"http\";\nimport * as https from \"https\";\nimport { HttpsProxyAgent, HttpsProxyAgentOptions } from \"https-proxy-agent\";\nimport { HttpProxyAgent, HttpProxyAgentOptions } from \"http-proxy-agent\";\nimport { PipelineRequest, PipelineResponse, ProxySettings, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { logger } from \"../log\";\n\nconst HTTPS_PROXY = \"HTTPS_PROXY\";\nconst HTTP_PROXY = \"HTTP_PROXY\";\nconst ALL_PROXY = \"ALL_PROXY\";\nconst NO_PROXY = \"NO_PROXY\";\n\n/**\n * The programmatic identifier of the proxyPolicy.\n */\nexport const proxyPolicyName = \"proxyPolicy\";\n\n/**\n * Stores the patterns specified in NO_PROXY environment variable.\n * @internal\n */\nexport const globalNoProxyList: string[] = [];\nlet noProxyListLoaded: boolean = false;\n\n/** A cache of whether a host should bypass the proxy. */\nconst globalBypassedMap: Map = new Map();\n\nfunction getEnvironmentValue(name: string): string | undefined {\n if (process.env[name]) {\n return process.env[name];\n } else if (process.env[name.toLowerCase()]) {\n return process.env[name.toLowerCase()];\n }\n return undefined;\n}\n\nfunction loadEnvironmentProxyValue(): string | undefined {\n if (!process) {\n return undefined;\n }\n\n const httpsProxy = getEnvironmentValue(HTTPS_PROXY);\n const allProxy = getEnvironmentValue(ALL_PROXY);\n const httpProxy = getEnvironmentValue(HTTP_PROXY);\n\n return httpsProxy || allProxy || httpProxy;\n}\n\n/**\n * Check whether the host of a given `uri` matches any pattern in the no proxy list.\n * If there's a match, any request sent to the same host shouldn't have the proxy settings set.\n * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210\n */\nfunction isBypassed(\n uri: string,\n noProxyList: string[],\n bypassedMap?: Map\n): boolean | undefined {\n if (noProxyList.length === 0) {\n return false;\n }\n const host = new URL(uri).hostname;\n if (bypassedMap?.has(host)) {\n return bypassedMap.get(host);\n }\n let isBypassedFlag = false;\n for (const pattern of noProxyList) {\n if (pattern[0] === \".\") {\n // This should match either domain it self or any subdomain or host\n // .foo.com will match foo.com it self or *.foo.com\n if (host.endsWith(pattern)) {\n isBypassedFlag = true;\n } else {\n if (host.length === pattern.length - 1 && host === pattern.slice(1)) {\n isBypassedFlag = true;\n }\n }\n } else {\n if (host === pattern) {\n isBypassedFlag = true;\n }\n }\n }\n bypassedMap?.set(host, isBypassedFlag);\n return isBypassedFlag;\n}\n\nexport function loadNoProxy(): string[] {\n const noProxy = getEnvironmentValue(NO_PROXY);\n noProxyListLoaded = true;\n if (noProxy) {\n return noProxy\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length);\n }\n\n return [];\n}\n\n/**\n * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.\n * If no argument is given, it attempts to parse a proxy URL from the environment\n * variables `HTTPS_PROXY` or `HTTP_PROXY`.\n * @param proxyUrl - The url of the proxy to use. May contain authentication information.\n */\nexport function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined {\n if (!proxyUrl) {\n proxyUrl = loadEnvironmentProxyValue();\n if (!proxyUrl) {\n return undefined;\n }\n }\n\n const parsedUrl = new URL(proxyUrl);\n const schema = parsedUrl.protocol ? parsedUrl.protocol + \"//\" : \"\";\n return {\n host: schema + parsedUrl.hostname,\n port: Number.parseInt(parsedUrl.port || \"80\"),\n username: parsedUrl.username,\n password: parsedUrl.password,\n };\n}\n\n/**\n * @internal\n */\nexport function getProxyAgentOptions(\n proxySettings: ProxySettings,\n { headers, tlsSettings }: PipelineRequest\n): HttpProxyAgentOptions {\n let parsedProxyUrl: URL;\n try {\n parsedProxyUrl = new URL(proxySettings.host);\n } catch (_error) {\n throw new Error(\n `Expecting a valid host string in proxy settings, but found \"${proxySettings.host}\".`\n );\n }\n\n if (tlsSettings) {\n logger.warning(\n \"TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.\"\n );\n }\n\n const proxyAgentOptions: HttpsProxyAgentOptions = {\n hostname: parsedProxyUrl.hostname,\n port: proxySettings.port,\n protocol: parsedProxyUrl.protocol,\n headers: headers.toJSON(),\n };\n if (proxySettings.username && proxySettings.password) {\n proxyAgentOptions.auth = `${proxySettings.username}:${proxySettings.password}`;\n } else if (proxySettings.username) {\n proxyAgentOptions.auth = `${proxySettings.username}`;\n }\n return proxyAgentOptions;\n}\n\nfunction setProxyAgentOnRequest(request: PipelineRequest, cachedAgents: CachedAgents): void {\n // Custom Agent should take precedence so if one is present\n // we should skip to avoid overwriting it.\n if (request.agent) {\n return;\n }\n\n const url = new URL(request.url);\n\n const isInsecure = url.protocol !== \"https:\";\n\n const proxySettings = request.proxySettings;\n if (proxySettings) {\n if (isInsecure) {\n if (!cachedAgents.httpProxyAgent) {\n const proxyAgentOptions = getProxyAgentOptions(proxySettings, request);\n cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyAgentOptions);\n }\n request.agent = cachedAgents.httpProxyAgent;\n } else {\n if (!cachedAgents.httpsProxyAgent) {\n const proxyAgentOptions = getProxyAgentOptions(proxySettings, request);\n cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyAgentOptions);\n }\n request.agent = cachedAgents.httpsProxyAgent;\n }\n }\n}\n\ninterface CachedAgents {\n httpsProxyAgent?: https.Agent;\n httpProxyAgent?: http.Agent;\n}\n\n/**\n * A policy that allows one to apply proxy settings to all requests.\n * If not passed static settings, they will be retrieved from the HTTPS_PROXY\n * or HTTP_PROXY environment variables.\n * @param proxySettings - ProxySettings to use on each request.\n * @param options - additional settings, for example, custom NO_PROXY patterns\n */\nexport function proxyPolicy(\n proxySettings = getDefaultProxySettings(),\n options?: {\n /** a list of patterns to override those loaded from NO_PROXY environment variable. */\n customNoProxyList?: string[];\n }\n): PipelinePolicy {\n if (!noProxyListLoaded) {\n globalNoProxyList.push(...loadNoProxy());\n }\n\n const cachedAgents: CachedAgents = {};\n\n return {\n name: proxyPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (\n !request.proxySettings &&\n !isBypassed(\n request.url,\n options?.customNoProxyList ?? globalNoProxyList,\n options?.customNoProxyList ? undefined : globalBypassedMap\n )\n ) {\n request.proxySettings = proxySettings;\n }\n\n if (request.proxySettings) {\n setProxyAgentOnRequest(request, cachedAgents);\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js new file mode 100644 index 0000000..302a1b8 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The programmatic identifier of the redirectPolicy. + */ +export const redirectPolicyName = "redirectPolicy"; +/** + * Methods that are allowed to follow redirects 301 and 302 + */ +const allowedRedirect = ["GET", "HEAD"]; +/** + * A policy to follow Location headers from the server in order + * to support server-side redirection. + * In the browser, this policy is not used. + * @param options - Options to control policy behavior. + */ +export function redirectPolicy(options = {}) { + const { maxRetries = 20 } = options; + return { + name: redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries); + }, + }; +} +async function handleRedirect(next, response, maxRetries, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && + (status === 300 || + (status === 301 && allowedRedirect.includes(request.method)) || + (status === 302 && allowedRedirect.includes(request.method)) || + (status === 303 && request.method === "POST") || + status === 307) && + currentRetries < maxRetries) { + const url = new URL(locationHeader, request.url); + request.url = url.toString(); + // POST request with Status code 303 should be converted into a + // redirected GET request if the redirect url is present in the location header + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, currentRetries + 1); + } + return response; +} +//# sourceMappingURL=redirectPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js.map new file mode 100644 index 0000000..6f4596d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/redirectPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"redirectPolicy.js","sourceRoot":"","sources":["../../../src/policies/redirectPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AAEnD;;GAEG;AACH,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AAaxC;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,UAAiC,EAAE;IAChE,MAAM,EAAE,UAAU,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC;IACpC,OAAO;QACL,IAAI,EAAE,kBAAkB;QACxB,KAAK,CAAC,WAA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AM,IAAI,CAAC,OAAO,CAAC,CAAC;QAChC,OAAO,cAAc,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,cAAc,GAAG,CAAC,CAAC,CAAC;KAClE;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the redirectPolicy.\n */\nexport const redirectPolicyName = \"redirectPolicy\";\n\n/**\n * Methods that are allowed to follow redirects 301 and 302\n */\nconst allowedRedirect = [\"GET\", \"HEAD\"];\n\n/**\n * Options for how redirect responses are handled.\n */\nexport interface RedirectPolicyOptions {\n /**\n * The maximum number of times the redirect URL will be tried before\n * failing. Defaults to 20.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy to follow Location headers from the server in order\n * to support server-side redirection.\n * In the browser, this policy is not used.\n * @param options - Options to control policy behavior.\n */\nexport function redirectPolicy(options: RedirectPolicyOptions = {}): PipelinePolicy {\n const { maxRetries = 20 } = options;\n return {\n name: redirectPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n const response = await next(request);\n return handleRedirect(next, response, maxRetries);\n },\n };\n}\n\nasync function handleRedirect(\n next: SendRequest,\n response: PipelineResponse,\n maxRetries: number,\n currentRetries: number = 0\n): Promise {\n const { request, status, headers } = response;\n const locationHeader = headers.get(\"location\");\n if (\n locationHeader &&\n (status === 300 ||\n (status === 301 && allowedRedirect.includes(request.method)) ||\n (status === 302 && allowedRedirect.includes(request.method)) ||\n (status === 303 && request.method === \"POST\") ||\n status === 307) &&\n currentRetries < maxRetries\n ) {\n const url = new URL(locationHeader, request.url);\n request.url = url.toString();\n\n // POST request with Status code 303 should be converted into a\n // redirected GET request if the redirect url is present in the location header\n if (status === 303) {\n request.method = \"GET\";\n request.headers.delete(\"Content-Length\");\n delete request.body;\n }\n\n request.headers.delete(\"Authorization\");\n\n const res = await next(request);\n return handleRedirect(next, res, maxRetries, currentRetries + 1);\n }\n\n return response;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js new file mode 100644 index 0000000..ce8feb9 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { delay } from "../util/helpers"; +import { createClientLogger } from "@azure/logger"; +import { AbortError } from "@azure/abort-controller"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants"; +const retryPolicyLogger = createClientLogger("core-rest-pipeline retryPolicy"); +/** + * The programmatic identifier of the retryPolicy. + */ +const retryPolicyName = "retryPolicy"; +/** + * retryPolicy is a generic policy to enable retrying requests when certain conditions are met + */ +export function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) { + const logger = options.logger || retryPolicyLogger; + return { + name: retryPolicyName, + async sendRequest(request, next) { + var _a, _b; + let response; + let responseError; + let retryCount = -1; + // eslint-disable-next-line no-constant-condition + retryRequest: while (true) { + retryCount += 1; + response = undefined; + responseError = undefined; + try { + logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } + catch (e) { + logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + // RestErrors are valid targets for the retry strategies. + // If none of the retry strategies can work with them, they will be thrown later in this policy. + // If the received error is not a RestError, it is immediately thrown. + responseError = e; + if (!e || responseError.name !== "RestError") { + throw e; + } + response = responseError.response; + } + if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + logger.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new AbortError(); + throw abortError; + } + if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_POLICY_COUNT)) { + logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } + else if (response) { + return response; + } + else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || retryPolicyLogger; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError, + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } + // If all the retries skip and there's no response, + // we're still in the retry loop, so a new request will be sent + // until `maxRetries` is reached. + } + }, + }; +} +//# sourceMappingURL=retryPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js.map new file mode 100644 index 0000000..721b2e8 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/retryPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retryPolic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Y,EAAE;wBAC1B,cAAc,CAAC,IAAI,CAAC,SAAS,UAAU,YAAY,CAAC,CAAC;wBACrD,SAAS,cAAc,CAAC;qBACzB;oBAED,MAAM,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,GAAG,SAAS,CAAC;oBAE/D,IAAI,YAAY,EAAE;wBAChB,cAAc,CAAC,KAAK,CAClB,SAAS,UAAU,oBAAoB,QAAQ,CAAC,IAAI,gBAAgB,EACpE,YAAY,CACb,CAAC;wBACF,MAAM,YAAY,CAAC;qBACpB;oBAED,IAAI,cAAc,IAAI,cAAc,KAAK,CAAC,EAAE;wBAC1C,cAAc,CAAC,IAAI,CACjB,SAAS,UAAU,oBAAoB,QAAQ,CAAC,IAAI,kBAAkB,cAAc,EAAE,CACvF,CAAC;wBACF,MAAM,KAAK,CAAC,cAAc,EAAE,SAAS,EAAE,EAAE,WAAW,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;wBAC7E,SAAS,YAAY,CAAC;qBACvB;oBAED,IAAI,UAAU,EAAE;wBACd,cAAc,CAAC,IAAI,CACjB,SAAS,UAAU,oBAAoB,QAAQ,CAAC,IAAI,iBAAiB,UAAU,EAAE,CAClF,CAAC;wBACF,OAAO,CAAC,GAAG,GAAG,UAAU,CAAC;wBACzB,SAAS,YAAY,CAAC;qBACvB;iBACF;gBAED,IAAI,aAAa,EAAE;oBACjB,MAAM,CAAC,IAAI,CACT,+EAA+E,CAChF,CAAC;oBACF,MAAM,aAAa,CAAC;iBACrB;gBACD,IAAI,QAAQ,EAAE;oBACZ,MAAM,CAAC,IAAI,CACT,mFAAmF,CACpF,CAAC;oBACF,OAAO,QAAQ,CAAC;iBACjB;gBAED,mDAAmD;gBACnD,+DAA+D;gBAC/D,iCAAiC;aAClC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { delay } from \"../util/helpers\";\nimport { createClientLogger } from \"@azure/logger\";\nimport { RetryStrategy } from \"../retryStrategies/retryStrategy\";\nimport { RestError } from \"../restError\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport { AzureLogger } from \"@azure/logger\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\nconst retryPolicyLogger = createClientLogger(\"core-rest-pipeline retryPolicy\");\n\n/**\n * The programmatic identifier of the retryPolicy.\n */\nconst retryPolicyName = \"retryPolicy\";\n\n/**\n * Options to the {@link retryPolicy}\n */\nexport interface RetryPolicyOptions {\n /**\n * Maximum number of retries. If not specified, it will limit to 3 retries.\n */\n maxRetries?: number;\n /**\n * Logger. If it's not provided, a default logger is used.\n */\n logger?: AzureLogger;\n}\n\n/**\n * retryPolicy is a generic policy to enable retrying requests when certain conditions are met\n */\nexport function retryPolicy(\n strategies: RetryStrategy[],\n options: RetryPolicyOptions = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }\n): PipelinePolicy {\n const logger = options.logger || retryPolicyLogger;\n return {\n name: retryPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n let response: PipelineResponse | undefined;\n let responseError: RestError | undefined;\n let retryCount = -1;\n\n // eslint-disable-next-line no-constant-condition\n retryRequest: while (true) {\n retryCount += 1;\n response = undefined;\n responseError = undefined;\n\n try {\n logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);\n response = await next(request);\n logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);\n } catch (e: any) {\n logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);\n\n // RestErrors are valid targets for the retry strategies.\n // If none of the retry strategies can work with them, they will be thrown later in this policy.\n // If the received error is not a RestError, it is immediately thrown.\n responseError = e as RestError;\n if (!e || responseError.name !== \"RestError\") {\n throw e;\n }\n\n response = responseError.response;\n }\n\n if (request.abortSignal?.aborted) {\n logger.error(`Retry ${retryCount}: Request aborted.`);\n const abortError = new AbortError();\n throw abortError;\n }\n\n if (retryCount >= (options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT)) {\n logger.info(\n `Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`\n );\n if (responseError) {\n throw responseError;\n } else if (response) {\n return response;\n } else {\n throw new Error(\"Maximum retries reached with no response or error to throw\");\n }\n }\n\n logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);\n\n strategiesLoop: for (const strategy of strategies) {\n const strategyLogger = strategy.logger || retryPolicyLogger;\n strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);\n\n const modifiers = strategy.retry({\n retryCount,\n response,\n responseError,\n });\n\n if (modifiers.skipStrategy) {\n strategyLogger.info(`Retry ${retryCount}: Skipped.`);\n continue strategiesLoop;\n }\n\n const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;\n\n if (errorToThrow) {\n strategyLogger.error(\n `Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`,\n errorToThrow\n );\n throw errorToThrow;\n }\n\n if (retryAfterInMs || retryAfterInMs === 0) {\n strategyLogger.info(\n `Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`\n );\n await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });\n continue retryRequest;\n }\n\n if (redirectTo) {\n strategyLogger.info(\n `Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`\n );\n request.url = redirectTo;\n continue retryRequest;\n }\n }\n\n if (responseError) {\n logger.info(\n `None of the retry strategies could work with the received error. Throwing it.`\n );\n throw responseError;\n }\n if (response) {\n logger.info(\n `None of the retry strategies could work with the received response. Returning it.`\n );\n return response;\n }\n\n // If all the retries skip and there's no response,\n // we're still in the retry loop, so a new request will be sent\n // until `maxRetries` is reached.\n }\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js new file mode 100644 index 0000000..46baba4 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The programmatic identifier of the setClientRequestIdPolicy. + */ +export const setClientRequestIdPolicyName = "setClientRequestIdPolicy"; +/** + * Each PipelineRequest gets a unique id upon creation. + * This policy passes that unique id along via an HTTP header to enable better + * telemetry and tracing. + * @param requestIdHeaderName - The name of the header to pass the request ID to. + */ +export function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + }, + }; +} +//# sourceMappingURL=setClientRequestIdPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js.map new file mode 100644 index 0000000..8c7eb19 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/setClientRequestIdPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"setClientRequestIdPolicy.js","sourceRoot":"","sources":["../../../src/policies/setClientRequestIdPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,mBAAmB,GAAG,wBAAwB;IAE9C,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE;gBAC7C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;aAC7D;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\n\n/**\n * The programmatic identifier of the setClientRequestIdPolicy.\n */\nexport const setClientRequestIdPolicyName = \"setClientRequestIdPolicy\";\n\n/**\n * Each PipelineRequest gets a unique id upon creation.\n * This policy passes that unique id along via an HTTP header to enable better\n * telemetry and tracing.\n * @param requestIdHeaderName - The name of the header to pass the request ID to.\n */\nexport function setClientRequestIdPolicy(\n requestIdHeaderName = \"x-ms-client-request-id\"\n): PipelinePolicy {\n return {\n name: setClientRequestIdPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (!request.headers.has(requestIdHeaderName)) {\n request.headers.set(requestIdHeaderName, request.requestId);\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js new file mode 100644 index 0000000..4c4bca0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy"; +import { retryPolicy } from "./retryPolicy"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants"; +/** + * Name of the {@link systemErrorRetryPolicy} + */ +export const systemErrorRetryPolicyName = "systemErrorRetryPolicy"; +/** + * A retry policy that specifically seeks to handle errors in the + * underlying transport layer (e.g. DNS lookup failures) rather than + * retryable error codes from the server itself. + * @param options - Options that customize the policy. + */ +export function systemErrorRetryPolicy(options = {}) { + var _a; + return { + name: systemErrorRetryPolicyName, + sendRequest: retryPolicy([ + exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })), + ], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, + }).sendRequest, + }; +} +//# sourceMappingURL=systemErrorRetryPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js.map new file mode 100644 index 0000000..e8063ba --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/systemErrorRetryPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"systemErrorRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/systemErrorRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6CAA6C,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,wBAAwB,CAAC;AAyBnE;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;;IAE3C,OAAO;QACL,IAAI,EAAE,0BAA0B;QAChC,WAAW,EAAE,WAAW,CACtB;YACE,wBAAwB,iCACnB,OAAO,KACV,qBAAqB,EAAE,IAAI,IAC3B;SACH,EACD;YACE,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CACF,CAAC,WAAW;KACd,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link systemErrorRetryPolicy}\n */\nexport const systemErrorRetryPolicyName = \"systemErrorRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface SystemErrorRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A retry policy that specifically seeks to handle errors in the\n * underlying transport layer (e.g. DNS lookup failures) rather than\n * retryable error codes from the server itself.\n * @param options - Options that customize the policy.\n */\nexport function systemErrorRetryPolicy(\n options: SystemErrorRetryPolicyOptions = {}\n): PipelinePolicy {\n return {\n name: systemErrorRetryPolicyName,\n sendRequest: retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreHttpStatusCodes: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }\n ).sendRequest,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js new file mode 100644 index 0000000..e4b8e28 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy"; +import { retryPolicy } from "./retryPolicy"; +import { DEFAULT_RETRY_POLICY_COUNT } from "../constants"; +/** + * Name of the {@link throttlingRetryPolicy} + */ +export const throttlingRetryPolicyName = "throttlingRetryPolicy"; +/** + * A policy that retries when the server sends a 429 response with a Retry-After header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * + * @param options - Options that configure retry logic. + */ +export function throttlingRetryPolicy(options = {}) { + var _a; + return { + name: throttlingRetryPolicyName, + sendRequest: retryPolicy([throttlingRetryStrategy()], { + maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, + }).sendRequest, + }; +} +//# sourceMappingURL=throttlingRetryPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js.map new file mode 100644 index 0000000..b67feb7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/throttlingRetryPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"throttlingRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/throttlingRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,uBAAuB,CAAC;AAYjE;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,UAAwC,EAAE;;IAC9E,OAAO;QACL,IAAI,EAAE,yBAAyB;QAC/B,WAAW,EAAE,WAAW,CAAC,CAAC,uBAAuB,EAAE,CAAC,EAAE;YACpD,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CAAC,CAAC,WAAW;KACf,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy\";\nimport { retryPolicy } from \"./retryPolicy\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants\";\n\n/**\n * Name of the {@link throttlingRetryPolicy}\n */\nexport const throttlingRetryPolicyName = \"throttlingRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ThrottlingRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy that retries when the server sends a 429 response with a Retry-After header.\n *\n * To learn more, please refer to\n * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,\n * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and\n * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors\n *\n * @param options - Options that configure retry logic.\n */\nexport function throttlingRetryPolicy(options: ThrottlingRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: throttlingRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy()], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js new file mode 100644 index 0000000..67ce535 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Name of the TLS Policy + */ +export const tlsPolicyName = "tlsPolicy"; +/** + * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. + */ +export function tlsPolicy(tlsSettings) { + return { + name: tlsPolicyName, + sendRequest: async (req, next) => { + // Users may define a request tlsSettings, honor those over the client level one + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + }, + }; +} +//# sourceMappingURL=tlsPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js.map new file mode 100644 index 0000000..9d3f1be --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tlsPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tlsPolicy.js","sourceRoot":"","sources":["../../../src/policies/tlsPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAC;AAEzC;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,WAAyB;IACjD,OAAO;QACL,IAAI,EAAE,aAAa;QACnB,WAAW,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YAC/B,gFAAgF;YAChF,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE;gBACpB,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;aAC/B;YACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelinePolicy } from \"../pipeline\";\nimport { TlsSettings } from \"../interfaces\";\n\n/**\n * Name of the TLS Policy\n */\nexport const tlsPolicyName = \"tlsPolicy\";\n\n/**\n * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.\n */\nexport function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy {\n return {\n name: tlsPolicyName,\n sendRequest: async (req, next) => {\n // Users may define a request tlsSettings, honor those over the client level one\n if (!req.tlsSettings) {\n req.tlsSettings = tlsSettings;\n }\n return next(req);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js new file mode 100644 index 0000000..6c77e99 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createTracingClient, } from "@azure/core-tracing"; +import { SDK_VERSION } from "../constants"; +import { getUserAgentValue } from "../util/userAgent"; +import { logger } from "../log"; +import { getErrorMessage, isError } from "@azure/core-util"; +import { isRestError } from "../restError"; +/** + * The programmatic identifier of the tracingPolicy. + */ +export const tracingPolicyName = "tracingPolicy"; +/** + * A simple policy to create OpenTelemetry Spans for each request made by the pipeline + * that has SpanOptions with a parent. + * Requests made without a parent Span will not be recorded. + * @param options - Options to configure the telemetry logged by the tracing policy. + */ +export function tracingPolicy(options = {}) { + const userAgent = getUserAgentValue(options.userAgentPrefix); + const tracingClient = tryCreateTracingClient(); + return { + name: tracingPolicyName, + async sendRequest(request, next) { + var _a, _b; + if (!tracingClient || !((_a = request.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext)) { + return next(request); + } + const { span, tracingContext } = (_b = tryCreateSpan(tracingClient, request, userAgent)) !== null && _b !== void 0 ? _b : {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } + catch (err) { + tryProcessError(span, err); + throw err; + } + }, + }; +} +function tryCreateTracingClient() { + try { + return createTracingClient({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: SDK_VERSION, + }); + } + catch (e) { + logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`); + return undefined; + } +} +function tryCreateSpan(tracingClient, request, userAgent) { + try { + // As per spec, we do not need to differentiate between HTTP and HTTPS in span name. + const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes: { + "http.method": request.method, + "http.url": request.url, + requestId: request.requestId, + }, + }); + // If the span is not recording, don't do any more work. + if (!span.isRecording()) { + span.end(); + return undefined; + } + if (userAgent) { + span.setAttribute("http.user_agent", userAgent); + } + // set headers + const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } + catch (e) { + logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`); + return undefined; + } +} +function tryProcessError(span, error) { + try { + span.setStatus({ + status: "error", + error: isError(error) ? error : undefined, + }); + if (isRestError(error) && error.statusCode) { + span.setAttribute("http.status_code", error.statusCode); + } + span.end(); + } + catch (e) { + logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); + } +} +function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + status: "success", + }); + span.end(); + } + catch (e) { + logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); + } +} +//# sourceMappingURL=tracingPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js.map new file mode 100644 index 0000000..fb18741 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/tracingPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracingPolicy.js","sourceRoot":"","sources":["../../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;QACD,IAAI,CAAC,SAAS,CAAC;YACb,MAAM,EAAE,SAAS;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,EAAE,CAAC;KACZ;IAAC,OAAO,CAAM,EAAE;QACf,MAAM,CAAC,OAAO,CAAC,qDAAqD,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;KAC3F;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n TracingClient,\n TracingContext,\n TracingSpan,\n createTracingClient,\n} from \"@azure/core-tracing\";\nimport { SDK_VERSION } from \"../constants\";\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { getUserAgentValue } from \"../util/userAgent\";\nimport { logger } from \"../log\";\nimport { getErrorMessage, isError } from \"@azure/core-util\";\nimport { isRestError } from \"../restError\";\n\n/**\n * The programmatic identifier of the tracingPolicy.\n */\nexport const tracingPolicyName = \"tracingPolicy\";\n\n/**\n * Options to configure the tracing policy.\n */\nexport interface TracingPolicyOptions {\n /**\n * String prefix to add to the user agent logged as metadata\n * on the generated Span.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A simple policy to create OpenTelemetry Spans for each request made by the pipeline\n * that has SpanOptions with a parent.\n * Requests made without a parent Span will not be recorded.\n * @param options - Options to configure the telemetry logged by the tracing policy.\n */\nexport function tracingPolicy(options: TracingPolicyOptions = {}): PipelinePolicy {\n const userAgent = getUserAgentValue(options.userAgentPrefix);\n const tracingClient = tryCreateTracingClient();\n\n return {\n name: tracingPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (!tracingClient || !request.tracingOptions?.tracingContext) {\n return next(request);\n }\n\n const { span, tracingContext } = tryCreateSpan(tracingClient, request, userAgent) ?? {};\n\n if (!span || !tracingContext) {\n return next(request);\n }\n\n try {\n const response = await tracingClient.withContext(tracingContext, next, request);\n tryProcessResponse(span, response);\n return response;\n } catch (err: any) {\n tryProcessError(span, err);\n throw err;\n }\n },\n };\n}\n\nfunction tryCreateTracingClient(): TracingClient | undefined {\n try {\n return createTracingClient({\n namespace: \"\",\n packageName: \"@azure/core-rest-pipeline\",\n packageVersion: SDK_VERSION,\n });\n } catch (e: unknown) {\n logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);\n return undefined;\n }\n}\n\nfunction tryCreateSpan(\n tracingClient: TracingClient,\n request: PipelineRequest,\n userAgent?: string\n): { span: TracingSpan; tracingContext: TracingContext } | undefined {\n try {\n // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.\n const { span, updatedOptions } = tracingClient.startSpan(\n `HTTP ${request.method}`,\n { tracingOptions: request.tracingOptions },\n {\n spanKind: \"client\",\n spanAttributes: {\n \"http.method\": request.method,\n \"http.url\": request.url,\n requestId: request.requestId,\n },\n }\n );\n\n // If the span is not recording, don't do any more work.\n if (!span.isRecording()) {\n span.end();\n return undefined;\n }\n\n if (userAgent) {\n span.setAttribute(\"http.user_agent\", userAgent);\n }\n\n // set headers\n const headers = tracingClient.createRequestHeaders(\n updatedOptions.tracingOptions.tracingContext\n );\n for (const [key, value] of Object.entries(headers)) {\n request.headers.set(key, value);\n }\n return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };\n } catch (e: any) {\n logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);\n return undefined;\n }\n}\n\nfunction tryProcessError(span: TracingSpan, error: unknown): void {\n try {\n span.setStatus({\n status: \"error\",\n error: isError(error) ? error : undefined,\n });\n if (isRestError(error) && error.statusCode) {\n span.setAttribute(\"http.status_code\", error.statusCode);\n }\n span.end();\n } catch (e: any) {\n logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);\n }\n}\n\nfunction tryProcessResponse(span: TracingSpan, response: PipelineResponse): void {\n try {\n span.setAttribute(\"http.status_code\", response.status);\n const serviceRequestId = response.headers.get(\"x-ms-request-id\");\n if (serviceRequestId) {\n span.setAttribute(\"serviceRequestId\", serviceRequestId);\n }\n span.setStatus({\n status: \"success\",\n });\n span.end();\n } catch (e: any) {\n logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js new file mode 100644 index 0000000..1191b50 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { getUserAgentHeaderName, getUserAgentValue } from "../util/userAgent"; +const UserAgentHeaderName = getUserAgentHeaderName(); +/** + * The programmatic identifier of the userAgentPolicy. + */ +export const userAgentPolicyName = "userAgentPolicy"; +/** + * A policy that sets the User-Agent header (or equivalent) to reflect + * the library version. + * @param options - Options to customize the user agent value. + */ +export function userAgentPolicy(options = {}) { + const userAgentValue = getUserAgentValue(options.userAgentPrefix); + return { + name: userAgentPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName)) { + request.headers.set(UserAgentHeaderName, userAgentValue); + } + return next(request); + }, + }; +} +//# sourceMappingURL=userAgentPolicy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js.map new file mode 100644 index 0000000..88807a5 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/policies/userAgentPolicy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userAgentPolicy.js","sourceRoot":"","sources":["../../../src/policies/userAgentPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAE9E,MAAM,mBAAmB,GAAG,sBAAsB,EAAE,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AAarD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAClE,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE;gBAC7C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,cAAc,CAAC,CAAC;aAC1D;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { getUserAgentHeaderName, getUserAgentValue } from \"../util/userAgent\";\n\nconst UserAgentHeaderName = getUserAgentHeaderName();\n\n/**\n * The programmatic identifier of the userAgentPolicy.\n */\nexport const userAgentPolicyName = \"userAgentPolicy\";\n\n/**\n * Options for adding user agent details to outgoing requests.\n */\nexport interface UserAgentPolicyOptions {\n /**\n * String prefix to add to the user agent for outgoing requests.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A policy that sets the User-Agent header (or equivalent) to reflect\n * the library version.\n * @param options - Options to customize the user agent value.\n */\nexport function userAgentPolicy(options: UserAgentPolicyOptions = {}): PipelinePolicy {\n const userAgentValue = getUserAgentValue(options.userAgentPrefix);\n return {\n name: userAgentPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise {\n if (!request.headers.has(UserAgentHeaderName)) {\n request.headers.set(UserAgentHeaderName, userAgentValue);\n }\n return next(request);\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js new file mode 100644 index 0000000..30ca3f6 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { isError } from "@azure/core-util"; +import { custom } from "./util/inspect"; +import { Sanitizer } from "./util/sanitizer"; +const errorSanitizer = new Sanitizer(); +/** + * A custom error type for failed pipeline requests. + */ +export class RestError extends Error { + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + this.request = options.request; + this.response = options.response; + Object.setPrototypeOf(this, RestError.prototype); + } + /** + * Logging method for util.inspect in Node + */ + [custom]() { + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; + } +} +/** + * Something went wrong when making the request. + * This means the actual request failed for some reason, + * such as a DNS issue or the connection being lost. + */ +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ +RestError.PARSE_ERROR = "PARSE_ERROR"; +/** + * Typeguard for RestError + * @param e - Something caught by a catch clause. + */ +export function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return isError(e) && e.name === "RestError"; +} +//# sourceMappingURL=restError.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js.map new file mode 100644 index 0000000..a3bad36 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/restError.js.map @@ -0,0 +1 @@ +{"version":3,"file":"restError.js","sourceRoot":"","sources":["../../src/restError.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,cAAc,GAAG,IAAI,SAAS,EAAE,CAAC;AAwBvC;;GAEG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAkClC,YAAY,OAAe,EAAE,UAA4B,EAAE;QACzD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QAEjC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;IACnD,CAAC;IAED;;OAEG;IACH,CAAC,MAAM,CAAC;QACN,OAAO,cAAc,IAAI,CAAC,OAAO,OAAO,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IAC1E,CAAC;;AAjDD;;;;GAIG;AACa,4BAAkB,GAAW,oBAAoB,CAAC;AAClE;;;GAGG;AACa,qBAAW,GAAW,aAAa,CAAC;AA0CtD;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,CAAU;IACpC,IAAI,CAAC,YAAY,SAAS,EAAE;QAC1B,OAAO,IAAI,CAAC;KACb;IACD,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;AAC9C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isError } from \"@azure/core-util\";\nimport { PipelineRequest, PipelineResponse } from \"./interfaces\";\nimport { custom } from \"./util/inspect\";\nimport { Sanitizer } from \"./util/sanitizer\";\n\nconst errorSanitizer = new Sanitizer();\n\n/**\n * The options supported by RestError.\n */\nexport interface RestErrorOptions {\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n statusCode?: number;\n /**\n * The request that was made.\n */\n request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n response?: PipelineResponse;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\nexport class RestError extends Error {\n /**\n * Something went wrong when making the request.\n * This means the actual request failed for some reason,\n * such as a DNS issue or the connection being lost.\n */\n static readonly REQUEST_SEND_ERROR: string = \"REQUEST_SEND_ERROR\";\n /**\n * This means that parsing the response from the server failed.\n * It may have been malformed.\n */\n static readonly PARSE_ERROR: string = \"PARSE_ERROR\";\n\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n public code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n public statusCode?: number;\n /**\n * The request that was made.\n */\n public request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n public response?: PipelineResponse;\n /**\n * Bonus property set by the throw site.\n */\n public details?: unknown;\n\n constructor(message: string, options: RestErrorOptions = {}) {\n super(message);\n this.name = \"RestError\";\n this.code = options.code;\n this.statusCode = options.statusCode;\n this.request = options.request;\n this.response = options.response;\n\n Object.setPrototypeOf(this, RestError.prototype);\n }\n\n /**\n * Logging method for util.inspect in Node\n */\n [custom](): string {\n return `RestError: ${this.message} \\n ${errorSanitizer.sanitize(this)}`;\n }\n}\n\n/**\n * Typeguard for RestError\n * @param e - Something caught by a catch clause.\n */\nexport function isRestError(e: unknown): e is RestError {\n if (e instanceof RestError) {\n return true;\n }\n return isError(e) && e.name === \"RestError\";\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js new file mode 100644 index 0000000..b8314ce --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { getRandomIntegerInclusive } from "@azure/core-util"; +import { isThrottlingRetryResponse } from "./throttlingRetryStrategy"; +// intervals are in milliseconds +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; +/** + * A retry strategy that retries with an exponentially increasing delay in these two cases: + * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). + * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505). + */ +export function exponentialRetryStrategy(options = {}) { + var _a, _b; + const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + let retryAfterInMs = retryInterval; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; + } + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; + } + // Exponentially increase the delay each time + const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount); + // Don't let the delay exceed the maximum + const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay); + // Allow the final value to have some "jitter" (within 50% of the delay size) so + // that retries across multiple clients don't occur simultaneously. + retryAfterInMs = + clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2); + return { retryAfterInMs }; + }, + }; +} +/** + * A response is a retry response if it has status codes: + * - 408, or + * - Greater or equal than 500, except for 501 and 505. + */ +export function isExponentialRetryResponse(response) { + return Boolean(response && + response.status !== undefined && + (response.status >= 500 || response.status === 408) && + response.status !== 501 && + response.status !== 505); +} +/** + * Determines whether an error from a pipeline response was triggered in the network layer. + */ +export function isSystemError(err) { + if (!err) { + return false; + } + return (err.code === "ETIMEDOUT" || + err.code === "ESOCKETTIMEDOUT" || + err.code === "ECONNREFUSED" || + err.code === "ECONNRESET" || + err.code === "ENOENT"); +} +//# sourceMappingURL=exponentialRetryStrategy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js.map new file mode 100644 index 0000000..4a46013 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/exponentialRetryStrategy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exponentialRetryStrategy.js","sourceRoot":"","sources":["../../../src/retryStrategies/exponentialRetryStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAE7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,gCAAgC;AAChC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAC3C,MAAM,iCAAiC,GAAG,IAAI,GAAG,EAAE,CAAC;AAEpD;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACtC,UAuBI,EAAE;;IAEN,MAAM,aAAa,GAAG,MAAA,OAAO,CAAC,cAAc,mCAAI,6BAA6B,CAAC;IAC9E,MAAM,gBAAgB,GAAG,MAAA,OAAO,CAAC,iBAAiB,mCAAI,iCAAiC,CAAC;IAExF,IAAI,cAAc,GAAG,aAAa,CAAC;IAEnC,OAAO;QACL,IAAI,EAAE,0BAA0B;QAChC,KAAK,CAAC,EAAE,UAAU,EAAE,QAAQ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AQ,CAAC,MAAM,KAAK,GAAG;QACvB,QAAQ,CAAC,MAAM,KAAK,GAAG,CAC1B,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,GAAe;IAC3C,IAAI,CAAC,GAAG,EAAE;QACR,OAAO,KAAK,CAAC;KACd;IACD,OAAO,CACL,GAAG,CAAC,IAAI,KAAK,WAAW;QACxB,GAAG,CAAC,IAAI,KAAK,iBAAiB;QAC9B,GAAG,CAAC,IAAI,KAAK,cAAc;QAC3B,GAAG,CAAC,IAAI,KAAK,YAAY;QACzB,GAAG,CAAC,IAAI,KAAK,QAAQ,CACtB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineResponse } from \"../interfaces\";\nimport { RestError } from \"../restError\";\nimport { getRandomIntegerInclusive } from \"@azure/core-util\";\nimport { RetryStrategy } from \"./retryStrategy\";\nimport { isThrottlingRetryResponse } from \"./throttlingRetryStrategy\";\n\n// intervals are in milliseconds\nconst DEFAULT_CLIENT_RETRY_INTERVAL = 1000;\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;\n\n/**\n * A retry strategy that retries with an exponentially increasing delay in these two cases:\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).\n */\nexport function exponentialRetryStrategy(\n options: {\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n\n /**\n * If true it won't retry if it received a system error.\n */\n ignoreSystemErrors?: boolean;\n\n /**\n * If true it won't retry if it received a non-fatal HTTP status code.\n */\n ignoreHttpStatusCodes?: boolean;\n } = {}\n): RetryStrategy {\n const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL;\n const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL;\n\n let retryAfterInMs = retryInterval;\n\n return {\n name: \"exponentialRetryStrategy\",\n retry({ retryCount, response, responseError }) {\n const matchedSystemError = isSystemError(responseError);\n const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;\n\n const isExponential = isExponentialRetryResponse(response);\n const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;\n const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential);\n\n if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {\n return { skipStrategy: true };\n }\n\n if (responseError && !matchedSystemError && !isExponential) {\n return { errorToThrow: responseError };\n }\n\n // Exponentially increase the delay each time\n const exponentialDelay = retryAfterInMs * Math.pow(2, retryCount);\n // Don't let the delay exceed the maximum\n const clampedExponentialDelay = Math.min(maxRetryInterval, exponentialDelay);\n // Allow the final value to have some \"jitter\" (within 50% of the delay size) so\n // that retries across multiple clients don't occur simultaneously.\n retryAfterInMs =\n clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2);\n return { retryAfterInMs };\n },\n };\n}\n\n/**\n * A response is a retry response if it has status codes:\n * - 408, or\n * - Greater or equal than 500, except for 501 and 505.\n */\nexport function isExponentialRetryResponse(response?: PipelineResponse): boolean {\n return Boolean(\n response &&\n response.status !== undefined &&\n (response.status >= 500 || response.status === 408) &&\n response.status !== 501 &&\n response.status !== 505\n );\n}\n\n/**\n * Determines whether an error from a pipeline response was triggered in the network layer.\n */\nexport function isSystemError(err?: RestError): boolean {\n if (!err) {\n return false;\n }\n return (\n err.code === \"ETIMEDOUT\" ||\n err.code === \"ESOCKETTIMEDOUT\" ||\n err.code === \"ECONNREFUSED\" ||\n err.code === \"ECONNRESET\" ||\n err.code === \"ENOENT\"\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js new file mode 100644 index 0000000..4b2354b --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export {}; +//# sourceMappingURL=retryStrategy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js.map new file mode 100644 index 0000000..ad16f46 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/retryStrategy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retryStrategy.js","sourceRoot":"","sources":["../../../src/retryStrategies/retryStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureLogger } from \"@azure/logger\";\nimport { PipelineResponse } from \"../interfaces\";\nimport { RestError } from \"../restError\";\n\n/**\n * Information provided to the retry strategy about the current progress of the retry policy.\n */\nexport interface RetryInformation {\n /**\n * A {@link PipelineResponse}, if the last retry attempt succeeded.\n */\n response?: PipelineResponse;\n /**\n * A {@link RestError}, if the last retry attempt failed.\n */\n responseError?: RestError;\n /**\n * Total number of retries so far.\n */\n retryCount: number;\n}\n\n/**\n * Properties that can modify the behavior of the retry policy.\n */\nexport interface RetryModifiers {\n /**\n * If true, allows skipping the current strategy from running on the retry policy.\n */\n skipStrategy?: boolean;\n /**\n * Indicates to retry against this URL.\n */\n redirectTo?: string;\n /**\n * Controls whether to retry in a given number of milliseconds.\n * If provided, a new retry will be attempted.\n */\n retryAfterInMs?: number;\n /**\n * Indicates to throw this error instead of retrying.\n */\n errorToThrow?: RestError;\n}\n\n/**\n * A retry strategy is intended to define whether to retry or not, and how to retry.\n */\nexport interface RetryStrategy {\n /**\n * Name of the retry strategy. Used for logging.\n */\n name: string;\n /**\n * Logger. If it's not provided, a default logger for all retry strategies is used.\n */\n logger?: AzureLogger;\n /**\n * Function that determines how to proceed with the subsequent requests.\n * @param state - Retry state\n */\n retry(state: RetryInformation): RetryModifiers;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js new file mode 100644 index 0000000..2b2547d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { parseHeaderValueAsNumber } from "../util/helpers"; +/** + * The header that comes back from Azure services representing + * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry). + */ +const RetryAfterHeader = "Retry-After"; +/** + * The headers that come back from Azure services representing + * the amount of time (minimum) to wait to retry. + * + * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds + * "Retry-After" : seconds or timestamp + */ +const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; +/** + * A response is a throttling retry response if it has a throttling status code (429 or 503), + * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. + * + * Returns the `retryAfterInMs` value if the response is a throttling retry response. + * If not throttling retry response, returns `undefined`. + * + * @internal + */ +function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return undefined; + try { + // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After" + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = parseHeaderValueAsNumber(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + // "Retry-After" header ==> seconds + // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds + const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1; + return retryAfterValue * multiplyingFactor; // in milli-seconds + } + } + // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + // negative diff would mean a date in the past, so retry asap with 0 milliseconds + return Number.isFinite(diff) ? Math.max(0, diff) : undefined; + } + catch (e) { + return undefined; + } +} +/** + * A response is a retry response if it has a throttling status code (429 or 503), + * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. + */ +export function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); +} +export function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs, + }; + }, + }; +} +//# sourceMappingURL=throttlingRetryStrategy.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js.map new file mode 100644 index 0000000..e5af49d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/retryStrategies/throttlingRetryStrategy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"throttlingRetryStrategy.js","sourceRoot":"","sources":["../../../src/retryStrategies/throttlingRetryStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAG3D;;;GAGG;AACH,MAAM,gBAAgB,GAAG,aAAa,CAAC;AACvC;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAa,CAAC,gBAAgB,EAAE,qBAAqB,EAAE,gBAAgB,CAAC,CAAC;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AAED,MAAM,UAAU,uBAAuB;IACrC,OAAO;QACL,IAAI,EAAE,yBAAyB;QAC/B,KAAK,CAAC,EAAE,QAAQ,EAAE;YAChB,MAAM,cAAc,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;YACnD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE;gBACpC,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;aAC/B;YACD,OAAO;gBACL,cAAc;aACf,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PipelineResponse } from \"..\";\nimport { parseHeaderValueAsNumber } from \"../util/helpers\";\nimport { RetryStrategy } from \"./retryStrategy\";\n\n/**\n * The header that comes back from Azure services representing\n * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).\n */\nconst RetryAfterHeader = \"Retry-After\";\n/**\n * The headers that come back from Azure services representing\n * the amount of time (minimum) to wait to retry.\n *\n * \"retry-after-ms\", \"x-ms-retry-after-ms\" : milliseconds\n * \"Retry-After\" : seconds or timestamp\n */\nconst AllRetryAfterHeaders: string[] = [\"retry-after-ms\", \"x-ms-retry-after-ms\", RetryAfterHeader];\n\n/**\n * A response is a throttling retry response if it has a throttling status code (429 or 503),\n * as long as one of the [ \"Retry-After\" or \"retry-after-ms\" or \"x-ms-retry-after-ms\" ] headers has a valid value.\n *\n * Returns the `retryAfterInMs` value if the response is a throttling retry response.\n * If not throttling retry response, returns `undefined`.\n *\n * @internal\n */\nfunction getRetryAfterInMs(response?: PipelineResponse): number | undefined {\n if (!(response && [429, 503].includes(response.status))) return undefined;\n try {\n // Headers: \"retry-after-ms\", \"x-ms-retry-after-ms\", \"Retry-After\"\n for (const header of AllRetryAfterHeaders) {\n const retryAfterValue = parseHeaderValueAsNumber(response, header);\n if (retryAfterValue === 0 || retryAfterValue) {\n // \"Retry-After\" header ==> seconds\n // \"retry-after-ms\", \"x-ms-retry-after-ms\" headers ==> milli-seconds\n const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;\n return retryAfterValue * multiplyingFactor; // in milli-seconds\n }\n }\n\n // RetryAfterHeader (\"Retry-After\") has a special case where it might be formatted as a date instead of a number of seconds\n const retryAfterHeader = response.headers.get(RetryAfterHeader);\n if (!retryAfterHeader) return;\n\n const date = Date.parse(retryAfterHeader);\n const diff = date - Date.now();\n // negative diff would mean a date in the past, so retry asap with 0 milliseconds\n return Number.isFinite(diff) ? Math.max(0, diff) : undefined;\n } catch (e: any) {\n return undefined;\n }\n}\n\n/**\n * A response is a retry response if it has a throttling status code (429 or 503),\n * as long as one of the [ \"Retry-After\" or \"retry-after-ms\" or \"x-ms-retry-after-ms\" ] headers has a valid value.\n */\nexport function isThrottlingRetryResponse(response?: PipelineResponse): boolean {\n return Number.isFinite(getRetryAfterInMs(response));\n}\n\nexport function throttlingRetryStrategy(): RetryStrategy {\n return {\n name: \"throttlingRetryStrategy\",\n retry({ response }) {\n const retryAfterInMs = getRetryAfterInMs(response);\n if (!Number.isFinite(retryAfterInMs)) {\n return { skipStrategy: true };\n }\n return {\n retryAfterInMs,\n };\n },\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js new file mode 100644 index 0000000..a1c1183 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { AbortError } from "@azure/abort-controller"; +const StandardAbortMessage = "The operation was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. + * @param delayInMs - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @param options - The options for delay - currently abort options + * - abortSignal - The abortSignal associated with containing operation. + * - abortErrorMsg - The abort error message associated with containing operation. + * @returns Resolved promise + */ +export function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = undefined; + let onAborted = undefined; + const rejectOnAbort = () => { + return reject(new AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (timer) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); +} +/** + * @internal + * @returns the parsed value or undefined if the parsed value is invalid. + */ +export function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js.map new file mode 100644 index 0000000..d6a91dc --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/util/helpers.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAmB,MAAM,yBAAyB,CAAC;AAGtE,MAAM,oBAAoB,GAAG,4BAA4B,CAAC;AAE1D;;;;;;;;GAQG;AACH,MAAM,UAAU,KAAK,CACnB,SAAiB,EACjB,KAAS,EACT,OAGC;IAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAA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AAkB;IAElB,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/C,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACjC,IAAI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;QAAE,OAAO;IACrC,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport { PipelineResponse } from \"../interfaces\";\n\nconst StandardAbortMessage = \"The operation was aborted.\";\n\n/**\n * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.\n * @param delayInMs - The number of milliseconds to be delayed.\n * @param value - The value to be resolved with after a timeout of t milliseconds.\n * @param options - The options for delay - currently abort options\n * - abortSignal - The abortSignal associated with containing operation.\n * - abortErrorMsg - The abort error message associated with containing operation.\n * @returns Resolved promise\n */\nexport function delay(\n delayInMs: number,\n value?: T,\n options?: {\n abortSignal?: AbortSignalLike;\n abortErrorMsg?: string;\n }\n): Promise {\n return new Promise((resolve, reject) => {\n let timer: ReturnType | undefined = undefined;\n let onAborted: (() => void) | undefined = undefined;\n\n const rejectOnAbort = (): void => {\n return reject(\n new AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage)\n );\n };\n\n const removeListeners = (): void => {\n if (options?.abortSignal && onAborted) {\n options.abortSignal.removeEventListener(\"abort\", onAborted);\n }\n };\n\n onAborted = (): void => {\n if (timer) {\n clearTimeout(timer);\n }\n removeListeners();\n return rejectOnAbort();\n };\n\n if (options?.abortSignal && options.abortSignal.aborted) {\n return rejectOnAbort();\n }\n\n timer = setTimeout(() => {\n removeListeners();\n resolve(value);\n }, delayInMs);\n\n if (options?.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", onAborted);\n }\n });\n}\n\n/**\n * @internal\n * @returns the parsed value or undefined if the parsed value is invalid.\n */\nexport function parseHeaderValueAsNumber(\n response: PipelineResponse,\n headerName: string\n): number | undefined {\n const value = response.headers.get(headerName);\n if (!value) return;\n const valueAsNum = Number(value);\n if (Number.isNaN(valueAsNum)) return;\n return valueAsNum;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js new file mode 100644 index 0000000..65d8b5e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export const custom = {}; +//# sourceMappingURL=inspect.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js.map new file mode 100644 index 0000000..edb1168 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inspect.browser.js","sourceRoot":"","sources":["../../../src/util/inspect.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport const custom = {};\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js new file mode 100644 index 0000000..53fba75 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { inspect } from "util"; +export const custom = inspect.custom; +//# sourceMappingURL=inspect.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js.map new file mode 100644 index 0000000..5ba871c --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/inspect.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../../src/util/inspect.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,MAAM,CAAC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { inspect } from \"util\";\n\nexport const custom = inspect.custom;\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js new file mode 100644 index 0000000..4ea4b25 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { isObject } from "@azure/core-util"; +const RedactedString = "REDACTED"; +// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts +const defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate", +]; +const defaultAllowedQueryParameters = ["api-version"]; +/** + * @internal + */ +export class Sanitizer { + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + sanitize(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { + // Ensure Errors include their interesting non-enumerable members + if (value instanceof Error) { + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); + } + if (key === "headers") { + return this.sanitizeHeaders(value); + } + else if (key === "url") { + return this.sanitizeUrl(value); + } + else if (key === "query") { + return this.sanitizeQuery(value); + } + else if (key === "body") { + // Don't log the request body + return undefined; + } + else if (key === "response") { + // Don't log response again + return undefined; + } + else if (key === "operationSpec") { + // When using sendOperationRequest, the request carries a massive + // field with the autorest spec. No need to log it. + return undefined; + } + else if (Array.isArray(value) || isObject(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } + else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } + else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } + sanitizeUrl(value) { + if (typeof value !== "string" || value === null) { + return value; + } + const url = new URL(value); + if (!url.search) { + return value; + } + for (const [key] of url.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url.searchParams.set(key, RedactedString); + } + } + return url.toString(); + } +} +//# sourceMappingURL=sanitizer.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js.map new file mode 100644 index 0000000..728401b --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/sanitizer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sanitizer.js","sourceRoot":"","sources":["../../../src/util/sanitizer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAiB,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAqB3D,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,sFAAsF;AACtF,MAAM,yBAAyB,GAAG;IAChC,wBAAwB;IACxB,+BAA+B;IAC/B,gBAAgB;IAChB,6BAA6B;IAC7B,iBAAiB;IACjB,mBAAmB;IACnB,OAAO;IACP,0BAA0B;IAC1B,aAAa;IAEb,kCAAkC;IAClC,8BAA8B;IAC9B,8BAA8B;IAC9B,6BAA6B;IAC7B,+BAA+B;IAC/B,wBAAwB;IACxB,gCAAgC;IAChC,+BAA+B;IAC/B,QAAQ;IAER,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,YAAY;IACZ,gBAAgB;IAChB,cAAc;IACd,MAAM;IACN,MAAM;IACN,SAAS;IACT,UAAU;IACV,mBAAmB;IACnB,eAAe;IACf,qBAAqB;IACrB,eAAe;IACf,QAAQ;IACR,YAAY;IACZ,aAAa;IACb,QAAQ;IACR,mBAAmB;IACnB,YAAY;IACZ,kBAAkB;CACnB,CAAC;AAEF,MAAM,6BAA6B,GAAa,CAAC,aAAa,CAAC,CAAC;AAEhE;;GAEG;AACH,MAAM,OAAO,SAAS;IAIpB,YAAY,EACV,4BAA4B,EAAE,kBAAkB,GAAG,EAAE,EACrD,gCAA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;gBACL,SAAS,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC;aAC/B;SACF;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAEO,WAAW,CAAC,KAAa;QAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE;YAC/C,OAAO,KAAK,CAAC;SACd;QAED,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;QAE3B,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE;YACf,OAAO,KAAK,CAAC;SACd;QAED,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,YAAY,EAAE;YACpC,IAAI,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,EAAE;gBACvD,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;aAC3C;SACF;QAED,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;IACxB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { UnknownObject, isObject } from \"@azure/core-util\";\n\n/**\n * @internal\n */\nexport interface SanitizerOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n}\n\nconst RedactedString = \"REDACTED\";\n\n// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts\nconst defaultAllowedHeaderNames = [\n \"x-ms-client-request-id\",\n \"x-ms-return-client-request-id\",\n \"x-ms-useragent\",\n \"x-ms-correlation-request-id\",\n \"x-ms-request-id\",\n \"client-request-id\",\n \"ms-cv\",\n \"return-client-request-id\",\n \"traceparent\",\n\n \"Access-Control-Allow-Credentials\",\n \"Access-Control-Allow-Headers\",\n \"Access-Control-Allow-Methods\",\n \"Access-Control-Allow-Origin\",\n \"Access-Control-Expose-Headers\",\n \"Access-Control-Max-Age\",\n \"Access-Control-Request-Headers\",\n \"Access-Control-Request-Method\",\n \"Origin\",\n\n \"Accept\",\n \"Accept-Encoding\",\n \"Cache-Control\",\n \"Connection\",\n \"Content-Length\",\n \"Content-Type\",\n \"Date\",\n \"ETag\",\n \"Expires\",\n \"If-Match\",\n \"If-Modified-Since\",\n \"If-None-Match\",\n \"If-Unmodified-Since\",\n \"Last-Modified\",\n \"Pragma\",\n \"Request-Id\",\n \"Retry-After\",\n \"Server\",\n \"Transfer-Encoding\",\n \"User-Agent\",\n \"WWW-Authenticate\",\n];\n\nconst defaultAllowedQueryParameters: string[] = [\"api-version\"];\n\n/**\n * @internal\n */\nexport class Sanitizer {\n private allowedHeaderNames: Set;\n private allowedQueryParameters: Set;\n\n constructor({\n additionalAllowedHeaderNames: allowedHeaderNames = [],\n additionalAllowedQueryParameters: allowedQueryParameters = [],\n }: SanitizerOptions = {}) {\n allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);\n allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);\n\n this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));\n this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));\n }\n\n public sanitize(obj: unknown): string {\n const seen = new Set();\n return JSON.stringify(\n obj,\n (key: string, value: unknown) => {\n // Ensure Errors include their interesting non-enumerable members\n if (value instanceof Error) {\n return {\n ...value,\n name: value.name,\n message: value.message,\n };\n }\n\n if (key === \"headers\") {\n return this.sanitizeHeaders(value as UnknownObject);\n } else if (key === \"url\") {\n return this.sanitizeUrl(value as string);\n } else if (key === \"query\") {\n return this.sanitizeQuery(value as UnknownObject);\n } else if (key === \"body\") {\n // Don't log the request body\n return undefined;\n } else if (key === \"response\") {\n // Don't log response again\n return undefined;\n } else if (key === \"operationSpec\") {\n // When using sendOperationRequest, the request carries a massive\n // field with the autorest spec. No need to log it.\n return undefined;\n } else if (Array.isArray(value) || isObject(value)) {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n\n return value;\n },\n 2\n );\n }\n\n private sanitizeHeaders(obj: UnknownObject): UnknownObject {\n const sanitized: UnknownObject = {};\n for (const key of Object.keys(obj)) {\n if (this.allowedHeaderNames.has(key.toLowerCase())) {\n sanitized[key] = obj[key];\n } else {\n sanitized[key] = RedactedString;\n }\n }\n return sanitized;\n }\n\n private sanitizeQuery(value: UnknownObject): UnknownObject {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n const sanitized: UnknownObject = {};\n\n for (const k of Object.keys(value)) {\n if (this.allowedQueryParameters.has(k.toLowerCase())) {\n sanitized[k] = value[k];\n } else {\n sanitized[k] = RedactedString;\n }\n }\n\n return sanitized;\n }\n\n private sanitizeUrl(value: string): string {\n if (typeof value !== \"string\" || value === null) {\n return value;\n }\n\n const url = new URL(value);\n\n if (!url.search) {\n return value;\n }\n\n for (const [key] of url.searchParams) {\n if (!this.allowedQueryParameters.has(key.toLowerCase())) {\n url.searchParams.set(key, RedactedString);\n }\n }\n\n return url.toString();\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js new file mode 100644 index 0000000..2b6617a --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { delay } from "./helpers"; +// Default options for the cycler if none are provided +export const DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1000, + retryIntervalInMs: 3000, + refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry +}; +/** + * Converts an an unreliable access token getter (which may resolve with null) + * into an AccessTokenGetter by retrying the unreliable getter in a regular + * interval. + * + * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null. + * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts. + * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception. + * @returns - A promise that, if it resolves, will resolve with an access token. + */ +async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } + catch (_a) { + return null; + } + } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; +} +/** + * Creates a token cycler from a credential, scopes, and optional settings. + * + * A token cycler represents a way to reliably retrieve a valid access token + * from a TokenCredential. It will handle initializing the token, refreshing it + * when it nears expiration, and synchronizes refresh attempts to avoid + * concurrency hazards. + * + * @param credential - the underlying TokenCredential that provides the access + * token + * @param tokenCyclerOptions - optionally override default settings for the cycler + * + * @returns - a function that reliably produces a valid access token + */ +export function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + /** + * This little holder defines several predicates that we use to construct + * the rules of refreshing the token. + */ + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + return (!cycler.isRefreshing && + ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); + }, + }; + /** + * Starts a refresh job or returns the existing job if one is already + * running. + */ + function refresh(scopes, getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + // We bind `scopes` here to avoid passing it around a lot + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + // Take advantage of promise chaining to insert an assignment to `token` + // before the refresh can be considered done. + refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) + .then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }) + .catch((reason) => { + // We also should reset the refresher if we enter a failed state. All + // existing awaiters will throw, but subsequent requests will start a + // new retry chain. + refreshWorker = null; + token = null; + tenantId = undefined; + throw reason; + }); + } + return refreshWorker; + } + return async (scopes, tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + // If the tenantId passed in token options is different to the one we have + // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to + // refresh the token with the new tenantId or token. + const mustRefresh = tenantId !== tokenOptions.tenantId || Boolean(tokenOptions.claims) || cycler.mustRefresh; + if (mustRefresh) + return refresh(scopes, tokenOptions); + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; +} +//# sourceMappingURL=tokenCycler.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js.map new file mode 100644 index 0000000..a70f597 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/tokenCycler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"t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AAE,EAAE;gBAChB,sEAAsE;gBACtE,qEAAqE;gBACrE,mBAAmB;gBACnB,aAAa,GAAG,IAAI,CAAC;gBACrB,KAAK,GAAG,IAAI,CAAC;gBACb,QAAQ,GAAG,SAAS,CAAC;gBACrB,MAAM,MAAM,CAAC;YACf,CAAC,CAAC,CAAC;SACN;QAED,OAAO,aAAqC,CAAC;IAC/C,CAAC;IAED,OAAO,KAAK,EAAE,MAAyB,EAAE,YAA6B,EAAwB,EAAE;QAC9F,EAAE;QACF,gBAAgB;QAChB,+DAA+D;QAC/D,6CAA6C;QAC7C,+DAA+D;QAC/D,yCAAyC;QACzC,6DAA6D;QAC7D,YAAY;QACZ,EAAE;QAEF,0EAA0E;QAC1E,kHAAkH;QAClH,oDAAoD;QACpD,MAAM,WAAW,GACf,QAAQ,KAAK,YAAY,CAAC,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,WAAW,CAAC;QAE3F,IAAI,WAAW;YAAE,OAAO,OAAO,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAEtD,IAAI,MAAM,CAAC,aAAa,EAAE;YACxB,OAAO,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;SAC/B;QAED,OAAO,KAAoB,CAAC;IAC9B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport { delay } from \"./helpers\";\n\n/**\n * A function that gets a promise of an access token and allows providing\n * options.\n *\n * @param options - the options to pass to the underlying token provider\n */\nexport type AccessTokenGetter = (\n scopes: string | string[],\n options: GetTokenOptions\n) => Promise;\n\nexport interface TokenCyclerOptions {\n /**\n * The window of time before token expiration during which the token will be\n * considered unusable due to risk of the token expiring before sending the\n * request.\n *\n * This will only become meaningful if the refresh fails for over\n * (refreshWindow - forcedRefreshWindow) milliseconds.\n */\n forcedRefreshWindowInMs: number;\n /**\n * Interval in milliseconds to retry failed token refreshes.\n */\n retryIntervalInMs: number;\n /**\n * The window of time before token expiration during which\n * we will attempt to refresh the token.\n */\n refreshWindowInMs: number;\n}\n\n// Default options for the cycler if none are provided\nexport const DEFAULT_CYCLER_OPTIONS: TokenCyclerOptions = {\n forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires\n retryIntervalInMs: 3000, // Allow refresh attempts every 3s\n refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry\n};\n\n/**\n * Converts an an unreliable access token getter (which may resolve with null)\n * into an AccessTokenGetter by retrying the unreliable getter in a regular\n * interval.\n *\n * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.\n * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.\n * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.\n * @returns - A promise that, if it resolves, will resolve with an access token.\n */\nasync function beginRefresh(\n getAccessToken: () => Promise,\n retryIntervalInMs: number,\n refreshTimeout: number\n): Promise {\n // This wrapper handles exceptions gracefully as long as we haven't exceeded\n // the timeout.\n async function tryGetAccessToken(): Promise {\n if (Date.now() < refreshTimeout) {\n try {\n return await getAccessToken();\n } catch {\n return null;\n }\n } else {\n const finalToken = await getAccessToken();\n\n // Timeout is up, so throw if it's still null\n if (finalToken === null) {\n throw new Error(\"Failed to refresh access token.\");\n }\n\n return finalToken;\n }\n }\n\n let token: AccessToken | null = await tryGetAccessToken();\n\n while (token === null) {\n await delay(retryIntervalInMs);\n\n token = await tryGetAccessToken();\n }\n\n return token;\n}\n\n/**\n * Creates a token cycler from a credential, scopes, and optional settings.\n *\n * A token cycler represents a way to reliably retrieve a valid access token\n * from a TokenCredential. It will handle initializing the token, refreshing it\n * when it nears expiration, and synchronizes refresh attempts to avoid\n * concurrency hazards.\n *\n * @param credential - the underlying TokenCredential that provides the access\n * token\n * @param tokenCyclerOptions - optionally override default settings for the cycler\n *\n * @returns - a function that reliably produces a valid access token\n */\nexport function createTokenCycler(\n credential: TokenCredential,\n tokenCyclerOptions?: Partial\n): AccessTokenGetter {\n let refreshWorker: Promise | null = null;\n let token: AccessToken | null = null;\n let tenantId: string | undefined;\n\n const options = {\n ...DEFAULT_CYCLER_OPTIONS,\n ...tokenCyclerOptions,\n };\n\n /**\n * This little holder defines several predicates that we use to construct\n * the rules of refreshing the token.\n */\n const cycler = {\n /**\n * Produces true if a refresh job is currently in progress.\n */\n get isRefreshing(): boolean {\n return refreshWorker !== null;\n },\n /**\n * Produces true if the cycler SHOULD refresh (we are within the refresh\n * window and not already refreshing)\n */\n get shouldRefresh(): boolean {\n return (\n !cycler.isRefreshing &&\n (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now()\n );\n },\n /**\n * Produces true if the cycler MUST refresh (null or nearly-expired\n * token).\n */\n get mustRefresh(): boolean {\n return (\n token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()\n );\n },\n };\n\n /**\n * Starts a refresh job or returns the existing job if one is already\n * running.\n */\n function refresh(\n scopes: string | string[],\n getTokenOptions: GetTokenOptions\n ): Promise {\n if (!cycler.isRefreshing) {\n // We bind `scopes` here to avoid passing it around a lot\n const tryGetAccessToken = (): Promise =>\n credential.getToken(scopes, getTokenOptions);\n\n // Take advantage of promise chaining to insert an assignment to `token`\n // before the refresh can be considered done.\n refreshWorker = beginRefresh(\n tryGetAccessToken,\n options.retryIntervalInMs,\n // If we don't have a token, then we should timeout immediately\n token?.expiresOnTimestamp ?? Date.now()\n )\n .then((_token) => {\n refreshWorker = null;\n token = _token;\n tenantId = getTokenOptions.tenantId;\n return token;\n })\n .catch((reason) => {\n // We also should reset the refresher if we enter a failed state. All\n // existing awaiters will throw, but subsequent requests will start a\n // new retry chain.\n refreshWorker = null;\n token = null;\n tenantId = undefined;\n throw reason;\n });\n }\n\n return refreshWorker as Promise;\n }\n\n return async (scopes: string | string[], tokenOptions: GetTokenOptions): Promise => {\n //\n // Simple rules:\n // - If we MUST refresh, then return the refresh task, blocking\n // the pipeline until a token is available.\n // - If we SHOULD refresh, then run refresh but don't return it\n // (we can still use the cached token).\n // - Return the token, since it's fine if we didn't return in\n // step 1.\n //\n\n // If the tenantId passed in token options is different to the one we have\n // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to\n // refresh the token with the new tenantId or token.\n const mustRefresh =\n tenantId !== tokenOptions.tenantId || Boolean(tokenOptions.claims) || cycler.mustRefresh;\n\n if (mustRefresh) return refresh(scopes, tokenOptions);\n\n if (cycler.shouldRefresh) {\n refresh(scopes, tokenOptions);\n }\n\n return token as AccessToken;\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js new file mode 100644 index 0000000..865b799 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { getHeaderName, setPlatformSpecificData } from "./userAgentPlatform"; +import { SDK_VERSION } from "../constants"; +function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); + } + return parts.join(" "); +} +/** + * @internal + */ +export function getUserAgentHeaderName() { + return getHeaderName(); +} +/** + * @internal + */ +export function getUserAgentValue(prefix) { + const runtimeInfo = new Map(); + runtimeInfo.set("core-rest-pipeline", SDK_VERSION); + setPlatformSpecificData(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; + return userAgentValue; +} +//# sourceMappingURL=userAgent.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js.map new file mode 100644 index 0000000..9b985f0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userAgent.js","sourceRoot":"","sources":["../../../src/util/userAgent.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,SAAS,kBAAkB,CAAC,aAAkC;IAC5D,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,aAAa,EAAE;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;KACnB;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,sBAAsB;IACpC,OAAO,aAAa,EAAE,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAe;IAC/C,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC9C,WAAW,CAAC,GAAG,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAAC;IACnD,uBAAuB,CAAC,WAAW,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,cAAc,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI,YAAY,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IAC3E,OAAO,cAAc,CAAC;AACxB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { getHeaderName, setPlatformSpecificData } from \"./userAgentPlatform\";\nimport { SDK_VERSION } from \"../constants\";\n\nfunction getUserAgentString(telemetryInfo: Map): string {\n const parts: string[] = [];\n for (const [key, value] of telemetryInfo) {\n const token = value ? `${key}/${value}` : key;\n parts.push(token);\n }\n return parts.join(\" \");\n}\n\n/**\n * @internal\n */\nexport function getUserAgentHeaderName(): string {\n return getHeaderName();\n}\n\n/**\n * @internal\n */\nexport function getUserAgentValue(prefix?: string): string {\n const runtimeInfo = new Map();\n runtimeInfo.set(\"core-rest-pipeline\", SDK_VERSION);\n setPlatformSpecificData(runtimeInfo);\n const defaultAgent = getUserAgentString(runtimeInfo);\n const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;\n return userAgentValue;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js new file mode 100644 index 0000000..cfc6ec0 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/* + * NOTE: When moving this file, please update "browser" section in package.json. + */ +/** + * @internal + */ +export function getHeaderName() { + return "x-ms-useragent"; +} +/** + * @internal + */ +export function setPlatformSpecificData(map) { + var _a, _b, _c; + const localNavigator = globalThis.navigator; + map.set("OS", ((_c = (_b = (_a = localNavigator === null || localNavigator === void 0 ? void 0 : localNavigator.userAgentData) === null || _a === void 0 ? void 0 : _a.platform) !== null && _b !== void 0 ? _b : localNavigator === null || localNavigator === void 0 ? void 0 : localNavigator.platform) !== null && _c !== void 0 ? _c : "unknown").replace(" ", "")); +} +//# sourceMappingURL=userAgentPlatform.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js.map new file mode 100644 index 0000000..9baafd4 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userAgentPlatform.browser.js","sourceRoot":"","sources":["../../../src/util/userAgentPlatform.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AAEH;;GAEG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAQD;;GAEG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAwB;;IAC9D,MAAM,cAAc,GAAG,UAAU,CAAC,SAAwB,CAAC;IAC3D,GAAG,CAAC,GAAG,CACL,IAAI,EACJ,CAAC,MAAA,MAAA,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,aAAa,0CAAE,QAAQ,mCAAI,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,QAAQ,mCAAI,SAAS,CAAC,CAAC,OAAO,CACxF,GAAG,EACH,EAAE,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n * NOTE: When moving this file, please update \"browser\" section in package.json.\n */\n\n/**\n * @internal\n */\nexport function getHeaderName(): string {\n return \"x-ms-useragent\";\n}\n\ninterface NavigatorEx extends Navigator {\n userAgentData?: {\n platform?: string;\n };\n}\n\n/**\n * @internal\n */\nexport function setPlatformSpecificData(map: Map): void {\n const localNavigator = globalThis.navigator as NavigatorEx;\n map.set(\n \"OS\",\n (localNavigator?.userAgentData?.platform ?? localNavigator?.platform ?? \"unknown\").replace(\n \" \",\n \"\"\n )\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js new file mode 100644 index 0000000..b9e83e7 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import * as os from "os"; +/** + * @internal + */ +export function getHeaderName() { + return "User-Agent"; +} +/** + * @internal + */ +export function setPlatformSpecificData(map) { + map.set("Node", process.version); + map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); +} +//# sourceMappingURL=userAgentPlatform.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js.map new file mode 100644 index 0000000..2331ea9 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userAgentPlatform.js","sourceRoot":"","sources":["../../../src/util/userAgentPlatform.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AAEzB;;GAEG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAwB;IAC9D,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACjC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as os from \"os\";\n\n/**\n * @internal\n */\nexport function getHeaderName(): string {\n return \"User-Agent\";\n}\n\n/**\n * @internal\n */\nexport function setPlatformSpecificData(map: Map): void {\n map.set(\"Node\", process.version);\n map.set(\"OS\", `(${os.arch()}-${os.type()}-${os.release()})`);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js new file mode 100644 index 0000000..ca70507 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/* + * NOTE: When moving this file, please update "react-native" section in package.json. + */ +const { Platform } = require("react-native"); // eslint-disable-line import/no-extraneous-dependencies, @typescript-eslint/no-require-imports +/** + * @internal + */ +export function getHeaderName() { + return "x-ms-useragent"; +} +/** + * @internal + */ +export function setPlatformSpecificData(map) { + const { major, minor, patch } = Platform.constants.reactNativeVersion; + map.set("react-native", `${major}.${minor}.${patch}`); + map.set("OS", `${Platform.OS}-${Platform.Version}`); +} +//# sourceMappingURL=userAgentPlatform.native.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js.map new file mode 100644 index 0000000..2b7ae58 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/userAgentPlatform.native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userAgentPlatform.native.js","sourceRoot":"","sources":["../../../src/util/userAgentPlatform.native.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,+FAA+F;AAE7I;;GAEG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAwB;IAC9D,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC,SAAS,CAAC,kBAAkB,CAAC;IACtE,GAAG,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,KAAK,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC,CAAC;IACtD,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;AACtD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n * NOTE: When moving this file, please update \"react-native\" section in package.json.\n */\nconst { Platform } = require(\"react-native\"); // eslint-disable-line import/no-extraneous-dependencies, @typescript-eslint/no-require-imports\n\n/**\n * @internal\n */\nexport function getHeaderName(): string {\n return \"x-ms-useragent\";\n}\n\n/**\n * @internal\n */\nexport function setPlatformSpecificData(map: Map): void {\n const { major, minor, patch } = Platform.constants.reactNativeVersion;\n map.set(\"react-native\", `${major}.${minor}.${patch}`);\n map.set(\"OS\", `${Platform.OS}-${Platform.Version}`);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js new file mode 100644 index 0000000..eb9a8a9 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { v4 as uuidv4 } from "uuid"; +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + * @internal + */ +export function generateUuid() { + return uuidv4(); +} +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js.map new file mode 100644 index 0000000..393650e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/util/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../../src/util/uuid.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,MAAM,EAAE,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { v4 as uuidv4 } from \"uuid\";\n\n/**\n * Generated Universally Unique Identifier\n *\n * @returns RFC4122 v4 UUID.\n * @internal\n */\nexport function generateUuid(): string {\n return uuidv4();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js b/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js new file mode 100644 index 0000000..9402a24 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { AbortError } from "@azure/abort-controller"; +import { createHttpHeaders } from "./httpHeaders"; +import { RestError } from "./restError"; +function isNodeReadableStream(body) { + return body && typeof body.pipe === "function"; +} +/** + * Checks if the body is a ReadableStream supported by browsers + */ +function isReadableStream(body) { + return Boolean(body && + typeof body.getReader === "function" && + typeof body.tee === "function"); +} +/** + * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests. + * @internal + */ +class XhrHttpClient { + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + var _a; + const url = new URL(request.url); + const isInsecure = url.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const xhr = new XMLHttpRequest(); + if (request.proxySettings) { + throw new Error("HTTP proxy is not supported in browser environment"); + } + const abortSignal = request.abortSignal; + if (abortSignal) { + if (abortSignal.aborted) { + throw new AbortError("The operation was aborted."); + } + const listener = () => { + xhr.abort(); + }; + abortSignal.addEventListener("abort", listener); + xhr.addEventListener("readystatechange", () => { + if (xhr.readyState === XMLHttpRequest.DONE) { + abortSignal.removeEventListener("abort", listener); + } + }); + } + addProgressListener(xhr.upload, request.onUploadProgress); + addProgressListener(xhr, request.onDownloadProgress); + xhr.open(request.method, request.url); + xhr.timeout = request.timeout; + xhr.withCredentials = request.withCredentials; + for (const [name, value] of request.headers) { + xhr.setRequestHeader(name, value); + } + xhr.responseType = ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.size) ? "blob" : "text"; + const body = typeof request.body === "function" ? request.body() : request.body; + if (isNodeReadableStream(body) || isReadableStream(body)) { + throw new Error("streams are not supported in XhrHttpClient."); + } + xhr.send(body === undefined ? null : body); + if (xhr.responseType === "blob") { + return new Promise((resolve, reject) => { + handleBlobResponse(xhr, request, resolve, reject); + rejectOnTerminalEvent(request, xhr, reject); + }); + } + else { + return new Promise(function (resolve, reject) { + xhr.addEventListener("load", () => resolve({ + request, + status: xhr.status, + headers: parseHeaders(xhr), + bodyAsText: xhr.responseText, + })); + rejectOnTerminalEvent(request, xhr, reject); + }); + } + } +} +function handleBlobResponse(xhr, request, res, rej) { + xhr.addEventListener("readystatechange", () => { + var _a, _b; + // Resolve as soon as headers are loaded + if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(Number.POSITIVE_INFINITY)) || + ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(xhr.status))) { + const blobBody = new Promise((resolve, reject) => { + xhr.addEventListener("load", () => { + resolve(xhr.response); + }); + rejectOnTerminalEvent(request, xhr, reject); + }); + res({ + request, + status: xhr.status, + headers: parseHeaders(xhr), + blobBody, + }); + } + else { + xhr.addEventListener("load", () => { + // xhr.response is of Blob type if the request is sent with xhr.responseType === "blob" + // but the status code is not one of the stream response status codes, + // so treat it as text and convert from Blob to text + if (xhr.response) { + xhr.response + .text() + .then((text) => { + res({ + request: request, + status: xhr.status, + headers: parseHeaders(xhr), + bodyAsText: text, + }); + return; + }) + .catch((e) => { + rej(e); + }); + } + else { + res({ + request, + status: xhr.status, + headers: parseHeaders(xhr), + }); + } + }); + } + } + }); +} +function addProgressListener(xhr, listener) { + if (listener) { + xhr.addEventListener("progress", (rawEvent) => listener({ + loadedBytes: rawEvent.loaded, + })); + } +} +function parseHeaders(xhr) { + const responseHeaders = createHttpHeaders(); + const headerLines = xhr + .getAllResponseHeaders() + .trim() + .split(/[\r\n]+/); + for (const line of headerLines) { + const index = line.indexOf(":"); + const headerName = line.slice(0, index); + const headerValue = line.slice(index + 2); + responseHeaders.set(headerName, headerValue); + } + return responseHeaders; +} +function rejectOnTerminalEvent(request, xhr, reject) { + xhr.addEventListener("error", () => reject(new RestError(`Failed to send request to ${request.url}`, { + code: RestError.REQUEST_SEND_ERROR, + request, + }))); + const abortError = new AbortError("The operation was aborted."); + xhr.addEventListener("abort", () => reject(abortError)); + xhr.addEventListener("timeout", () => reject(abortError)); +} +/** + * Create a new HttpClient instance for the browser environment. + * @internal + */ +export function createXhrHttpClient() { + return new XhrHttpClient(); +} +//# sourceMappingURL=xhrHttpClient.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js.map b/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js.map new file mode 100644 index 0000000..6934e73 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/dist-esm/src/xhrHttpClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"xhrHttpClient.js","sourceRoot":"","sources":["../../src/xhrHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAQrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,SAAS,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iB,EAAE,CAAC;IAC5C,MAAM,WAAW,GAAG,GAAG;SACpB,qBAAqB,EAAE;SACvB,IAAI,EAAE;SACN,KAAK,CAAC,SAAS,CAAC,CAAC;IACpB,KAAK,MAAM,IAAI,IAAI,WAAW,EAAE;QAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAChC,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QACxC,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAC1C,eAAe,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;KAC9C;IACD,OAAO,eAAe,CAAC;AACzB,CAAC;AAED,SAAS,qBAAqB,CAC5B,OAAwB,EACxB,GAAmB,EACnB,MAA0B;IAE1B,GAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CACjC,MAAM,CACJ,IAAI,SAAS,CAAC,6BAA6B,OAAO,CAAC,GAAG,EAAE,EAAE;QACxD,IAAI,EAAE,SAAS,CAAC,kBAAkB;QAClC,OAAO;KACR,CAAC,CACH,CACF,CAAC;IACF,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,4BAA4B,CAAC,CAAC;IAChE,GAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACxD,GAAG,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,IAAI,aAAa,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"@azure/abort-controller\";\nimport {\n HttpClient,\n HttpHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { RestError } from \"./restError\";\n\nfunction isNodeReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\n/**\n * Checks if the body is a ReadableStream supported by browsers\n */\nfunction isReadableStream(body: unknown): body is ReadableStream {\n return Boolean(\n body &&\n typeof (body as ReadableStream).getReader === \"function\" &&\n typeof (body as ReadableStream).tee === \"function\"\n );\n}\n\n/**\n * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.\n * @internal\n */\nclass XhrHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n const xhr = new XMLHttpRequest();\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n const abortSignal = request.abortSignal;\n if (abortSignal) {\n if (abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n const listener = (): void => {\n xhr.abort();\n };\n abortSignal.addEventListener(\"abort\", listener);\n xhr.addEventListener(\"readystatechange\", () => {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n abortSignal.removeEventListener(\"abort\", listener);\n }\n });\n }\n\n addProgressListener(xhr.upload, request.onUploadProgress);\n addProgressListener(xhr, request.onDownloadProgress);\n\n xhr.open(request.method, request.url);\n xhr.timeout = request.timeout;\n xhr.withCredentials = request.withCredentials;\n for (const [name, value] of request.headers) {\n xhr.setRequestHeader(name, value);\n }\n\n xhr.responseType = request.streamResponseStatusCodes?.size ? \"blob\" : \"text\";\n\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isNodeReadableStream(body) || isReadableStream(body)) {\n throw new Error(\"streams are not supported in XhrHttpClient.\");\n }\n\n xhr.send(body === undefined ? null : body);\n\n if (xhr.responseType === \"blob\") {\n return new Promise((resolve, reject) => {\n handleBlobResponse(xhr, request, resolve, reject);\n rejectOnTerminalEvent(request, xhr, reject);\n });\n } else {\n return new Promise(function (resolve, reject) {\n xhr.addEventListener(\"load\", () =>\n resolve({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: xhr.responseText,\n })\n );\n rejectOnTerminalEvent(request, xhr, reject);\n });\n }\n }\n}\n\nfunction handleBlobResponse(\n xhr: XMLHttpRequest,\n request: PipelineRequest,\n res: (value: PipelineResponse | PromiseLike) => void,\n rej: (reason?: any) => void\n): void {\n xhr.addEventListener(\"readystatechange\", () => {\n // Resolve as soon as headers are loaded\n if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(xhr.status)\n ) {\n const blobBody = new Promise((resolve, reject) => {\n xhr.addEventListener(\"load\", () => {\n resolve(xhr.response);\n });\n rejectOnTerminalEvent(request, xhr, reject);\n });\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n blobBody,\n });\n } else {\n xhr.addEventListener(\"load\", () => {\n // xhr.response is of Blob type if the request is sent with xhr.responseType === \"blob\"\n // but the status code is not one of the stream response status codes,\n // so treat it as text and convert from Blob to text\n if (xhr.response) {\n xhr.response\n .text()\n .then((text: string) => {\n res({\n request: request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: text,\n });\n return;\n })\n .catch((e: any) => {\n rej(e);\n });\n } else {\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n });\n }\n });\n }\n }\n });\n}\n\nfunction addProgressListener(\n xhr: XMLHttpRequestEventTarget,\n listener?: (progress: TransferProgressEvent) => void\n): void {\n if (listener) {\n xhr.addEventListener(\"progress\", (rawEvent) =>\n listener({\n loadedBytes: rawEvent.loaded,\n })\n );\n }\n}\n\nfunction parseHeaders(xhr: XMLHttpRequest): HttpHeaders {\n const responseHeaders = createHttpHeaders();\n const headerLines = xhr\n .getAllResponseHeaders()\n .trim()\n .split(/[\\r\\n]+/);\n for (const line of headerLines) {\n const index = line.indexOf(\":\");\n const headerName = line.slice(0, index);\n const headerValue = line.slice(index + 2);\n responseHeaders.set(headerName, headerValue);\n }\n return responseHeaders;\n}\n\nfunction rejectOnTerminalEvent(\n request: PipelineRequest,\n xhr: XMLHttpRequest,\n reject: (err: any) => void\n): void {\n xhr.addEventListener(\"error\", () =>\n reject(\n new RestError(`Failed to send request to ${request.url}`, {\n code: RestError.REQUEST_SEND_ERROR,\n request,\n })\n )\n );\n const abortError = new AbortError(\"The operation was aborted.\");\n xhr.addEventListener(\"abort\", () => reject(abortError));\n xhr.addEventListener(\"timeout\", () => reject(abortError));\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createXhrHttpClient(): HttpClient {\n return new XhrHttpClient();\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/.bin/uuid b/node_modules/@azure/core-rest-pipeline/node_modules/.bin/uuid new file mode 120000 index 0000000..588f70e --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CHANGELOG.md b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..7519d19 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,229 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CONTRIBUTING.md b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/LICENSE.md b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other 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. diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/README.md b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/README.md new file mode 100644 index 0000000..ed27e57 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/README.md @@ -0,0 +1,505 @@ + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - Node 8, 10, 12, 14 + - Chrome, Safari, Firefox, Edge, IE 11 browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +**Upgrading from `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#upgrading-from-uuid3x) for details. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, + 0xc0, + 0xbd, + 0x7f, + 0x11, + 0xc0, + 0x43, + 0xda, + 0x97, + 0x5e, + 0x2a, + 0x8a, + 0xd9, + 0xeb, + 0xae, + 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, + 0x91, + 0x56, + 0xbe, + 0xc4, + 0xfb, + 0xc1, + 0xea, + 0x71, + 0xb4, + 0xef, + 0xe1, + 0x67, + 0x1c, + 0x58, + 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs: + +**Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [cdnjs](https://cdnjs.com/libraries/uuid)**: + +```html + +``` + +These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method: + +```html + +``` + +Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively. + +## "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +## Upgrading From `uuid@7.x` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7.x` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3.x` + +"_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3.x` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7.x` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3.x` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. + +---- +Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/package.json b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/package.json new file mode 100644 index 0000000..f0ab371 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "8.3.2", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.11.6", + "@babel/core": "7.11.6", + "@babel/preset-env": "7.11.5", + "@commitlint/cli": "11.0.0", + "@commitlint/config-conventional": "11.0.0", + "@rollup/plugin-node-resolve": "9.0.0", + "babel-eslint": "10.1.0", + "bundlewatch": "0.3.1", + "eslint": "7.10.0", + "eslint-config-prettier": "6.12.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.22.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "3.1.4", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.1", + "husky": "4.3.0", + "jest": "25.5.4", + "lint-staged": "10.4.0", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.1.2", + "random-seed": "0.3.0", + "rollup": "2.28.2", + "rollup-plugin-terser": "7.0.2", + "runmd": "1.3.2", + "standard-version": "9.0.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "6.4.0", + "@wdio/cli": "6.4.0", + "@wdio/jasmine-framework": "6.4.0", + "@wdio/local-runner": "6.4.0", + "@wdio/spec-reporter": "6.4.0", + "@wdio/static-server-service": "6.4.0", + "@wdio/sync": "6.4.0" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjs node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --ignore-path .prettierignore --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --ignore-path .prettierignore --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v12' ) && ( npm run build && runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "husky": { + "hooks": { + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/@azure/core-rest-pipeline/node_modules/uuid/wrapper.mjs b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/@azure/core-rest-pipeline/package.json b/node_modules/@azure/core-rest-pipeline/package.json new file mode 100644 index 0000000..8e5dae6 --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/package.json @@ -0,0 +1,145 @@ +{ + "name": "@azure/core-rest-pipeline", + "version": "1.10.2", + "description": "Isomorphic client library for making HTTP requests in node.js and browser.", + "sdk-type": "client", + "main": "dist/index.js", + "module": "dist-esm/src/index.js", + "browser": { + "./dist-esm/src/defaultHttpClient.js": "./dist-esm/src/defaultHttpClient.browser.js", + "./dist-esm/src/policies/decompressResponsePolicy.js": "./dist-esm/src/policies/decompressResponsePolicy.browser.js", + "./dist-esm/src/policies/formDataPolicy.js": "./dist-esm/src/policies/formDataPolicy.browser.js", + "./dist-esm/src/policies/proxyPolicy.js": "./dist-esm/src/policies/proxyPolicy.browser.js", + "./dist-esm/src/util/inspect.js": "./dist-esm/src/util/inspect.browser.js", + "./dist-esm/src/util/userAgentPlatform.js": "./dist-esm/src/util/userAgentPlatform.browser.js" + }, + "react-native": { + "./dist/index.js": "./dist-esm/src/index.js", + "./dist-esm/src/defaultHttpClient.js": "./dist-esm/src/defaultHttpClient.native.js", + "./dist-esm/src/util/userAgentPlatform.js": "./dist-esm/src/util/userAgentPlatform.native.js" + }, + "types": "core-rest-pipeline.shims.d.ts", + "typesVersions": { + "<3.6": { + "core-rest-pipeline.shims.d.ts": [ + "core-rest-pipeline.shims-3_1.d.ts" + ] + } + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build:types": "downlevel-dts types/latest/ types/3.1/", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local && npm run build:types", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "karma start --single-run", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/3.1/core-rest-pipeline.d.ts", + "types/latest/core-rest-pipeline.d.ts", + "core-rest-pipeline.shims.d.ts", + "core-rest-pipeline.shims-3_1.d.ts", + "LICENSE", + "README.md" + ], + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "engines": { + "node": ">=14.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-rest-pipeline/", + "sideEffects": false, + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "//metadata": { + "constantPaths": [ + { + "path": "src/constants.ts", + "prefix": "SDK_VERSION" + } + ] + }, + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/core-auth": "^1.4.0", + "@azure/core-tracing": "^1.0.1", + "@azure/core-util": "^1.0.0", + "@azure/logger": "^1.0.0", + "form-data": "^4.0.0", + "tslib": "^2.2.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "uuid": "^8.3.0" + }, + "devDependencies": { + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@microsoft/api-extractor": "^7.31.1", + "@opentelemetry/api": "^1.4.0", + "@types/chai": "^4.1.6", + "@types/chai-as-promised": "^7.1.0", + "@types/mocha": "^7.0.2", + "@types/node": "^14.0.0", + "@types/sinon": "^9.0.4", + "@types/uuid": "^8.0.0", + "chai": "^4.2.0", + "chai-as-promised": "^7.1.1", + "downlevel-dts": "^0.10.0", + "cross-env": "^7.0.2", + "eslint": "^8.0.0", + "inherits": "^2.0.3", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.0.0", + "karma-edge-launcher": "^0.4.2", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-mocha": "^2.0.1", + "karma-sourcemap-loader": "^0.3.8", + "karma": "^6.3.0", + "mocha-junit-reporter": "^2.0.0", + "mocha": "^7.1.1", + "prettier": "^2.5.1", + "puppeteer": "^19.2.2", + "rimraf": "^3.0.0", + "sinon": "^9.0.2", + "source-map-support": "^0.5.9", + "typescript": "~4.8.0", + "util": "^0.12.1" + }, + "//sampleConfiguration": { + "skipFolder": true, + "disableDocsMs": true, + "productName": "Azure SDK Core", + "productSlugs": [ + "azure" + ] + } +} diff --git a/node_modules/@azure/core-rest-pipeline/types/3.1/core-rest-pipeline.d.ts b/node_modules/@azure/core-rest-pipeline/types/3.1/core-rest-pipeline.d.ts new file mode 100644 index 0000000..21b476b --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/types/3.1/core-rest-pipeline.d.ts @@ -0,0 +1,1085 @@ +/// +import { AbortSignalLike } from '@azure/abort-controller'; +import { AccessToken } from '@azure/core-auth'; +import { AzureLogger } from '@azure/logger'; +import { Debugger } from '@azure/logger'; +import { GetTokenOptions } from '@azure/core-auth'; +import { OperationTracingOptions } from '@azure/core-tracing'; +import { TokenCredential } from '@azure/core-auth'; +/** + * Options when adding a policy to the pipeline. + * Used to express dependencies on other policies. + */ +export declare interface AddPipelineOptions { + /** + * Policies that this policy must come before. + */ + beforePolicies?: string[]; + /** + * Policies that this policy must come after. + */ + afterPolicies?: string[]; + /** + * The phase that this policy must come after. + */ + afterPhase?: PipelinePhase; + /** + * The phase this policy belongs to. + */ + phase?: PipelinePhase; +} +/** + * An interface compatible with NodeJS's `http.Agent`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface Agent { + /** + * Destroy any sockets that are currently in use by the agent. + */ + destroy(): void; + /** + * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state. + */ + maxFreeSockets: number; + /** + * Determines how many concurrent sockets the agent can have open per origin. + */ + maxSockets: number; + /** + * An object which contains queues of requests that have not yet been assigned to sockets. + */ + requests: unknown; + /** + * An object which contains arrays of sockets currently in use by the agent. + */ + sockets: unknown; +} +/** + * Options sent to the authorizeRequestOnChallenge callback + */ +export declare interface AuthorizeRequestOnChallengeOptions { + /** + * The scopes for which the bearer token applies. + */ + scopes: string[]; + /** + * Function that retrieves either a cached access token or a new access token. + */ + getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise; + /** + * Request that the policy is trying to fulfill. + */ + request: PipelineRequest; + /** + * Response containing the challenge. + */ + response: PipelineResponse; + /** + * A logger, if one was sent through the HTTP pipeline. + */ + logger?: AzureLogger; +} +/** + * Options sent to the authorizeRequest callback + */ +export declare interface AuthorizeRequestOptions { + /** + * The scopes for which the bearer token applies. + */ + scopes: string[]; + /** + * Function that retrieves either a cached access token or a new access token. + */ + getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise; + /** + * Request that the policy is trying to fulfill. + */ + request: PipelineRequest; + /** + * A logger, if one was sent through the HTTP pipeline. + */ + logger?: AzureLogger; +} +/** + * A policy that can request a token from a TokenCredential implementation and + * then apply it to the Authorization header of a request as a Bearer token. + */ +export declare function bearerTokenAuthenticationPolicy(options: BearerTokenAuthenticationPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the bearerTokenAuthenticationPolicy. + */ +export declare const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; +/** + * Options to configure the bearerTokenAuthenticationPolicy + */ +export declare interface BearerTokenAuthenticationPolicyOptions { + /** + * The TokenCredential implementation that can supply the bearer token. + */ + credential?: TokenCredential; + /** + * The scopes for which the bearer token applies. + */ + scopes: string | string[]; + /** + * Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges. + * If provided, it must contain at least the `authorizeRequestOnChallenge` method. + * If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information. + */ + challengeCallbacks?: ChallengeCallbacks; + /** + * A logger can be sent for debugging purposes. + */ + logger?: AzureLogger; +} +/** + * Options to override the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges. + */ +export declare interface ChallengeCallbacks { + /** + * Allows for the authorization of the main request of this policy before it's sent. + */ + authorizeRequest?(options: AuthorizeRequestOptions): Promise; + /** + * Allows to handle authentication challenges and to re-authorize the request. + * The response containing the challenge is `options.response`. + * If this method returns true, the underlying request will be sent once again. + * The request may be modified before being sent. + */ + authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise; +} +/** + * Create the correct HttpClient for the current environment. + */ +export declare function createDefaultHttpClient(): HttpClient; +/** + * Creates a totally empty pipeline. + * Useful for testing or creating a custom one. + */ +export declare function createEmptyPipeline(): Pipeline; +/** + * Creates an object that satisfies the `HttpHeaders` interface. + * @param rawHeaders - A simple object representing initial headers + */ +export declare function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders; +/** + * Create a new pipeline with a default set of customizable policies. + * @param options - Options to configure a custom pipeline. + */ +export declare function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline; +/** + * Creates a new pipeline request with the given options. + * This method is to allow for the easy setting of default values and not required. + * @param options - The options to create the request with. + */ +export declare function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest; +/** + * A policy to enable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +export declare function decompressResponsePolicy(): PipelinePolicy; +/** + * The programmatic identifier of the decompressResponsePolicy. + */ +export declare const decompressResponsePolicyName = "decompressResponsePolicy"; +/** + * A policy that retries according to three strategies: + * - When the server sends a 429 response with a Retry-After header. + * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). + * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. + */ +export declare function defaultRetryPolicy(options?: DefaultRetryPolicyOptions): PipelinePolicy; +/** + * Options that control how to retry failed requests. + */ +export declare interface DefaultRetryPolicyOptions extends PipelineRetryOptions { +} +/** + * A policy that attempts to retry requests while introducing an exponentially increasing delay. + * @param options - Options that configure retry logic. + */ +export declare function exponentialRetryPolicy(options?: ExponentialRetryPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the exponentialRetryPolicy. + */ +export declare const exponentialRetryPolicyName = "exponentialRetryPolicy"; +/** + * Options that control how to retry failed requests. + */ +export declare interface ExponentialRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second.) The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} +/** + * A simple object that provides form data, as if from a browser form. + */ +export declare type FormDataMap = { + [key: string]: FormDataValue | FormDataValue[]; +}; +/** + * A policy that encodes FormData on the request into the body. + */ +export declare function formDataPolicy(): PipelinePolicy; +/** + * The programmatic identifier of the formDataPolicy. + */ +export declare const formDataPolicyName = "formDataPolicy"; +/** + * Each form data entry can be a string or (in the browser) a Blob. + */ +export declare type FormDataValue = string | Blob; +/** + * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy. + * If no argument is given, it attempts to parse a proxy URL from the environment + * variables `HTTPS_PROXY` or `HTTP_PROXY`. + * @param proxyUrl - The url of the proxy to use. May contain authentication information. + */ +export declare function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined; +/** + * The required interface for a client that makes HTTP requests + * on behalf of a pipeline. + */ +export declare interface HttpClient { + /** + * The method that makes the request and returns a response. + */ + sendRequest: SendRequest; +} +/** + * Represents a set of HTTP headers on a request/response. + * Header names are treated as case insensitive. + */ +export declare interface HttpHeaders extends Iterable<[ + string, + string +]> { + /** + * Returns the value of a specific header or undefined if not set. + * @param name - The name of the header to retrieve. + */ + get(name: string): string | undefined; + /** + * Returns true if the specified header exists. + * @param name - The name of the header to check. + */ + has(name: string): boolean; + /** + * Sets a specific header with a given value. + * @param name - The name of the header to set. + * @param value - The value to use for the header. + */ + set(name: string, value: string | number | boolean): void; + /** + * Removes a specific header from the collection. + * @param name - The name of the header to delete. + */ + delete(name: string): void; + /** + * Accesses a raw JS object that acts as a simple map + * of header names to values. + */ + toJSON(options?: { + preserveCase?: boolean; + }): RawHttpHeaders; +} +/** + * Supported HTTP methods to use when making requests. + */ +export declare type HttpMethods = "GET" | "PUT" | "POST" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "TRACE"; +/** + * Defines options that are used to configure internal options of + * the HTTP pipeline for an SDK client. + */ +export declare interface InternalPipelineOptions extends PipelineOptions { + /** + * Options to configure request/response logging. + */ + loggingOptions?: LogPolicyOptions; +} +/** + * Typeguard for RestError + * @param e - Something caught by a catch clause. + */ +export declare function isRestError(e: unknown): e is RestError; +/** + * An interface compatible with NodeJS's `tls.KeyObject`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; +} +/** + * A policy that logs all requests and responses. + * @param options - Options to configure logPolicy. + */ +export declare function logPolicy(options?: LogPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the logPolicy. + */ +export declare const logPolicyName = "logPolicy"; +/** + * Options to configure the logPolicy. + */ +export declare interface LogPolicyOptions { + /** + * Header names whose values will be logged when logging is enabled. + * Defaults include a list of well-known safe headers. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + */ + additionalAllowedHeaderNames?: string[]; + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + */ + additionalAllowedQueryParameters?: string[]; + /** + * The log function to use for writing pipeline logs. + * Defaults to core-http's built-in logger. + * Compatible with the `debug` library. + */ + logger?: Debugger; +} +/** + * ndJsonPolicy is a policy used to control keep alive settings for every request. + */ +export declare function ndJsonPolicy(): PipelinePolicy; +/** + * The programmatic identifier of the ndJsonPolicy. + */ +export declare const ndJsonPolicyName = "ndJsonPolicy"; +/** + * Represents a pipeline for making a HTTP request to a URL. + * Pipelines can have multiple policies to manage manipulating each request + * before and after it is made to the server. + */ +export declare interface Pipeline { + /** + * Add a new policy to the pipeline. + * @param policy - A policy that manipulates a request. + * @param options - A set of options for when the policy should run. + */ + addPolicy(policy: PipelinePolicy, options?: AddPipelineOptions): void; + /** + * Remove a policy from the pipeline. + * @param options - Options that let you specify which policies to remove. + */ + removePolicy(options: { + name?: string; + phase?: PipelinePhase; + }): PipelinePolicy[]; + /** + * Uses the pipeline to make a HTTP request. + * @param httpClient - The HttpClient that actually performs the request. + * @param request - The request to be made. + */ + sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise; + /** + * Returns the current set of policies in the pipeline in the order in which + * they will be applied to the request. Later in the list is closer to when + * the request is performed. + */ + getOrderedPolicies(): PipelinePolicy[]; + /** + * Duplicates this pipeline to allow for modifying an existing one without mutating it. + */ + clone(): Pipeline; +} +/** + * Defines options that are used to configure the HTTP pipeline for + * an SDK client. + */ +export declare interface PipelineOptions { + /** + * Options that control how to retry failed requests. + */ + retryOptions?: PipelineRetryOptions; + /** + * Options to configure a proxy for outgoing requests. + */ + proxyOptions?: ProxySettings; + /** Options for configuring TLS authentication */ + tlsOptions?: TlsSettings; + /** + * Options for how redirect responses are handled. + */ + redirectOptions?: RedirectPolicyOptions; + /** + * Options for adding user agent details to outgoing requests. + */ + userAgentOptions?: UserAgentPolicyOptions; +} +/** + * Policies are executed in phases. + * The execution order is: + * 1. Serialize Phase + * 2. Policies not in a phase + * 3. Deserialize Phase + * 4. Retry Phase + * 5. Sign Phase + */ +export declare type PipelinePhase = "Deserialize" | "Serialize" | "Retry" | "Sign"; +/** + * A pipeline policy manipulates a request as it travels through the pipeline. + * It is conceptually a middleware that is allowed to modify the request before + * it is made as well as the response when it is received. + */ +export declare interface PipelinePolicy { + /** + * The policy name. Must be a unique string in the pipeline. + */ + name: string; + /** + * The main method to implement that manipulates a request/response. + * @param request - The request being performed. + * @param next - The next policy in the pipeline. Must be called to continue the pipeline. + */ + sendRequest(request: PipelineRequest, next: SendRequest): Promise; +} +/** + * Metadata about a request being made by the pipeline. + */ +export declare interface PipelineRequest { + /** + * The URL to make the request to. + */ + url: string; + /** + * The HTTP method to use when making the request. + */ + method: HttpMethods; + /** + * The HTTP headers to use when making the request. + */ + headers: HttpHeaders; + /** + * The number of milliseconds a request can take before automatically being terminated. + * If the request is terminated, an `AbortError` is thrown. + * Defaults to 0, which disables the timeout. + */ + timeout: number; + /** + * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. + * Defaults to false. + */ + withCredentials: boolean; + /** + * A unique identifier for the request. Used for logging and tracing. + */ + requestId: string; + /** + * The HTTP body content (if any) + */ + body?: RequestBodyType; + /** + * To simulate a browser form post + */ + formData?: FormDataMap; + /** + * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream. + * When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream. + */ + streamResponseStatusCodes?: Set; + /** + * Proxy configuration. + */ + proxySettings?: ProxySettings; + /** + * If the connection should not be reused. + */ + disableKeepAlive?: boolean; + /** + * Used to abort the request later. + */ + abortSignal?: AbortSignalLike; + /** + * Tracing options to use for any created Spans. + */ + tracingOptions?: OperationTracingOptions; + /** + * Callback which fires upon upload progress. + */ + onUploadProgress?: (progress: TransferProgressEvent) => void; + /** Callback which fires upon download progress. */ + onDownloadProgress?: (progress: TransferProgressEvent) => void; + /** Set to true if the request is sent over HTTP instead of HTTPS */ + allowInsecureConnection?: boolean; + /** + * NODEJS ONLY + * + * A Node-only option to provide a custom `http.Agent`/`https.Agent`. + * Does nothing when running in the browser. + */ + agent?: Agent; + /** + * BROWSER ONLY + * + * A browser only option to enable browser Streams. If this option is set and a response is a stream + * the response will have a property `browserStream` instead of `blobBody` which will be undefined. + * + * Default value is false + */ + enableBrowserStreams?: boolean; + /** Settings for configuring TLS authentication */ + tlsSettings?: TlsSettings; +} +/** + * Settings to initialize a request. + * Almost equivalent to Partial, but url is mandatory. + */ +export declare interface PipelineRequestOptions { + /** + * The URL to make the request to. + */ + url: string; + /** + * The HTTP method to use when making the request. + */ + method?: HttpMethods; + /** + * The HTTP headers to use when making the request. + */ + headers?: HttpHeaders; + /** + * The number of milliseconds a request can take before automatically being terminated. + * If the request is terminated, an `AbortError` is thrown. + * Defaults to 0, which disables the timeout. + */ + timeout?: number; + /** + * If credentials (cookies) should be sent along during an XHR. + * Defaults to false. + */ + withCredentials?: boolean; + /** + * A unique identifier for the request. Used for logging and tracing. + */ + requestId?: string; + /** + * The HTTP body content (if any) + */ + body?: RequestBodyType; + /** + * To simulate a browser form post + */ + formData?: FormDataMap; + /** + * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream. + */ + streamResponseStatusCodes?: Set; + /** + * BROWSER ONLY + * + * A browser only option to enable use of the Streams API. If this option is set and streaming is used + * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of + * `blobBody` which will be undefined. + * + * Default value is false + */ + enableBrowserStreams?: boolean; + /** + * Proxy configuration. + */ + proxySettings?: ProxySettings; + /** + * If the connection should not be reused. + */ + disableKeepAlive?: boolean; + /** + * Used to abort the request later. + */ + abortSignal?: AbortSignalLike; + /** + * Options used to create a span when tracing is enabled. + */ + tracingOptions?: OperationTracingOptions; + /** + * Callback which fires upon upload progress. + */ + onUploadProgress?: (progress: TransferProgressEvent) => void; + /** Callback which fires upon download progress. */ + onDownloadProgress?: (progress: TransferProgressEvent) => void; + /** Set to true if the request is sent over HTTP instead of HTTPS */ + allowInsecureConnection?: boolean; +} +/** + * Metadata about a response received by the pipeline. + */ +export declare interface PipelineResponse { + /** + * The request that generated this response. + */ + request: PipelineRequest; + /** + * The HTTP status code of the response. + */ + status: number; + /** + * The HTTP response headers. + */ + headers: HttpHeaders; + /** + * The response body as text (string format) + */ + bodyAsText?: string | null; + /** + * BROWSER ONLY + * + * The response body as a browser Blob. + * Always undefined in node.js. + */ + blobBody?: Promise; + /** + * BROWSER ONLY + * + * The response body as a browser ReadableStream. + * Always undefined in node.js. + */ + browserStreamBody?: ReadableStream; + /** + * NODEJS ONLY + * + * The response body as a node.js Readable stream. + * Always undefined in the browser. + */ + readableStreamBody?: NodeJS.ReadableStream; +} +/** + * Options that control how to retry failed requests. + */ +export declare interface PipelineRetryOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second). The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +export declare function proxyPolicy(proxySettings?: ProxySettings | undefined, options?: { + /** a list of patterns to override those loaded from NO_PROXY environment variable. */ + customNoProxyList?: string[]; +}): PipelinePolicy; +/** + * The programmatic identifier of the proxyPolicy. + */ +export declare const proxyPolicyName = "proxyPolicy"; +/** + * Options to configure a proxy for outgoing requests (Node.js only). + */ +export declare interface ProxySettings { + /** + * The proxy's host address. + */ + host: string; + /** + * The proxy host's port. + */ + port: number; + /** + * The user name to authenticate with the proxy, if required. + */ + username?: string; + /** + * The password to authenticate with the proxy, if required. + */ + password?: string; +} +/** + * An interface compatible with NodeJS's `tls.PxfObject`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; +} +/** + * A HttpHeaders collection represented as a simple JSON object. + */ +export declare type RawHttpHeaders = { + [headerName: string]: string; +}; +/** + * A HttpHeaders collection for input, represented as a simple JSON object. + */ +export declare type RawHttpHeadersInput = Record; +/** + * A policy to follow Location headers from the server in order + * to support server-side redirection. + * In the browser, this policy is not used. + * @param options - Options to control policy behavior. + */ +export declare function redirectPolicy(options?: RedirectPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the redirectPolicy. + */ +export declare const redirectPolicyName = "redirectPolicy"; +/** + * Options for how redirect responses are handled. + */ +export declare interface RedirectPolicyOptions { + /** + * The maximum number of times the redirect URL will be tried before + * failing. Defaults to 20. + */ + maxRetries?: number; +} +/** + * Types of bodies supported on the request. + * NodeJS.ReadableStream and () =\> NodeJS.ReadableStream is Node only. + * Blob, ReadableStream, and () =\> ReadableStream are browser only. + */ +export declare type RequestBodyType = NodeJS.ReadableStream | (() => NodeJS.ReadableStream) | ReadableStream | (() => ReadableStream) | Blob | ArrayBuffer | ArrayBufferView | FormData | string | null; +/** + * A custom error type for failed pipeline requests. + */ +export declare class RestError extends Error { + /** + * Something went wrong when making the request. + * This means the actual request failed for some reason, + * such as a DNS issue or the connection being lost. + */ + static readonly REQUEST_SEND_ERROR: string; + /** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ + static readonly PARSE_ERROR: string; + /** + * The code of the error itself (use statics on RestError if possible.) + */ + code?: string; + /** + * The HTTP status code of the request (if applicable.) + */ + statusCode?: number; + /** + * The request that was made. + */ + request?: PipelineRequest; + /** + * The response received (if any.) + */ + response?: PipelineResponse; + /** + * Bonus property set by the throw site. + */ + details?: unknown; + constructor(message: string, options?: RestErrorOptions); +} +/** + * The options supported by RestError. + */ +export declare interface RestErrorOptions { + /** + * The code of the error itself (use statics on RestError if possible.) + */ + code?: string; + /** + * The HTTP status code of the request (if applicable.) + */ + statusCode?: number; + /** + * The request that was made. + */ + request?: PipelineRequest; + /** + * The response received (if any.) + */ + response?: PipelineResponse; +} +/** + * Information provided to the retry strategy about the current progress of the retry policy. + */ +export declare interface RetryInformation { + /** + * A {@link PipelineResponse}, if the last retry attempt succeeded. + */ + response?: PipelineResponse; + /** + * A {@link RestError}, if the last retry attempt failed. + */ + responseError?: RestError; + /** + * Total number of retries so far. + */ + retryCount: number; +} +/** + * Properties that can modify the behavior of the retry policy. + */ +export declare interface RetryModifiers { + /** + * If true, allows skipping the current strategy from running on the retry policy. + */ + skipStrategy?: boolean; + /** + * Indicates to retry against this URL. + */ + redirectTo?: string; + /** + * Controls whether to retry in a given number of milliseconds. + * If provided, a new retry will be attempted. + */ + retryAfterInMs?: number; + /** + * Indicates to throw this error instead of retrying. + */ + errorToThrow?: RestError; +} +/** + * retryPolicy is a generic policy to enable retrying requests when certain conditions are met + */ +export declare function retryPolicy(strategies: RetryStrategy[], options?: RetryPolicyOptions): PipelinePolicy; +/** + * Options to the {@link retryPolicy} + */ +export declare interface RetryPolicyOptions { + /** + * Maximum number of retries. If not specified, it will limit to 3 retries. + */ + maxRetries?: number; + /** + * Logger. If it's not provided, a default logger is used. + */ + logger?: AzureLogger; +} +/** + * A retry strategy is intended to define whether to retry or not, and how to retry. + */ +export declare interface RetryStrategy { + /** + * Name of the retry strategy. Used for logging. + */ + name: string; + /** + * Logger. If it's not provided, a default logger for all retry strategies is used. + */ + logger?: AzureLogger; + /** + * Function that determines how to proceed with the subsequent requests. + * @param state - Retry state + */ + retry(state: RetryInformation): RetryModifiers; +} +/** + * A simple interface for making a pipeline request and receiving a response. + */ +export declare type SendRequest = (request: PipelineRequest) => Promise; +/** + * Each PipelineRequest gets a unique id upon creation. + * This policy passes that unique id along via an HTTP header to enable better + * telemetry and tracing. + * @param requestIdHeaderName - The name of the header to pass the request ID to. + */ +export declare function setClientRequestIdPolicy(requestIdHeaderName?: string): PipelinePolicy; +/** + * The programmatic identifier of the setClientRequestIdPolicy. + */ +export declare const setClientRequestIdPolicyName = "setClientRequestIdPolicy"; +/** + * A retry policy that specifically seeks to handle errors in the + * underlying transport layer (e.g. DNS lookup failures) rather than + * retryable error codes from the server itself. + * @param options - Options that customize the policy. + */ +export declare function systemErrorRetryPolicy(options?: SystemErrorRetryPolicyOptions): PipelinePolicy; +/** + * Name of the {@link systemErrorRetryPolicy} + */ +export declare const systemErrorRetryPolicyName = "systemErrorRetryPolicy"; +/** + * Options that control how to retry failed requests. + */ +export declare interface SystemErrorRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second.) The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} +/** + * A policy that retries when the server sends a 429 response with a Retry-After header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * + * @param options - Options that configure retry logic. + */ +export declare function throttlingRetryPolicy(options?: ThrottlingRetryPolicyOptions): PipelinePolicy; +/** + * Name of the {@link throttlingRetryPolicy} + */ +export declare const throttlingRetryPolicyName = "throttlingRetryPolicy"; +/** + * Options that control how to retry failed requests. + */ +export declare interface ThrottlingRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; +} +/** + * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. + */ +export declare function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy; +/** + * Name of the TLS Policy + */ +export declare const tlsPolicyName = "tlsPolicy"; +/** + * Represents a certificate for TLS authentication. + */ +export declare interface TlsSettings { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form `{pem: [,passphrase: ]}`. + * The object form can only occur in an array.object.passphrase is optional. + * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form `{buf: [,passphrase: ]}`. + * The object form can only occur in an array.object.passphrase is optional. + * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; +} +/** + * A simple policy to create OpenTelemetry Spans for each request made by the pipeline + * that has SpanOptions with a parent. + * Requests made without a parent Span will not be recorded. + * @param options - Options to configure the telemetry logged by the tracing policy. + */ +export declare function tracingPolicy(options?: TracingPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the tracingPolicy. + */ +export declare const tracingPolicyName = "tracingPolicy"; +/** + * Options to configure the tracing policy. + */ +export declare interface TracingPolicyOptions { + /** + * String prefix to add to the user agent logged as metadata + * on the generated Span. + * Defaults to an empty string. + */ + userAgentPrefix?: string; +} +/** + * Fired in response to upload or download progress. + */ +export declare type TransferProgressEvent = { + /** + * The number of bytes loaded so far. + */ + loadedBytes: number; +}; +/** + * A policy that sets the User-Agent header (or equivalent) to reflect + * the library version. + * @param options - Options to customize the user agent value. + */ +export declare function userAgentPolicy(options?: UserAgentPolicyOptions): PipelinePolicy; +/** + * The programmatic identifier of the userAgentPolicy. + */ +export declare const userAgentPolicyName = "userAgentPolicy"; +/** + * Options for adding user agent details to outgoing requests. + */ +export declare interface UserAgentPolicyOptions { + /** + * String prefix to add to the user agent for outgoing requests. + * Defaults to an empty string. + */ + userAgentPrefix?: string; +} +export {}; diff --git a/node_modules/@azure/core-rest-pipeline/types/latest/core-rest-pipeline.d.ts b/node_modules/@azure/core-rest-pipeline/types/latest/core-rest-pipeline.d.ts new file mode 100644 index 0000000..efbe28f --- /dev/null +++ b/node_modules/@azure/core-rest-pipeline/types/latest/core-rest-pipeline.d.ts @@ -0,0 +1,1164 @@ +/// + +import { AbortSignalLike } from '@azure/abort-controller'; +import { AccessToken } from '@azure/core-auth'; +import { AzureLogger } from '@azure/logger'; +import { Debugger } from '@azure/logger'; +import { GetTokenOptions } from '@azure/core-auth'; +import { OperationTracingOptions } from '@azure/core-tracing'; +import { TokenCredential } from '@azure/core-auth'; + +/** + * Options when adding a policy to the pipeline. + * Used to express dependencies on other policies. + */ +export declare interface AddPipelineOptions { + /** + * Policies that this policy must come before. + */ + beforePolicies?: string[]; + /** + * Policies that this policy must come after. + */ + afterPolicies?: string[]; + /** + * The phase that this policy must come after. + */ + afterPhase?: PipelinePhase; + /** + * The phase this policy belongs to. + */ + phase?: PipelinePhase; +} + +/** + * An interface compatible with NodeJS's `http.Agent`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface Agent { + /** + * Destroy any sockets that are currently in use by the agent. + */ + destroy(): void; + /** + * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state. + */ + maxFreeSockets: number; + /** + * Determines how many concurrent sockets the agent can have open per origin. + */ + maxSockets: number; + /** + * An object which contains queues of requests that have not yet been assigned to sockets. + */ + requests: unknown; + /** + * An object which contains arrays of sockets currently in use by the agent. + */ + sockets: unknown; +} + +/** + * Options sent to the authorizeRequestOnChallenge callback + */ +export declare interface AuthorizeRequestOnChallengeOptions { + /** + * The scopes for which the bearer token applies. + */ + scopes: string[]; + /** + * Function that retrieves either a cached access token or a new access token. + */ + getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise; + /** + * Request that the policy is trying to fulfill. + */ + request: PipelineRequest; + /** + * Response containing the challenge. + */ + response: PipelineResponse; + /** + * A logger, if one was sent through the HTTP pipeline. + */ + logger?: AzureLogger; +} + +/** + * Options sent to the authorizeRequest callback + */ +export declare interface AuthorizeRequestOptions { + /** + * The scopes for which the bearer token applies. + */ + scopes: string[]; + /** + * Function that retrieves either a cached access token or a new access token. + */ + getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise; + /** + * Request that the policy is trying to fulfill. + */ + request: PipelineRequest; + /** + * A logger, if one was sent through the HTTP pipeline. + */ + logger?: AzureLogger; +} + +/** + * A policy that can request a token from a TokenCredential implementation and + * then apply it to the Authorization header of a request as a Bearer token. + */ +export declare function bearerTokenAuthenticationPolicy(options: BearerTokenAuthenticationPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the bearerTokenAuthenticationPolicy. + */ +export declare const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; + +/** + * Options to configure the bearerTokenAuthenticationPolicy + */ +export declare interface BearerTokenAuthenticationPolicyOptions { + /** + * The TokenCredential implementation that can supply the bearer token. + */ + credential?: TokenCredential; + /** + * The scopes for which the bearer token applies. + */ + scopes: string | string[]; + /** + * Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges. + * If provided, it must contain at least the `authorizeRequestOnChallenge` method. + * If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information. + */ + challengeCallbacks?: ChallengeCallbacks; + /** + * A logger can be sent for debugging purposes. + */ + logger?: AzureLogger; +} + +/** + * Options to override the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges. + */ +export declare interface ChallengeCallbacks { + /** + * Allows for the authorization of the main request of this policy before it's sent. + */ + authorizeRequest?(options: AuthorizeRequestOptions): Promise; + /** + * Allows to handle authentication challenges and to re-authorize the request. + * The response containing the challenge is `options.response`. + * If this method returns true, the underlying request will be sent once again. + * The request may be modified before being sent. + */ + authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise; +} + +/** + * Create the correct HttpClient for the current environment. + */ +export declare function createDefaultHttpClient(): HttpClient; + +/** + * Creates a totally empty pipeline. + * Useful for testing or creating a custom one. + */ +export declare function createEmptyPipeline(): Pipeline; + +/** + * Creates an object that satisfies the `HttpHeaders` interface. + * @param rawHeaders - A simple object representing initial headers + */ +export declare function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders; + +/** + * Create a new pipeline with a default set of customizable policies. + * @param options - Options to configure a custom pipeline. + */ +export declare function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline; + +/** + * Creates a new pipeline request with the given options. + * This method is to allow for the easy setting of default values and not required. + * @param options - The options to create the request with. + */ +export declare function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest; + +/** + * A policy to enable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +export declare function decompressResponsePolicy(): PipelinePolicy; + +/** + * The programmatic identifier of the decompressResponsePolicy. + */ +export declare const decompressResponsePolicyName = "decompressResponsePolicy"; + +/** + * A policy that retries according to three strategies: + * - When the server sends a 429 response with a Retry-After header. + * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). + * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. + */ +export declare function defaultRetryPolicy(options?: DefaultRetryPolicyOptions): PipelinePolicy; + +/** + * Options that control how to retry failed requests. + */ +export declare interface DefaultRetryPolicyOptions extends PipelineRetryOptions { +} + +/** + * A policy that attempts to retry requests while introducing an exponentially increasing delay. + * @param options - Options that configure retry logic. + */ +export declare function exponentialRetryPolicy(options?: ExponentialRetryPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the exponentialRetryPolicy. + */ +export declare const exponentialRetryPolicyName = "exponentialRetryPolicy"; + +/** + * Options that control how to retry failed requests. + */ +export declare interface ExponentialRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second.) The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} + +/** + * A simple object that provides form data, as if from a browser form. + */ +export declare type FormDataMap = { + [key: string]: FormDataValue | FormDataValue[]; +}; + +/** + * A policy that encodes FormData on the request into the body. + */ +export declare function formDataPolicy(): PipelinePolicy; + +/** + * The programmatic identifier of the formDataPolicy. + */ +export declare const formDataPolicyName = "formDataPolicy"; + +/** + * Each form data entry can be a string or (in the browser) a Blob. + */ +export declare type FormDataValue = string | Blob; + +/** + * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy. + * If no argument is given, it attempts to parse a proxy URL from the environment + * variables `HTTPS_PROXY` or `HTTP_PROXY`. + * @param proxyUrl - The url of the proxy to use. May contain authentication information. + */ +export declare function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined; + +/** + * The required interface for a client that makes HTTP requests + * on behalf of a pipeline. + */ +export declare interface HttpClient { + /** + * The method that makes the request and returns a response. + */ + sendRequest: SendRequest; +} + +/** + * Represents a set of HTTP headers on a request/response. + * Header names are treated as case insensitive. + */ +export declare interface HttpHeaders extends Iterable<[string, string]> { + /** + * Returns the value of a specific header or undefined if not set. + * @param name - The name of the header to retrieve. + */ + get(name: string): string | undefined; + /** + * Returns true if the specified header exists. + * @param name - The name of the header to check. + */ + has(name: string): boolean; + /** + * Sets a specific header with a given value. + * @param name - The name of the header to set. + * @param value - The value to use for the header. + */ + set(name: string, value: string | number | boolean): void; + /** + * Removes a specific header from the collection. + * @param name - The name of the header to delete. + */ + delete(name: string): void; + /** + * Accesses a raw JS object that acts as a simple map + * of header names to values. + */ + toJSON(options?: { + preserveCase?: boolean; + }): RawHttpHeaders; +} + +/** + * Supported HTTP methods to use when making requests. + */ +export declare type HttpMethods = "GET" | "PUT" | "POST" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "TRACE"; + +/** + * Defines options that are used to configure internal options of + * the HTTP pipeline for an SDK client. + */ +export declare interface InternalPipelineOptions extends PipelineOptions { + /** + * Options to configure request/response logging. + */ + loggingOptions?: LogPolicyOptions; +} + +/** + * Typeguard for RestError + * @param e - Something caught by a catch clause. + */ +export declare function isRestError(e: unknown): e is RestError; + +/** + * An interface compatible with NodeJS's `tls.KeyObject`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; +} + +/** + * A policy that logs all requests and responses. + * @param options - Options to configure logPolicy. + */ +export declare function logPolicy(options?: LogPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the logPolicy. + */ +export declare const logPolicyName = "logPolicy"; + +/** + * Options to configure the logPolicy. + */ +export declare interface LogPolicyOptions { + /** + * Header names whose values will be logged when logging is enabled. + * Defaults include a list of well-known safe headers. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + */ + additionalAllowedHeaderNames?: string[]; + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + */ + additionalAllowedQueryParameters?: string[]; + /** + * The log function to use for writing pipeline logs. + * Defaults to core-http's built-in logger. + * Compatible with the `debug` library. + */ + logger?: Debugger; +} + +/** + * ndJsonPolicy is a policy used to control keep alive settings for every request. + */ +export declare function ndJsonPolicy(): PipelinePolicy; + +/** + * The programmatic identifier of the ndJsonPolicy. + */ +export declare const ndJsonPolicyName = "ndJsonPolicy"; + +/** + * Represents a pipeline for making a HTTP request to a URL. + * Pipelines can have multiple policies to manage manipulating each request + * before and after it is made to the server. + */ +export declare interface Pipeline { + /** + * Add a new policy to the pipeline. + * @param policy - A policy that manipulates a request. + * @param options - A set of options for when the policy should run. + */ + addPolicy(policy: PipelinePolicy, options?: AddPipelineOptions): void; + /** + * Remove a policy from the pipeline. + * @param options - Options that let you specify which policies to remove. + */ + removePolicy(options: { + name?: string; + phase?: PipelinePhase; + }): PipelinePolicy[]; + /** + * Uses the pipeline to make a HTTP request. + * @param httpClient - The HttpClient that actually performs the request. + * @param request - The request to be made. + */ + sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise; + /** + * Returns the current set of policies in the pipeline in the order in which + * they will be applied to the request. Later in the list is closer to when + * the request is performed. + */ + getOrderedPolicies(): PipelinePolicy[]; + /** + * Duplicates this pipeline to allow for modifying an existing one without mutating it. + */ + clone(): Pipeline; +} + +/** + * Defines options that are used to configure the HTTP pipeline for + * an SDK client. + */ +export declare interface PipelineOptions { + /** + * Options that control how to retry failed requests. + */ + retryOptions?: PipelineRetryOptions; + /** + * Options to configure a proxy for outgoing requests. + */ + proxyOptions?: ProxySettings; + /** Options for configuring TLS authentication */ + tlsOptions?: TlsSettings; + /** + * Options for how redirect responses are handled. + */ + redirectOptions?: RedirectPolicyOptions; + /** + * Options for adding user agent details to outgoing requests. + */ + userAgentOptions?: UserAgentPolicyOptions; +} + +/** + * Policies are executed in phases. + * The execution order is: + * 1. Serialize Phase + * 2. Policies not in a phase + * 3. Deserialize Phase + * 4. Retry Phase + * 5. Sign Phase + */ +export declare type PipelinePhase = "Deserialize" | "Serialize" | "Retry" | "Sign"; + +/** + * A pipeline policy manipulates a request as it travels through the pipeline. + * It is conceptually a middleware that is allowed to modify the request before + * it is made as well as the response when it is received. + */ +export declare interface PipelinePolicy { + /** + * The policy name. Must be a unique string in the pipeline. + */ + name: string; + /** + * The main method to implement that manipulates a request/response. + * @param request - The request being performed. + * @param next - The next policy in the pipeline. Must be called to continue the pipeline. + */ + sendRequest(request: PipelineRequest, next: SendRequest): Promise; +} + +/** + * Metadata about a request being made by the pipeline. + */ +export declare interface PipelineRequest { + /** + * The URL to make the request to. + */ + url: string; + /** + * The HTTP method to use when making the request. + */ + method: HttpMethods; + /** + * The HTTP headers to use when making the request. + */ + headers: HttpHeaders; + /** + * The number of milliseconds a request can take before automatically being terminated. + * If the request is terminated, an `AbortError` is thrown. + * Defaults to 0, which disables the timeout. + */ + timeout: number; + /** + * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. + * Defaults to false. + */ + withCredentials: boolean; + /** + * A unique identifier for the request. Used for logging and tracing. + */ + requestId: string; + /** + * The HTTP body content (if any) + */ + body?: RequestBodyType; + /** + * To simulate a browser form post + */ + formData?: FormDataMap; + /** + * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream. + * When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream. + */ + streamResponseStatusCodes?: Set; + /** + * Proxy configuration. + */ + proxySettings?: ProxySettings; + /** + * If the connection should not be reused. + */ + disableKeepAlive?: boolean; + /** + * Used to abort the request later. + */ + abortSignal?: AbortSignalLike; + /** + * Tracing options to use for any created Spans. + */ + tracingOptions?: OperationTracingOptions; + /** + * Callback which fires upon upload progress. + */ + onUploadProgress?: (progress: TransferProgressEvent) => void; + /** Callback which fires upon download progress. */ + onDownloadProgress?: (progress: TransferProgressEvent) => void; + /** Set to true if the request is sent over HTTP instead of HTTPS */ + allowInsecureConnection?: boolean; + /** + * NODEJS ONLY + * + * A Node-only option to provide a custom `http.Agent`/`https.Agent`. + * Does nothing when running in the browser. + */ + agent?: Agent; + /** + * BROWSER ONLY + * + * A browser only option to enable browser Streams. If this option is set and a response is a stream + * the response will have a property `browserStream` instead of `blobBody` which will be undefined. + * + * Default value is false + */ + enableBrowserStreams?: boolean; + /** Settings for configuring TLS authentication */ + tlsSettings?: TlsSettings; +} + +/** + * Settings to initialize a request. + * Almost equivalent to Partial, but url is mandatory. + */ +export declare interface PipelineRequestOptions { + /** + * The URL to make the request to. + */ + url: string; + /** + * The HTTP method to use when making the request. + */ + method?: HttpMethods; + /** + * The HTTP headers to use when making the request. + */ + headers?: HttpHeaders; + /** + * The number of milliseconds a request can take before automatically being terminated. + * If the request is terminated, an `AbortError` is thrown. + * Defaults to 0, which disables the timeout. + */ + timeout?: number; + /** + * If credentials (cookies) should be sent along during an XHR. + * Defaults to false. + */ + withCredentials?: boolean; + /** + * A unique identifier for the request. Used for logging and tracing. + */ + requestId?: string; + /** + * The HTTP body content (if any) + */ + body?: RequestBodyType; + /** + * To simulate a browser form post + */ + formData?: FormDataMap; + /** + * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream. + */ + streamResponseStatusCodes?: Set; + /** + * BROWSER ONLY + * + * A browser only option to enable use of the Streams API. If this option is set and streaming is used + * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of + * `blobBody` which will be undefined. + * + * Default value is false + */ + enableBrowserStreams?: boolean; + /** + * Proxy configuration. + */ + proxySettings?: ProxySettings; + /** + * If the connection should not be reused. + */ + disableKeepAlive?: boolean; + /** + * Used to abort the request later. + */ + abortSignal?: AbortSignalLike; + /** + * Options used to create a span when tracing is enabled. + */ + tracingOptions?: OperationTracingOptions; + /** + * Callback which fires upon upload progress. + */ + onUploadProgress?: (progress: TransferProgressEvent) => void; + /** Callback which fires upon download progress. */ + onDownloadProgress?: (progress: TransferProgressEvent) => void; + /** Set to true if the request is sent over HTTP instead of HTTPS */ + allowInsecureConnection?: boolean; +} + +/** + * Metadata about a response received by the pipeline. + */ +export declare interface PipelineResponse { + /** + * The request that generated this response. + */ + request: PipelineRequest; + /** + * The HTTP status code of the response. + */ + status: number; + /** + * The HTTP response headers. + */ + headers: HttpHeaders; + /** + * The response body as text (string format) + */ + bodyAsText?: string | null; + /** + * BROWSER ONLY + * + * The response body as a browser Blob. + * Always undefined in node.js. + */ + blobBody?: Promise; + /** + * BROWSER ONLY + * + * The response body as a browser ReadableStream. + * Always undefined in node.js. + */ + browserStreamBody?: ReadableStream; + /** + * NODEJS ONLY + * + * The response body as a node.js Readable stream. + * Always undefined in the browser. + */ + readableStreamBody?: NodeJS.ReadableStream; +} + +/** + * Options that control how to retry failed requests. + */ +export declare interface PipelineRetryOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second). The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} + +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +export declare function proxyPolicy(proxySettings?: ProxySettings | undefined, options?: { + /** a list of patterns to override those loaded from NO_PROXY environment variable. */ + customNoProxyList?: string[]; +}): PipelinePolicy; + +/** + * The programmatic identifier of the proxyPolicy. + */ +export declare const proxyPolicyName = "proxyPolicy"; + +/** + * Options to configure a proxy for outgoing requests (Node.js only). + */ +export declare interface ProxySettings { + /** + * The proxy's host address. + */ + host: string; + /** + * The proxy host's port. + */ + port: number; + /** + * The user name to authenticate with the proxy, if required. + */ + username?: string; + /** + * The password to authenticate with the proxy, if required. + */ + password?: string; +} + +/** + * An interface compatible with NodeJS's `tls.PxfObject`. + * We want to avoid publicly re-exporting the actual interface, + * since it might vary across runtime versions. + */ +export declare interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; +} + +/** + * A HttpHeaders collection represented as a simple JSON object. + */ +export declare type RawHttpHeaders = { + [headerName: string]: string; +}; + +/** + * A HttpHeaders collection for input, represented as a simple JSON object. + */ +export declare type RawHttpHeadersInput = Record; + +/** + * A policy to follow Location headers from the server in order + * to support server-side redirection. + * In the browser, this policy is not used. + * @param options - Options to control policy behavior. + */ +export declare function redirectPolicy(options?: RedirectPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the redirectPolicy. + */ +export declare const redirectPolicyName = "redirectPolicy"; + +/** + * Options for how redirect responses are handled. + */ +export declare interface RedirectPolicyOptions { + /** + * The maximum number of times the redirect URL will be tried before + * failing. Defaults to 20. + */ + maxRetries?: number; +} + +/** + * Types of bodies supported on the request. + * NodeJS.ReadableStream and () =\> NodeJS.ReadableStream is Node only. + * Blob, ReadableStream, and () =\> ReadableStream are browser only. + */ +export declare type RequestBodyType = NodeJS.ReadableStream | (() => NodeJS.ReadableStream) | ReadableStream | (() => ReadableStream) | Blob | ArrayBuffer | ArrayBufferView | FormData | string | null; + +/** + * A custom error type for failed pipeline requests. + */ +export declare class RestError extends Error { + /** + * Something went wrong when making the request. + * This means the actual request failed for some reason, + * such as a DNS issue or the connection being lost. + */ + static readonly REQUEST_SEND_ERROR: string; + /** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ + static readonly PARSE_ERROR: string; + /** + * The code of the error itself (use statics on RestError if possible.) + */ + code?: string; + /** + * The HTTP status code of the request (if applicable.) + */ + statusCode?: number; + /** + * The request that was made. + */ + request?: PipelineRequest; + /** + * The response received (if any.) + */ + response?: PipelineResponse; + /** + * Bonus property set by the throw site. + */ + details?: unknown; + constructor(message: string, options?: RestErrorOptions); +} + +/** + * The options supported by RestError. + */ +export declare interface RestErrorOptions { + /** + * The code of the error itself (use statics on RestError if possible.) + */ + code?: string; + /** + * The HTTP status code of the request (if applicable.) + */ + statusCode?: number; + /** + * The request that was made. + */ + request?: PipelineRequest; + /** + * The response received (if any.) + */ + response?: PipelineResponse; +} + +/** + * Information provided to the retry strategy about the current progress of the retry policy. + */ +export declare interface RetryInformation { + /** + * A {@link PipelineResponse}, if the last retry attempt succeeded. + */ + response?: PipelineResponse; + /** + * A {@link RestError}, if the last retry attempt failed. + */ + responseError?: RestError; + /** + * Total number of retries so far. + */ + retryCount: number; +} + +/** + * Properties that can modify the behavior of the retry policy. + */ +export declare interface RetryModifiers { + /** + * If true, allows skipping the current strategy from running on the retry policy. + */ + skipStrategy?: boolean; + /** + * Indicates to retry against this URL. + */ + redirectTo?: string; + /** + * Controls whether to retry in a given number of milliseconds. + * If provided, a new retry will be attempted. + */ + retryAfterInMs?: number; + /** + * Indicates to throw this error instead of retrying. + */ + errorToThrow?: RestError; +} + +/** + * retryPolicy is a generic policy to enable retrying requests when certain conditions are met + */ +export declare function retryPolicy(strategies: RetryStrategy[], options?: RetryPolicyOptions): PipelinePolicy; + +/** + * Options to the {@link retryPolicy} + */ +export declare interface RetryPolicyOptions { + /** + * Maximum number of retries. If not specified, it will limit to 3 retries. + */ + maxRetries?: number; + /** + * Logger. If it's not provided, a default logger is used. + */ + logger?: AzureLogger; +} + +/** + * A retry strategy is intended to define whether to retry or not, and how to retry. + */ +export declare interface RetryStrategy { + /** + * Name of the retry strategy. Used for logging. + */ + name: string; + /** + * Logger. If it's not provided, a default logger for all retry strategies is used. + */ + logger?: AzureLogger; + /** + * Function that determines how to proceed with the subsequent requests. + * @param state - Retry state + */ + retry(state: RetryInformation): RetryModifiers; +} + +/** + * A simple interface for making a pipeline request and receiving a response. + */ +export declare type SendRequest = (request: PipelineRequest) => Promise; + +/** + * Each PipelineRequest gets a unique id upon creation. + * This policy passes that unique id along via an HTTP header to enable better + * telemetry and tracing. + * @param requestIdHeaderName - The name of the header to pass the request ID to. + */ +export declare function setClientRequestIdPolicy(requestIdHeaderName?: string): PipelinePolicy; + +/** + * The programmatic identifier of the setClientRequestIdPolicy. + */ +export declare const setClientRequestIdPolicyName = "setClientRequestIdPolicy"; + +/** + * A retry policy that specifically seeks to handle errors in the + * underlying transport layer (e.g. DNS lookup failures) rather than + * retryable error codes from the server itself. + * @param options - Options that customize the policy. + */ +export declare function systemErrorRetryPolicy(options?: SystemErrorRetryPolicyOptions): PipelinePolicy; + +/** + * Name of the {@link systemErrorRetryPolicy} + */ +export declare const systemErrorRetryPolicyName = "systemErrorRetryPolicy"; + +/** + * Options that control how to retry failed requests. + */ +export declare interface SystemErrorRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; + /** + * The amount of delay in milliseconds between retry attempts. Defaults to 1000 + * (1 second.) The delay increases exponentially with each retry up to a maximum + * specified by maxRetryDelayInMs. + */ + retryDelayInMs?: number; + /** + * The maximum delay in milliseconds allowed before retrying an operation. Defaults + * to 64000 (64 seconds). + */ + maxRetryDelayInMs?: number; +} + +/** + * A policy that retries when the server sends a 429 response with a Retry-After header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * + * @param options - Options that configure retry logic. + */ +export declare function throttlingRetryPolicy(options?: ThrottlingRetryPolicyOptions): PipelinePolicy; + +/** + * Name of the {@link throttlingRetryPolicy} + */ +export declare const throttlingRetryPolicyName = "throttlingRetryPolicy"; + +/** + * Options that control how to retry failed requests. + */ +export declare interface ThrottlingRetryPolicyOptions { + /** + * The maximum number of retry attempts. Defaults to 3. + */ + maxRetries?: number; +} + +/** + * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. + */ +export declare function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy; + +/** + * Name of the TLS Policy + */ +export declare const tlsPolicyName = "tlsPolicy"; + +/** + * Represents a certificate for TLS authentication. + */ +export declare interface TlsSettings { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form `{pem: [,passphrase: ]}`. + * The object form can only occur in an array.object.passphrase is optional. + * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form `{buf: [,passphrase: ]}`. + * The object form can only occur in an array.object.passphrase is optional. + * Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; +} + +/** + * A simple policy to create OpenTelemetry Spans for each request made by the pipeline + * that has SpanOptions with a parent. + * Requests made without a parent Span will not be recorded. + * @param options - Options to configure the telemetry logged by the tracing policy. + */ +export declare function tracingPolicy(options?: TracingPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the tracingPolicy. + */ +export declare const tracingPolicyName = "tracingPolicy"; + +/** + * Options to configure the tracing policy. + */ +export declare interface TracingPolicyOptions { + /** + * String prefix to add to the user agent logged as metadata + * on the generated Span. + * Defaults to an empty string. + */ + userAgentPrefix?: string; +} + +/** + * Fired in response to upload or download progress. + */ +export declare type TransferProgressEvent = { + /** + * The number of bytes loaded so far. + */ + loadedBytes: number; +}; + +/** + * A policy that sets the User-Agent header (or equivalent) to reflect + * the library version. + * @param options - Options to customize the user agent value. + */ +export declare function userAgentPolicy(options?: UserAgentPolicyOptions): PipelinePolicy; + +/** + * The programmatic identifier of the userAgentPolicy. + */ +export declare const userAgentPolicyName = "userAgentPolicy"; + +/** + * Options for adding user agent details to outgoing requests. + */ +export declare interface UserAgentPolicyOptions { + /** + * String prefix to add to the user agent for outgoing requests. + * Defaults to an empty string. + */ + userAgentPrefix?: string; +} + +export { } diff --git a/node_modules/@azure/core-tracing/CHANGELOG.md b/node_modules/@azure/core-tracing/CHANGELOG.md new file mode 100644 index 0000000..e7c7431 --- /dev/null +++ b/node_modules/@azure/core-tracing/CHANGELOG.md @@ -0,0 +1,105 @@ +# Release History + +## 1.0.1 (2022-05-05) + +### Other Changes + +- Minor improvements to the typing of `updatedOptions` when calling startSpan. + +## 1.0.0 (2022-03-31) + +This release marks the GA release of our @azure/core-tracing libraries and is unchanged from preview.14 + +## 1.0.0-preview.14 (2022-02-03) + +### Breaking Changes + +- @azure/core-tracing has been rewritten in order to provide cleaner abstractions for client libraries as well as remove @opentelemetry/api as a direct dependency. + - @opentelemetry/api is no longer a direct dependency of @azure/core-tracing providing for smaller bundle sizes and lower incidence of version conflicts + - `createSpanFunction` has been removed and replaced with a stateful `TracingClient` which can be created using the `createTracingClient` function. + - `TracingClient` introduces a new API for creating tracing spans. Use `TracingClient#withSpan` to wrap an invocation in a span, ensuring the span is ended and exceptions are captured. + - `TracingClient` also provides the lower-level APIs necessary to start a span without making it active, create request headers, serialize `traceparent` header, and wrapping a callback with an active context. + +### Other Changes + +- Updates package to work with the react native bundler. [PR #17783](https://github.com/Azure/azure-sdk-for-js/pull/17783) + +## 1.0.0-preview.13 (2021-07-15) + +### Features Added + +- Added support for disabling distributed tracing using the AZURE_TRACING_DISABLED environment variable. + +### Breaking Changes + +- Removed `TestTracer` and `TestSpan` from public API and into `@azure/test-utils`. [PR #16315](https://github.com/Azure/azure-sdk-for-js/pull/16315) + - `TestTracer` and `TestSpan` are intended for test support when used by other Azure packages and not intended for use by end users. +- Removed `setTracer`, @azure/core-tracing will now rely on the `trace` API to fetch a tracer from the global tracer provider. [PR #16347](https://github.com/Azure/azure-sdk-for-js/pull/16347) + - If you are using `setTracer`, please use `trace.setGlobalTracerProvider(provider)` instead as described in the OpenTelemetry documentation. +- Removed `NoOpTracer` and `NoOpSpan` from the public API. Please use `trace.wrapSpanContext(INVALID_SPAN_CONTEXT)` from `@opentelemetry/api` instead. [PR #16315](https://github.com/Azure/azure-sdk-for-js/pull/16315) + +## 1.0.0-preview.12 (2021-06-30) + +- Update `@opentelemetry/api` to version 1.0.0 [PR #15883](https://github.com/Azure/azure-sdk-for-js/pull/15883) + - This version ships with ESM modules and fixes an issue where Angular projects would warn ab out optimization bailouts due to dependencies on CommonJS or AMD. + +### Breaking Changes + +- Removed `OpenCensusSpanWrapper` and `OpenCensusTracerWrapper` from the public API. Customers using these wrappers should migrate to using `OpenTelemetry` directly. [PR #15770](https://github.com/Azure/azure-sdk-for-js/pull/15770) +- Update `@azure/core-tracing` to version 1.0.0-preview.12. This brings core-tracing up to date with `@opentelemetry/api@1.0.0`. + - `Span#context` was renamed to `Span#spanContext`. This change is supported in `@azure/core-http@1.2.7`. + +## 1.0.0-preview.11 (2021-03-30) + +### Breaking Changes + +- Update @azure/core-tracing to version 1.0.0-preview.11. This brings core-tracing up to date with @opentelemetry/api@1.0.0-rc.0. + There are two scenarios that will require changes if you are using tracing: + - Previously, you would pass a parent span using the `OperationOptions.tracingOptions.spanOptions.parentSpan` property. This has been + changed so that you now specify a parent `Context` using the `OperationOptions.tracingOptions.tracingContext` property instead. + - The status code for Spans is no longer of type `CanonicalCode`. Instead, it's now `SpanStatusCode`, which also has a smaller range of values. + +## 1.0.0-preview.10 (2021-03-04) + +- Internal improvements to make future opentelemetry updates simpler. + +## 1.0.0-preview.9 (2020-08-04) + +- Update `@opentelemetry/api` to version 0.10.2 [PR 10393](https://github.com/Azure/azure-sdk-for-js/pull/10393) + +## 1.0.0-preview.8 (2020-04-28) + +- Update `TestSpan` to allow setting span attributes [PR link](https://github.com/Azure/azure-sdk-for-js/pull/6565). +- [BREAKING] Migrate to OpenTelemetry 0.6 using the new `@opentelemetry/api` package. There were a few breaking changes: + - `SpanContext` now requires traceFlags to be set. + - `Tracer` has removed `recordSpanData`, `getBinaryFormat`, and `getHttpTextFormat`. + - `Tracer.getCurrentSpan` returns `undefined` instead of `null` when unset. + - `Link` objects renamed `spanContext` property to `context`. + +## 1.0.0-preview.7 (2019-12-03) + +- Updated the behavior of how incompatible versions of OpenTelemetry Tracer are handled. Now, errors will be thrown only if the user has manually set a Tracer. This means that incompatible versions will be silently ignored when tracing is not enabled. +- Updated to use OpenTelemetry 0.2 via the `@opentelemetry/types` package. There were two breaking changes in this update: + - `isRecordingEvents` on `Span` was renamed to `isRecording`. [PR link](https://github.com/open-telemetry/opentelemetry-js/pull/454) + - `addLink` was removed from `Span` as links are now only allowed to be added during span creation. This is possible by specifying any necessary links inside `SpanOptions`. [PR link](https://github.com/open-telemetry/opentelemetry-js/pull/449) + +## 1.0.0-preview.5 (2019-10-22) + +- Fixes issue where loading multiple copies of this module could result in the tracer set by `setTracer()` being reset. + +## 1.0.0-preview.4 (2019-10-08) + +- Remove dependency on the `debug` module to ensure compatibility with IE11 + +## 1.0.0-preview.3 (2019-10-07) + +- Updated to use the latest types from OpenTelemetry (PR [#5182](https://github.com/Azure/azure-sdk-for-js/pull/5182)) +- Clean up and refactored code for easier usage and testability. (PR [#5233](https://github.com/Azure/azure-sdk-for-js/pull/5233) and PR [#5283](https://github.com/Azure/azure-sdk-for-js/pull/5283)) + +## 1.0.0-preview.2 (2019-09-09) + +Updated the `OpenCensusSpanPlugin` & the `NoOpSpanPlugin` to support for retrieving span context. This allows updating of request headers with the right [span context](https://www.w3.org/TR/trace-context/#trace-context-http-headers-format). (PR [#4712](https://github.com/Azure/azure-sdk-for-js/pull/4712)) + +## 1.0.0-preview.1 (2019-08-05) + +Provides low-level interfaces and helper methods for tracing in Azure SDK diff --git a/node_modules/@azure/core-tracing/LICENSE b/node_modules/@azure/core-tracing/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/core-tracing/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/core-tracing/README.md b/node_modules/@azure/core-tracing/README.md new file mode 100644 index 0000000..47b4c47 --- /dev/null +++ b/node_modules/@azure/core-tracing/README.md @@ -0,0 +1,37 @@ +# Azure Core tracing library for JavaScript + +This is the core tracing library that provides low-level interfaces and helper methods for tracing in Azure SDK JavaScript libraries which work in the browser and Node.js. + +## Getting started + +### Installation + +This package is primarily used in Azure client libraries and not meant to be used directly by consumers of Azure SDKs. + +## Key Concepts + +- `TracingClient` is the primary interface providing tracing functionality to client libraries. Client libraries should only be aware of and interact with a `TracingClient` instance. + - A `TracingClient` implementation can be created using the `createTracingClient` factory function. +- `Instrumenter` provides an abstraction over an instrumentation and acts as the interop point for using third party libraries like OpenTelemetry. By default, a no-op `Instrumenter` is used. Customers who wish to enable `OpenTelemetry` based tracing will do so by installing and registering the [@azure/opentelemetry-instrumentation-azure-sdk] package. +- `TracingContext` is an **immutable** data container, used to pass operation-specific information around (such as span parenting information). +- `TracingSpan` is an abstraction of a `Span` which can be used to record events, attributes, and exceptions. + +## Examples + +Examples can be found in the `samples` folder. + +## Next steps + +You can build and run the tests locally by executing `rushx test`. Explore the `test` folder to see advanced usage and behavior of the public classes. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +[@azure/opentelemetry-instrumentation-azure-sdk]: https://www.npmjs.com/package/@azure/opentelemetry-instrumentation-azure-sdk + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Fcore-tracing%2FREADME.png) diff --git a/node_modules/@azure/core-tracing/dist-esm/src/index.js b/node_modules/@azure/core-tracing/dist-esm/src/index.js new file mode 100644 index 0000000..af9e3f4 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/index.js @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export { useInstrumenter } from "./instrumenter"; +export { createTracingClient } from "./tracingClient"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/index.js.map b/node_modules/@azure/core-tracing/dist-esm/src/index.js.map new file mode 100644 index 0000000..da37580 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAmBlC,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport {\n Instrumenter,\n InstrumenterSpanOptions,\n OperationTracingOptions,\n OptionsWithTracingContext,\n Resolved,\n SpanStatus,\n SpanStatusError,\n SpanStatusSuccess,\n TracingClient,\n TracingClientOptions,\n TracingContext,\n TracingSpan,\n TracingSpanKind,\n TracingSpanLink,\n TracingSpanOptions,\n} from \"./interfaces\";\nexport { useInstrumenter } from \"./instrumenter\";\nexport { createTracingClient } from \"./tracingClient\";\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js b/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js new file mode 100644 index 0000000..5c92593 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createTracingContext } from "./tracingContext"; +export function createDefaultTracingSpan() { + return { + end: () => { + // noop + }, + isRecording: () => false, + recordException: () => { + // noop + }, + setAttribute: () => { + // noop + }, + setStatus: () => { + // noop + }, + }; +} +export function createDefaultInstrumenter() { + return { + createRequestHeaders: () => { + return {}; + }, + parseTraceparentHeader: () => { + return undefined; + }, + startSpan: (_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }), + }; + }, + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + }, + }; +} +/** @internal */ +let instrumenterImplementation; +/** + * Extends the Azure SDK with support for a given instrumenter implementation. + * + * @param instrumenter - The instrumenter implementation to use. + */ +export function useInstrumenter(instrumenter) { + instrumenterImplementation = instrumenter; +} +/** + * Gets the currently set instrumenter, a No-Op instrumenter by default. + * + * @returns The currently set instrumenter + */ +export function getInstrumenter() { + if (!instrumenterImplementation) { + instrumenterImplementation = createDefaultInstrumenter(); + } + return instrumenterImplementation; +} +//# sourceMappingURL=instrumenter.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js.map b/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js.map new file mode 100644 index 0000000..f5cec32 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/instrumenter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"instrumenter.js","sourceRoot":"","sources":["../../src/instrumenter.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,UAAU,wBAAwB;IACtC,OAAO;QACL,GAAG,EAAE,GAAG,EAAE;YACR,OAAO;QACT,CAAC;QACD,WAAW,EAAE,GAAG,EAAE,CAAC,KAAK;QACxB,eAAe,EAAE,GAAG,EAAE;YACpB,OAAO;QACT,CAAC;QACD,YAAY,EAAE,GAAG,EAAE;YACjB,OAAO;QACT,CAAC;QACD,SAAS,EAAE,GAAG,EAAE;YACd,OAAO;QACT,CAAC;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB;IACvC,OAAO;QACL,oBAAoB,EAAE,GAA2B,EAAE;YACjD,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,sBAAsB,EAAE,GAA+B,EAAE;YACvD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,SAAS,EAAE,CACT,KAAa,EACb,WAAoC,EACmB,EAAE;YACzD,OAAO;gBACL,IAAI,EAAE,wBAAwB,EAAE;gBAChC,cAAc,EAAE,oBAAoB,CAAC,EAAE,aAAa,EAAE,WAAW,CAAC,cAAc,EAAE,CAAC;aACpF,CAAC;QACJ,CAAC;QACD,WAAW,CAIT,QAAwB,EACxB,QAAkB,EAClB,GAAG,YAA0B;YAE7B,OAAO,QAAQ,CAAC,GAAG,YAAY,CAAC,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC;AAED,gBAAgB;AAChB,IAAI,0BAAoD,CAAC;AAEzD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,YAA0B;IACxD,0BAA0B,GAAG,YAAY,CAAC;AAC5C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe;IAC7B,IAAI,CAAC,0BAA0B,EAAE;QAC/B,0BAA0B,GAAG,yBAAyB,EAAE,CAAC;KAC1D;IACD,OAAO,0BAA0B,CAAC;AACpC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Instrumenter, InstrumenterSpanOptions, TracingContext, TracingSpan } from \"./interfaces\";\nimport { createTracingContext } from \"./tracingContext\";\n\nexport function createDefaultTracingSpan(): TracingSpan {\n return {\n end: () => {\n // noop\n },\n isRecording: () => false,\n recordException: () => {\n // noop\n },\n setAttribute: () => {\n // noop\n },\n setStatus: () => {\n // noop\n },\n };\n}\n\nexport function createDefaultInstrumenter(): Instrumenter {\n return {\n createRequestHeaders: (): Record => {\n return {};\n },\n parseTraceparentHeader: (): TracingContext | undefined => {\n return undefined;\n },\n startSpan: (\n _name: string,\n spanOptions: InstrumenterSpanOptions\n ): { span: TracingSpan; tracingContext: TracingContext } => {\n return {\n span: createDefaultTracingSpan(),\n tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }),\n };\n },\n withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType\n >(\n _context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType {\n return callback(...callbackArgs);\n },\n };\n}\n\n/** @internal */\nlet instrumenterImplementation: Instrumenter | undefined;\n\n/**\n * Extends the Azure SDK with support for a given instrumenter implementation.\n *\n * @param instrumenter - The instrumenter implementation to use.\n */\nexport function useInstrumenter(instrumenter: Instrumenter): void {\n instrumenterImplementation = instrumenter;\n}\n\n/**\n * Gets the currently set instrumenter, a No-Op instrumenter by default.\n *\n * @returns The currently set instrumenter\n */\nexport function getInstrumenter(): Instrumenter {\n if (!instrumenterImplementation) {\n instrumenterImplementation = createDefaultInstrumenter();\n }\n return instrumenterImplementation;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js b/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js new file mode 100644 index 0000000..c0a2e2e --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export {}; +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js.map b/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js.map new file mode 100644 index 0000000..05fc9a2 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A narrower version of TypeScript 4.5's Awaited type which Recursively\n * unwraps the \"awaited type\", emulating the behavior of `await`.\n */\nexport type Resolved = T extends { then(onfulfilled: infer F): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped\n ? F extends (value: infer V) => any // if the argument to `then` is callable, extracts the first argument\n ? Resolved // recursively unwrap the value\n : never // the argument to `then` was not callable\n : T; // non-object or non-thenable\n\n/**\n * Represents a client that can integrate with the currently configured {@link Instrumenter}.\n *\n * Create an instance using {@link createTracingClient}.\n */\nexport interface TracingClient {\n /**\n * Wraps a callback in a tracing span, calls the callback, and closes the span.\n *\n * This is the primary interface for using Tracing and will handle error recording as well as setting the status on the span.\n *\n * Both synchronous and asynchronous functions will be awaited in order to reflect the result of the callback on the span.\n *\n * Example:\n *\n * ```ts\n * const myOperationResult = await tracingClient.withSpan(\"myClassName.myOperationName\", options, (updatedOptions) => myOperation(updatedOptions));\n * ```\n * @param name - The name of the span. By convention this should be `${className}.${methodName}`.\n * @param operationOptions - The original options passed to the method. The callback will receive these options with the newly created {@link TracingContext}.\n * @param callback - The callback to be invoked with the updated options and newly created {@link TracingSpan}.\n */\n withSpan<\n Options extends { tracingOptions?: OperationTracingOptions },\n Callback extends (\n updatedOptions: Options,\n span: Omit\n ) => ReturnType\n >(\n name: string,\n operationOptions: Options,\n callback: Callback,\n spanOptions?: TracingSpanOptions\n ): Promise>>;\n /**\n * Starts a given span but does not set it as the active span.\n *\n * You must end the span using {@link TracingSpan.end}.\n *\n * Most of the time you will want to use {@link withSpan} instead.\n *\n * @param name - The name of the span. By convention this should be `${className}.${methodName}`.\n * @param operationOptions - The original operation options.\n * @param spanOptions - The options to use when creating the span.\n *\n * @returns A {@link TracingSpan} and the updated operation options.\n */\n startSpan(\n name: string,\n operationOptions?: Options,\n spanOptions?: TracingSpanOptions\n ): {\n span: TracingSpan;\n updatedOptions: OptionsWithTracingContext;\n };\n /**\n * Wraps a callback with an active context and calls the callback.\n * Depending on the implementation, this may set the globally available active context.\n *\n * Useful when you want to leave the boundaries of the SDK (make a request or callback to user code) and are unable to use the {@link withSpan} API.\n *\n * @param context - The {@link TracingContext} to use as the active context in the scope of the callback.\n * @param callback - The callback to be invoked with the given context set as the globally active context.\n * @param callbackArgs - The callback arguments.\n */\n withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType\n >(\n context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType;\n\n /**\n * Parses a traceparent header value into a {@link TracingSpanContext}.\n *\n * @param traceparentHeader - The traceparent header to parse.\n * @returns An implementation-specific identifier for the span.\n */\n parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined;\n\n /**\n * Creates a set of request headers to propagate tracing information to a backend.\n *\n * @param tracingContext - The context containing the span to propagate.\n * @returns The set of headers to add to a request.\n */\n createRequestHeaders(tracingContext?: TracingContext): Record;\n}\n\n/**\n * Options that can be passed to {@link createTracingClient}\n */\nexport interface TracingClientOptions {\n /** The value of the az.namespace tracing attribute on newly created spans. */\n namespace: string;\n /** The name of the package invoking this trace. */\n packageName: string;\n /** An optional version of the package invoking this trace. */\n packageVersion?: string;\n}\n\n/** The kind of span. */\nexport type TracingSpanKind = \"client\" | \"server\" | \"producer\" | \"consumer\" | \"internal\";\n\n/** Options used to configure the newly created span. */\nexport interface TracingSpanOptions {\n /** The kind of span. Implementations should default this to \"client\". */\n spanKind?: TracingSpanKind;\n /** A collection of {@link TracingSpanLink} to link to this span. */\n spanLinks?: TracingSpanLink[];\n /** Initial set of attributes to set on a span. */\n spanAttributes?: { [key: string]: unknown };\n}\n\n/** A pointer from the current {@link TracingSpan} to another span in the same or a different trace. */\nexport interface TracingSpanLink {\n /** The {@link TracingContext} containing the span context to link to. */\n tracingContext: TracingContext;\n /** A set of attributes on the link. */\n attributes?: { [key: string]: unknown };\n}\n\n/**\n * Represents an implementation agnostic instrumenter.\n */\nexport interface Instrumenter {\n /**\n * Creates a new {@link TracingSpan} with the given name and options and sets it on a new context.\n * @param name - The name of the span. By convention this should be `${className}.${methodName}`.\n * @param spanOptions - The options to use when creating the span.\n *\n * @returns A {@link TracingSpan} that can be used to end the span, and the context this span has been set on.\n */\n startSpan(\n name: string,\n spanOptions: InstrumenterSpanOptions\n ): { span: TracingSpan; tracingContext: TracingContext };\n /**\n * Wraps a callback with an active context and calls the callback.\n * Depending on the implementation, this may set the globally available active context.\n *\n * @param context - The {@link TracingContext} to use as the active context in the scope of the callback.\n * @param callback - The callback to be invoked with the given context set as the globally active context.\n * @param callbackArgs - The callback arguments.\n */\n withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType\n >(\n context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType;\n\n /**\n * Provides an implementation-specific method to parse a {@link https://www.w3.org/TR/trace-context/#traceparent-header}\n * into a {@link TracingSpanContext} which can be used to link non-parented spans together.\n */\n parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined;\n /**\n * Provides an implementation-specific method to serialize a {@link TracingSpan} to a set of headers.\n * @param tracingContext - The context containing the span to serialize.\n */\n createRequestHeaders(tracingContext?: TracingContext): Record;\n}\n\n/**\n * Options passed to {@link Instrumenter.startSpan} as a superset of {@link TracingSpanOptions}.\n */\nexport interface InstrumenterSpanOptions extends TracingSpanOptions {\n /** The name of the package invoking this trace. */\n packageName: string;\n /** The version of the package invoking this trace. */\n packageVersion?: string;\n /** The current tracing context. Defaults to an implementation-specific \"active\" context. */\n tracingContext?: TracingContext;\n}\n\n/**\n * Status representing a successful operation that can be sent to {@link TracingSpan.setStatus}\n */\nexport type SpanStatusSuccess = { status: \"success\" };\n\n/**\n * Status representing an error that can be sent to {@link TracingSpan.setStatus}\n */\nexport type SpanStatusError = { status: \"error\"; error?: Error | string };\n\n/**\n * Represents the statuses that can be passed to {@link TracingSpan.setStatus}.\n *\n * By default, all spans will be created with status \"unset\".\n */\nexport type SpanStatus = SpanStatusSuccess | SpanStatusError;\n\n/**\n * Represents an implementation agnostic tracing span.\n */\nexport interface TracingSpan {\n /**\n * Sets the status of the span. When an error is provided, it will be recorded on the span as well.\n *\n * @param status - The {@link SpanStatus} to set on the span.\n */\n setStatus(status: SpanStatus): void;\n\n /**\n * Sets a given attribute on a span.\n *\n * @param name - The attribute's name.\n * @param value - The attribute's value to set. May be any non-nullish value.\n */\n setAttribute(name: string, value: unknown): void;\n\n /**\n * Ends the span.\n */\n end(): void;\n\n /**\n * Records an exception on a {@link TracingSpan} without modifying its status.\n *\n * When recording an unhandled exception that should fail the span, please use {@link TracingSpan.setStatus} instead.\n *\n * @param exception - The exception to record on the span.\n *\n */\n recordException(exception: Error | string): void;\n\n /**\n * Returns true if this {@link TracingSpan} is recording information.\n *\n * Depending on the span implementation, this may return false if the span is not being sampled.\n */\n isRecording(): boolean;\n}\n\n/** An immutable context bag of tracing values for the current operation. */\nexport interface TracingContext {\n /**\n * Sets a given object on a context.\n * @param key - The key of the given context value.\n * @param value - The value to set on the context.\n *\n * @returns - A new context with the given value set.\n */\n setValue(key: symbol, value: unknown): TracingContext;\n /**\n * Gets an object from the context if it exists.\n * @param key - The key of the given context value.\n *\n * @returns - The value of the given context value if it exists, otherwise `undefined`.\n */\n getValue(key: symbol): unknown;\n /**\n * Deletes an object from the context if it exists.\n * @param key - The key of the given context value to delete.\n */\n deleteValue(key: symbol): TracingContext;\n}\n\n/**\n * Tracing options to set on an operation.\n */\nexport interface OperationTracingOptions {\n /** The context to use for created Tracing Spans. */\n tracingContext?: TracingContext;\n}\n\n/**\n * A utility type for when we know a TracingContext has been set\n * as part of an operation's options.\n */\nexport type OptionsWithTracingContext<\n Options extends { tracingOptions?: OperationTracingOptions }\n> = Options & {\n tracingOptions: {\n tracingContext: TracingContext;\n };\n};\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js b/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js new file mode 100644 index 0000000..2b08c91 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { getInstrumenter } from "./instrumenter"; +import { knownContextKeys } from "./tracingContext"; +/** + * Creates a new tracing client. + * + * @param options - Options used to configure the tracing client. + * @returns - An instance of {@link TracingClient}. + */ +export function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name, operationOptions, spanOptions) { + var _a; + const startSpanResult = getInstrumenter().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }), + }); + return { + span, + updatedOptions, + }; + } + async function withSpan(name, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + span.setStatus({ status: "success" }); + return result; + } + catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } + finally { + span.end(); + } + } + function withContext(context, callback, ...callbackArgs) { + return getInstrumenter().withContext(context, callback, ...callbackArgs); + } + /** + * Parses a traceparent header value into a span identifier. + * + * @param traceparentHeader - The traceparent header to parse. + * @returns An implementation-specific identifier for the span. + */ + function parseTraceparentHeader(traceparentHeader) { + return getInstrumenter().parseTraceparentHeader(traceparentHeader); + } + /** + * Creates a set of request headers to propagate tracing information to a backend. + * + * @param tracingContext - The context containing the span to serialize. + * @returns The set of headers to add to a request. + */ + function createRequestHeaders(tracingContext) { + return getInstrumenter().createRequestHeaders(tracingContext); + } + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders, + }; +} +//# sourceMappingURL=tracingClient.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js.map b/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js.map new file mode 100644 index 0000000..360dd9c --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/tracingClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracingClient.js","sourceRoot":"","sources":["../../src/tracingClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAA6B;IAC/D,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;IAE3D,SAAS,SAAS,CAChB,IAAY,EACZ,gBAA0B,EAC1B,WAAgC;;QAKhC,MAAM,eAAe,GAAG,eAAe,EAAE,CAAC,SAAS,CAAC,IAAI,kCACnD,WAAW,KACd,WAAW,EAAE,WAAW,EACxB,cAAc,EAAE,cAAc,EAC9B,cAAc,EAAE,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,cAAc,0CAAE,cAAc,IAChE,CAAC;QACH,IAAI,cAAc,GAAG,eAAe,CAAC,cAAc,CAAC;QACpD,MAAM,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC;QAClC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,gBAAgB,CAAC,SAAS,CAAC,EAAE;YACxD,cAAc,GAAG,cAAc,CAAC,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;SACjF;QACD,IAAI,CAAC,YAAY,CAAC,cAAc,E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EAAE,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,CAAC;IACrE,CAAC;IAED;;;;;OAKG;IACH,SAAS,oBAAoB,CAAC,cAA+B;QAC3D,OAAO,eAAe,EAAE,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC;IAChE,CAAC;IAED,OAAO;QACL,SAAS;QACT,QAAQ;QACR,WAAW;QACX,sBAAsB;QACtB,oBAAoB;KACrB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n OperationTracingOptions,\n OptionsWithTracingContext,\n Resolved,\n TracingClient,\n TracingClientOptions,\n TracingContext,\n TracingSpan,\n TracingSpanOptions,\n} from \"./interfaces\";\nimport { getInstrumenter } from \"./instrumenter\";\nimport { knownContextKeys } from \"./tracingContext\";\n\n/**\n * Creates a new tracing client.\n *\n * @param options - Options used to configure the tracing client.\n * @returns - An instance of {@link TracingClient}.\n */\nexport function createTracingClient(options: TracingClientOptions): TracingClient {\n const { namespace, packageName, packageVersion } = options;\n\n function startSpan(\n name: string,\n operationOptions?: Options,\n spanOptions?: TracingSpanOptions\n ): {\n span: TracingSpan;\n updatedOptions: OptionsWithTracingContext;\n } {\n const startSpanResult = getInstrumenter().startSpan(name, {\n ...spanOptions,\n packageName: packageName,\n packageVersion: packageVersion,\n tracingContext: operationOptions?.tracingOptions?.tracingContext,\n });\n let tracingContext = startSpanResult.tracingContext;\n const span = startSpanResult.span;\n if (!tracingContext.getValue(knownContextKeys.namespace)) {\n tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);\n }\n span.setAttribute(\"az.namespace\", tracingContext.getValue(knownContextKeys.namespace));\n const updatedOptions: OptionsWithTracingContext = Object.assign({}, operationOptions, {\n tracingOptions: { ...operationOptions?.tracingOptions, tracingContext },\n });\n\n return {\n span,\n updatedOptions,\n };\n }\n\n async function withSpan<\n Options extends { tracingOptions?: OperationTracingOptions },\n Callback extends (\n updatedOptions: Options,\n span: Omit\n ) => ReturnType\n >(\n name: string,\n operationOptions: Options,\n callback: Callback,\n spanOptions?: TracingSpanOptions\n ): Promise>> {\n const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);\n try {\n const result = await withContext(updatedOptions.tracingOptions.tracingContext, () =>\n Promise.resolve(callback(updatedOptions, span))\n );\n span.setStatus({ status: \"success\" });\n return result as ReturnType;\n } catch (err: any) {\n span.setStatus({ status: \"error\", error: err });\n throw err;\n } finally {\n span.end();\n }\n }\n\n function withContext<\n CallbackArgs extends unknown[],\n Callback extends (...args: CallbackArgs) => ReturnType\n >(\n context: TracingContext,\n callback: Callback,\n ...callbackArgs: CallbackArgs\n ): ReturnType {\n return getInstrumenter().withContext(context, callback, ...callbackArgs);\n }\n\n /**\n * Parses a traceparent header value into a span identifier.\n *\n * @param traceparentHeader - The traceparent header to parse.\n * @returns An implementation-specific identifier for the span.\n */\n function parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined {\n return getInstrumenter().parseTraceparentHeader(traceparentHeader);\n }\n\n /**\n * Creates a set of request headers to propagate tracing information to a backend.\n *\n * @param tracingContext - The context containing the span to serialize.\n * @returns The set of headers to add to a request.\n */\n function createRequestHeaders(tracingContext?: TracingContext): Record {\n return getInstrumenter().createRequestHeaders(tracingContext);\n }\n\n return {\n startSpan,\n withSpan,\n withContext,\n parseTraceparentHeader,\n createRequestHeaders,\n };\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js b/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js new file mode 100644 index 0000000..efcf609 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** @internal */ +export const knownContextKeys = { + span: Symbol.for("@azure/core-tracing span"), + namespace: Symbol.for("@azure/core-tracing namespace"), +}; +/** + * Creates a new {@link TracingContext} with the given options. + * @param options - A set of known keys that may be set on the context. + * @returns A new {@link TracingContext} with the given options. + * + * @internal + */ +export function createTracingContext(options = {}) { + let context = new TracingContextImpl(options.parentContext); + if (options.span) { + context = context.setValue(knownContextKeys.span, options.span); + } + if (options.namespace) { + context = context.setValue(knownContextKeys.namespace, options.namespace); + } + return context; +} +/** @internal */ +export class TracingContextImpl { + constructor(initialContext) { + this._contextMap = + initialContext instanceof TracingContextImpl + ? new Map(initialContext._contextMap) + : new Map(); + } + setValue(key, value) { + const newContext = new TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } +} +//# sourceMappingURL=tracingContext.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js.map b/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js.map new file mode 100644 index 0000000..375db09 --- /dev/null +++ b/node_modules/@azure/core-tracing/dist-esm/src/tracingContext.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tracingContext.js","sourceRoot":"","sources":["../../src/tracingContext.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,gBAAgB;AAChB,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,0BAA0B,CAAC;IAC5C,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC;CACvD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAuC,EAAE;IAC5E,IAAI,OAAO,GAAmB,IAAI,kBAAkB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IAC5E,IAAI,OAAO,CAAC,IAAI,EAAE;QAChB,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;KACjE;IACD,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;KAC3E;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gBAAgB;AAChB,MAAM,OAAO,kBAAkB;IAE7B,YAAY,cAA+B;QACzC,IAAI,CAAC,WAAW;YACd,cAAc,YAAY,kBAAkB;gBAC1C,CAAC,CAAC,IAAI,GAAG,CAAkB,cAAc,CAAC,WAAW,CAAC;gBACtD,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,QAAQ,CAAC,GAAW,EAAE,KAAc;QAClC,MAAM,UAAU,GAAG,IAAI,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAChD,UAAU,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACvC,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,QAAQ,CAAC,GAAW;QAClB,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;IAED,WAAW,CAAC,GAAW;QACrB,MAAM,UAAU,GAAG,IAAI,kBAAkB,CAAC,IAAI,CAAC,CAAC;QAChD,UAAU,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACnC,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TracingContext, TracingSpan } from \"./interfaces\";\n\n/** @internal */\nexport const knownContextKeys = {\n span: Symbol.for(\"@azure/core-tracing span\"),\n namespace: Symbol.for(\"@azure/core-tracing namespace\"),\n};\n\n/**\n * Creates a new {@link TracingContext} with the given options.\n * @param options - A set of known keys that may be set on the context.\n * @returns A new {@link TracingContext} with the given options.\n *\n * @internal\n */\nexport function createTracingContext(options: CreateTracingContextOptions = {}): TracingContext {\n let context: TracingContext = new TracingContextImpl(options.parentContext);\n if (options.span) {\n context = context.setValue(knownContextKeys.span, options.span);\n }\n if (options.namespace) {\n context = context.setValue(knownContextKeys.namespace, options.namespace);\n }\n return context;\n}\n\n/** @internal */\nexport class TracingContextImpl implements TracingContext {\n private _contextMap: Map;\n constructor(initialContext?: TracingContext) {\n this._contextMap =\n initialContext instanceof TracingContextImpl\n ? new Map(initialContext._contextMap)\n : new Map();\n }\n\n setValue(key: symbol, value: unknown): TracingContext {\n const newContext = new TracingContextImpl(this);\n newContext._contextMap.set(key, value);\n return newContext;\n }\n\n getValue(key: symbol): unknown {\n return this._contextMap.get(key);\n }\n\n deleteValue(key: symbol): TracingContext {\n const newContext = new TracingContextImpl(this);\n newContext._contextMap.delete(key);\n return newContext;\n }\n}\n\n/**\n * Represents a set of items that can be set when creating a new {@link TracingContext}.\n */\nexport interface CreateTracingContextOptions {\n /** The {@link parentContext} - the newly created context will contain all the values of the parent context unless overridden. */\n parentContext?: TracingContext;\n /** An initial span to set on the context. */\n span?: TracingSpan;\n /** The namespace to set on any child spans. */\n namespace?: string;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-tracing/package.json b/node_modules/@azure/core-tracing/package.json new file mode 100644 index 0000000..ef10e5e --- /dev/null +++ b/node_modules/@azure/core-tracing/package.json @@ -0,0 +1,101 @@ +{ + "name": "@azure/core-tracing", + "version": "1.0.1", + "description": "Provides low-level interfaces and helper methods for tracing in Azure SDK", + "sdk-type": "client", + "main": "dist/index.js", + "module": "dist-esm/src/index.js", + "browser": {}, + "react-native": { + "./dist/index.js": "./dist-esm/src/index.js" + }, + "types": "types/core-tracing.d.ts", + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "karma start --single-run", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/core-tracing.d.ts", + "README.md", + "LICENSE" + ], + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "tracing", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "engines": { + "node": ">=12.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-tracing/README.md", + "sideEffects": false, + "dependencies": { + "tslib": "^2.2.0" + }, + "devDependencies": { + "@azure/core-auth": "^1.3.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@microsoft/api-extractor": "7.18.11", + "@types/chai": "^4.1.6", + "@types/mocha": "^7.0.2", + "@types/node": "^12.0.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "eslint": "^7.15.0", + "inherits": "^2.0.3", + "karma": "^6.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-edge-launcher": "^0.4.2", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.3.8", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "prettier": "^2.5.1", + "rimraf": "^3.0.0", + "typescript": "~4.6.0", + "util": "^0.12.1", + "sinon": "^9.0.2", + "@types/sinon": "^9.0.4" + }, + "//sampleConfiguration": { + "disableDocsMs": true, + "productName": "Azure SDK Core", + "productSlugs": [ + "azure" + ] + } +} diff --git a/node_modules/@azure/core-tracing/types/core-tracing.d.ts b/node_modules/@azure/core-tracing/types/core-tracing.d.ts new file mode 100644 index 0000000..6871feb --- /dev/null +++ b/node_modules/@azure/core-tracing/types/core-tracing.d.ts @@ -0,0 +1,284 @@ +/** + * Creates a new tracing client. + * + * @param options - Options used to configure the tracing client. + * @returns - An instance of {@link TracingClient}. + */ +export declare function createTracingClient(options: TracingClientOptions): TracingClient; + +/** + * Represents an implementation agnostic instrumenter. + */ +export declare interface Instrumenter { + /** + * Creates a new {@link TracingSpan} with the given name and options and sets it on a new context. + * @param name - The name of the span. By convention this should be `${className}.${methodName}`. + * @param spanOptions - The options to use when creating the span. + * + * @returns A {@link TracingSpan} that can be used to end the span, and the context this span has been set on. + */ + startSpan(name: string, spanOptions: InstrumenterSpanOptions): { + span: TracingSpan; + tracingContext: TracingContext; + }; + /** + * Wraps a callback with an active context and calls the callback. + * Depending on the implementation, this may set the globally available active context. + * + * @param context - The {@link TracingContext} to use as the active context in the scope of the callback. + * @param callback - The callback to be invoked with the given context set as the globally active context. + * @param callbackArgs - The callback arguments. + */ + withContext ReturnType>(context: TracingContext, callback: Callback, ...callbackArgs: CallbackArgs): ReturnType; + /** + * Provides an implementation-specific method to parse a {@link https://www.w3.org/TR/trace-context/#traceparent-header} + * into a {@link TracingSpanContext} which can be used to link non-parented spans together. + */ + parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined; + /** + * Provides an implementation-specific method to serialize a {@link TracingSpan} to a set of headers. + * @param tracingContext - The context containing the span to serialize. + */ + createRequestHeaders(tracingContext?: TracingContext): Record; +} + +/** + * Options passed to {@link Instrumenter.startSpan} as a superset of {@link TracingSpanOptions}. + */ +export declare interface InstrumenterSpanOptions extends TracingSpanOptions { + /** The name of the package invoking this trace. */ + packageName: string; + /** The version of the package invoking this trace. */ + packageVersion?: string; + /** The current tracing context. Defaults to an implementation-specific "active" context. */ + tracingContext?: TracingContext; +} + +/** + * Tracing options to set on an operation. + */ +export declare interface OperationTracingOptions { + /** The context to use for created Tracing Spans. */ + tracingContext?: TracingContext; +} + +/** + * A utility type for when we know a TracingContext has been set + * as part of an operation's options. + */ +export declare type OptionsWithTracingContext = Options & { + tracingOptions: { + tracingContext: TracingContext; + }; +}; + +/** + * A narrower version of TypeScript 4.5's Awaited type which Recursively + * unwraps the "awaited type", emulating the behavior of `await`. + */ +export declare type Resolved = T extends { + then(onfulfilled: infer F): any; +} ? F extends (value: infer V) => any ? Resolved : never : T; + +/** + * Represents the statuses that can be passed to {@link TracingSpan.setStatus}. + * + * By default, all spans will be created with status "unset". + */ +export declare type SpanStatus = SpanStatusSuccess | SpanStatusError; + +/** + * Status representing an error that can be sent to {@link TracingSpan.setStatus} + */ +export declare type SpanStatusError = { + status: "error"; + error?: Error | string; +}; + +/** + * Status representing a successful operation that can be sent to {@link TracingSpan.setStatus} + */ +export declare type SpanStatusSuccess = { + status: "success"; +}; + +/** + * Represents a client that can integrate with the currently configured {@link Instrumenter}. + * + * Create an instance using {@link createTracingClient}. + */ +export declare interface TracingClient { + /** + * Wraps a callback in a tracing span, calls the callback, and closes the span. + * + * This is the primary interface for using Tracing and will handle error recording as well as setting the status on the span. + * + * Both synchronous and asynchronous functions will be awaited in order to reflect the result of the callback on the span. + * + * Example: + * + * ```ts + * const myOperationResult = await tracingClient.withSpan("myClassName.myOperationName", options, (updatedOptions) => myOperation(updatedOptions)); + * ``` + * @param name - The name of the span. By convention this should be `${className}.${methodName}`. + * @param operationOptions - The original options passed to the method. The callback will receive these options with the newly created {@link TracingContext}. + * @param callback - The callback to be invoked with the updated options and newly created {@link TracingSpan}. + */ + withSpan) => ReturnType>(name: string, operationOptions: Options, callback: Callback, spanOptions?: TracingSpanOptions): Promise>>; + /** + * Starts a given span but does not set it as the active span. + * + * You must end the span using {@link TracingSpan.end}. + * + * Most of the time you will want to use {@link withSpan} instead. + * + * @param name - The name of the span. By convention this should be `${className}.${methodName}`. + * @param operationOptions - The original operation options. + * @param spanOptions - The options to use when creating the span. + * + * @returns A {@link TracingSpan} and the updated operation options. + */ + startSpan(name: string, operationOptions?: Options, spanOptions?: TracingSpanOptions): { + span: TracingSpan; + updatedOptions: OptionsWithTracingContext; + }; + /** + * Wraps a callback with an active context and calls the callback. + * Depending on the implementation, this may set the globally available active context. + * + * Useful when you want to leave the boundaries of the SDK (make a request or callback to user code) and are unable to use the {@link withSpan} API. + * + * @param context - The {@link TracingContext} to use as the active context in the scope of the callback. + * @param callback - The callback to be invoked with the given context set as the globally active context. + * @param callbackArgs - The callback arguments. + */ + withContext ReturnType>(context: TracingContext, callback: Callback, ...callbackArgs: CallbackArgs): ReturnType; + /** + * Parses a traceparent header value into a {@link TracingSpanContext}. + * + * @param traceparentHeader - The traceparent header to parse. + * @returns An implementation-specific identifier for the span. + */ + parseTraceparentHeader(traceparentHeader: string): TracingContext | undefined; + /** + * Creates a set of request headers to propagate tracing information to a backend. + * + * @param tracingContext - The context containing the span to propagate. + * @returns The set of headers to add to a request. + */ + createRequestHeaders(tracingContext?: TracingContext): Record; +} + +/** + * Options that can be passed to {@link createTracingClient} + */ +export declare interface TracingClientOptions { + /** The value of the az.namespace tracing attribute on newly created spans. */ + namespace: string; + /** The name of the package invoking this trace. */ + packageName: string; + /** An optional version of the package invoking this trace. */ + packageVersion?: string; +} + +/** An immutable context bag of tracing values for the current operation. */ +export declare interface TracingContext { + /** + * Sets a given object on a context. + * @param key - The key of the given context value. + * @param value - The value to set on the context. + * + * @returns - A new context with the given value set. + */ + setValue(key: symbol, value: unknown): TracingContext; + /** + * Gets an object from the context if it exists. + * @param key - The key of the given context value. + * + * @returns - The value of the given context value if it exists, otherwise `undefined`. + */ + getValue(key: symbol): unknown; + /** + * Deletes an object from the context if it exists. + * @param key - The key of the given context value to delete. + */ + deleteValue(key: symbol): TracingContext; +} + +/** + * Represents an implementation agnostic tracing span. + */ +export declare interface TracingSpan { + /** + * Sets the status of the span. When an error is provided, it will be recorded on the span as well. + * + * @param status - The {@link SpanStatus} to set on the span. + */ + setStatus(status: SpanStatus): void; + /** + * Sets a given attribute on a span. + * + * @param name - The attribute's name. + * @param value - The attribute's value to set. May be any non-nullish value. + */ + setAttribute(name: string, value: unknown): void; + /** + * Ends the span. + */ + end(): void; + /** + * Records an exception on a {@link TracingSpan} without modifying its status. + * + * When recording an unhandled exception that should fail the span, please use {@link TracingSpan.setStatus} instead. + * + * @param exception - The exception to record on the span. + * + */ + recordException(exception: Error | string): void; + /** + * Returns true if this {@link TracingSpan} is recording information. + * + * Depending on the span implementation, this may return false if the span is not being sampled. + */ + isRecording(): boolean; +} + +/** The kind of span. */ +export declare type TracingSpanKind = "client" | "server" | "producer" | "consumer" | "internal"; + +/** A pointer from the current {@link TracingSpan} to another span in the same or a different trace. */ +export declare interface TracingSpanLink { + /** The {@link TracingContext} containing the span context to link to. */ + tracingContext: TracingContext; + /** A set of attributes on the link. */ + attributes?: { + [key: string]: unknown; + }; +} + +/** Options used to configure the newly created span. */ +export declare interface TracingSpanOptions { + /** The kind of span. Implementations should default this to "client". */ + spanKind?: TracingSpanKind; + /** A collection of {@link TracingSpanLink} to link to this span. */ + spanLinks?: TracingSpanLink[]; + /** Initial set of attributes to set on a span. */ + spanAttributes?: { + [key: string]: unknown; + }; +} + +/** + * Extends the Azure SDK with support for a given instrumenter implementation. + * + * @param instrumenter - The instrumenter implementation to use. + */ +export declare function useInstrumenter(instrumenter: Instrumenter): void; + +export { } diff --git a/node_modules/@azure/core-util/LICENSE b/node_modules/@azure/core-util/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/core-util/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/core-util/README.md b/node_modules/@azure/core-util/README.md new file mode 100644 index 0000000..516ba51 --- /dev/null +++ b/node_modules/@azure/core-util/README.md @@ -0,0 +1,40 @@ +# Azure Core Util client library for JavaScript (Experimental) + +This library is intended to provide various shared utility functions for client SDK packages. + +## Getting started + +### Requirements + +### Currently supported environments + +- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) +- Latest versions of Safari, Chrome, Edge, and Firefox. + +See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. + +### Installation + +This package is primarily used in authoring client SDKs and not meant to be consumed directly by end users. + +## Key concepts + +Utility methods provided by this library should be stateless. + +## Examples + +Examples can be found in the `samples` folder. + +## Next steps + +Look at usage in dependent client SDKs. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Fcore-util%2FREADME.png) diff --git a/node_modules/@azure/core-util/dist-esm/src/base64.browser.js b/node_modules/@azure/core-util/dist-esm/src/base64.browser.js new file mode 100644 index 0000000..44324ea --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/base64.browser.js @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Converts a base64 string into a byte array. + * @param content - The base64 string to convert. + * @internal + */ +export function base64ToBytes(content) { + if (typeof atob !== "function") { + throw new Error(`Your browser environment is missing the global "atob" function.`); + } + const binary = atob(content); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} +/** + * Converts an ArrayBuffer to base64 string. + * @param buffer - Raw binary data. + * @internal + */ +export function bufferToBase64(buffer) { + if (typeof btoa !== "function") { + throw new Error(`Your browser environment is missing the global "btoa" function.`); + } + const bytes = new Uint8Array(buffer); + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} +//# sourceMappingURL=base64.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/base64.browser.js.map b/node_modules/@azure/core-util/dist-esm/src/base64.browser.js.map new file mode 100644 index 0000000..f06f731 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/base64.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base64.browser.js","sourceRoot":"","sources":["../../src/base64.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAQlC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;QAC9B,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;KACpF;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;KACjC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,MAAmB;IAChD,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;QAC9B,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;KACpF;IAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACxB,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;KACrC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\ndeclare global {\n // stub these out for the browser\n function btoa(input: string): string;\n function atob(input: string): string;\n}\n\n/**\n * Converts a base64 string into a byte array.\n * @param content - The base64 string to convert.\n * @internal\n */\nexport function base64ToBytes(content: string): Uint8Array {\n if (typeof atob !== \"function\") {\n throw new Error(`Your browser environment is missing the global \"atob\" function.`);\n }\n\n const binary = atob(content);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n\n return bytes;\n}\n\n/**\n * Converts an ArrayBuffer to base64 string.\n * @param buffer - Raw binary data.\n * @internal\n */\nexport function bufferToBase64(buffer: ArrayBuffer): string {\n if (typeof btoa !== \"function\") {\n throw new Error(`Your browser environment is missing the global \"btoa\" function.`);\n }\n\n const bytes = new Uint8Array(buffer);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js b/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js new file mode 100644 index 0000000..28c0d5a --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { AbortError } from "@azure/abort-controller"; +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +export function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + function rejectOnAbort() { + reject(new AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } + catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); +} +//# sourceMappingURL=createAbortablePromise.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js.map b/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js.map new file mode 100644 index 0000000..f6e2d79 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/createAbortablePromise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"createAbortablePromise.js","sourceRoot":"","sources":["../../src/createAbortablePromise.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAmB,MAAM,yBAAyB,CAAC;AActE;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,YAGS,EACT,OAAuC;IAEvC,MAAM,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IACzE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,SAAS,aAAa;YACpB,MAAM,CAAC,IAAI,UAAU,CAAC,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,4BAA4B,CAAC,CAAC,CAAC;QACxE,CAAC;QACD,SAAS,eAAe;YACtB,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACrD,CAAC;QACD,SAAS,OAAO;YACd,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,EAAI,CAAC;YACvB,eAAe,EAAE,CAAC;YAClB,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,IAAI,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,OAAO,EAAE;YACxB,OAAO,aAAa,EAAE,CAAC;SACxB;QACD,IAAI;YACF,YAAY,CACV,CAAC,CAAC,EAAE,EAAE;gBACJ,eAAe,EAAE,CAAC;gBAClB,OAAO,CAAC,CAAC,CAAC,CAAC;YACb,CAAC,EACD,CAAC,CAAC,EAAE,EAAE;gBACJ,eAAe,EAAE,CAAC;gBAClB,MAAM,CAAC,CAAC,CAAC,CAAC;YACZ,CAAC,CACF,CAAC;SACH;QAAC,OAAO,GAAG,EAAE;YACZ,MAAM,CAAC,GAAG,CAAC,CAAC;SACb;QACD,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\n\n/**\n * Options for the createAbortablePromise function.\n */\nexport interface CreateAbortablePromiseOptions {\n /** A function to be called if the promise was aborted */\n cleanupBeforeAbort?: () => void;\n /** An abort signal */\n abortSignal?: AbortSignalLike;\n /** An abort error message */\n abortErrorMsg?: string;\n}\n\n/**\n * Creates an abortable promise.\n * @param buildPromise - A function that takes the resolve and reject functions as parameters.\n * @param options - The options for the abortable promise.\n * @returns A promise that can be aborted.\n */\nexport function createAbortablePromise(\n buildPromise: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n ) => void,\n options?: CreateAbortablePromiseOptions\n): Promise {\n const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};\n return new Promise((resolve, reject) => {\n function rejectOnAbort(): void {\n reject(new AbortError(abortErrorMsg ?? \"The operation was aborted.\"));\n }\n function removeListeners(): void {\n abortSignal?.removeEventListener(\"abort\", onAbort);\n }\n function onAbort(): void {\n cleanupBeforeAbort?.();\n removeListeners();\n rejectOnAbort();\n }\n if (abortSignal?.aborted) {\n return rejectOnAbort();\n }\n try {\n buildPromise(\n (x) => {\n removeListeners();\n resolve(x);\n },\n (x) => {\n removeListeners();\n reject(x);\n }\n );\n } catch (err) {\n reject(err);\n }\n abortSignal?.addEventListener(\"abort\", onAbort);\n });\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/delay.js b/node_modules/@azure/core-util/dist-esm/src/delay.js new file mode 100644 index 0000000..42003ee --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/delay.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createAbortablePromise } from "./createAbortablePromise"; +const StandardAbortMessage = "The delay was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +export function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return createAbortablePromise((resolve) => { + token = setTimeout(resolve, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, + }); +} +//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/delay.js.map b/node_modules/@azure/core-util/dist-esm/src/delay.js.map new file mode 100644 index 0000000..d211527 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/delay.js.map @@ -0,0 +1 @@ +{"version":3,"file":"delay.js","sourceRoot":"","sources":["../../src/delay.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE,MAAM,oBAAoB,GAAG,wBAAwB,CAAC;AAgBtD;;;;;GAKG;AACH,MAAM,UAAU,KAAK,CAAC,QAAgB,EAAE,OAAsB;IAC5D,IAAI,KAAoC,CAAC;IACzC,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC;IACrD,OAAO,sBAAsB,CAC3B,CAAC,OAAO,EAAE,EAAE;QACV,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IACxC,CAAC,EACD;QACE,kBAAkB,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC;QAC7C,WAAW;QACX,aAAa,EAAE,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,oBAAoB;KACrD,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { createAbortablePromise } from \"./createAbortablePromise\";\n\nconst StandardAbortMessage = \"The delay was aborted.\";\n\n/**\n * Options for support abort functionality for the delay method\n */\nexport interface DelayOptions {\n /**\n * The abortSignal associated with containing operation.\n */\n abortSignal?: AbortSignalLike;\n /**\n * The abort error message associated with containing operation.\n */\n abortErrorMsg?: string;\n}\n\n/**\n * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.\n * @param timeInMs - The number of milliseconds to be delayed.\n * @param options - The options for delay - currently abort options\n * @returns Promise that is resolved after timeInMs\n */\nexport function delay(timeInMs: number, options?: DelayOptions): Promise {\n let token: ReturnType;\n const { abortSignal, abortErrorMsg } = options ?? {};\n return createAbortablePromise(\n (resolve) => {\n token = setTimeout(resolve, timeInMs);\n },\n {\n cleanupBeforeAbort: () => clearTimeout(token),\n abortSignal,\n abortErrorMsg: abortErrorMsg ?? StandardAbortMessage,\n }\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/error.js b/node_modules/@azure/core-util/dist-esm/src/error.js new file mode 100644 index 0000000..55f1862 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/error.js @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { isObject } from "./object"; +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +export function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +export function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } + else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } + else { + stringified = String(e); + } + } + catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/error.js.map b/node_modules/@azure/core-util/dist-esm/src/error.js.map new file mode 100644 index 0000000..4b7c633 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../../src/error.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC;;;GAGG;AACH,MAAM,UAAU,OAAO,CAAC,CAAU;IAChC,IAAI,QAAQ,CAAC,CAAC,CAAC,EAAE;QACf,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC;QAC3C,MAAM,UAAU,GAAG,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ,CAAC;QACjD,OAAO,OAAO,IAAI,UAAU,CAAC;KAC9B;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,CAAU;IACxC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE;QACd,OAAO,CAAC,CAAC,OAAO,CAAC;KAClB;SAAM;QACL,IAAI,WAAmB,CAAC;QACxB,IAAI;YACF,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,EAAE;gBAC9B,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;aACjC;iBAAM;gBACL,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;aACzB;SACF;QAAC,OAAO,GAAQ,EAAE;YACjB,WAAW,GAAG,6BAA6B,CAAC;SAC7C;QACD,OAAO,iBAAiB,WAAW,EAAE,CAAC;KACvC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isObject } from \"./object\";\n\n/**\n * Typeguard for an error object shape (has name and message)\n * @param e - Something caught by a catch clause.\n */\nexport function isError(e: unknown): e is Error {\n if (isObject(e)) {\n const hasName = typeof e.name === \"string\";\n const hasMessage = typeof e.message === \"string\";\n return hasName && hasMessage;\n }\n return false;\n}\n\n/**\n * Given what is thought to be an error object, return the message if possible.\n * If the message is missing, returns a stringified version of the input.\n * @param e - Something thrown from a try block\n * @returns The error message or a string of the input\n */\nexport function getErrorMessage(e: unknown): string {\n if (isError(e)) {\n return e.message;\n } else {\n let stringified: string;\n try {\n if (typeof e === \"object\" && e) {\n stringified = JSON.stringify(e);\n } else {\n stringified = String(e);\n }\n } catch (err: any) {\n stringified = \"[unable to stringify input]\";\n }\n return `Unknown error ${stringified}`;\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/hex.js b/node_modules/@azure/core-util/dist-esm/src/hex.js new file mode 100644 index 0000000..13502ef --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/hex.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param buffer - Raw binary data. + * @internal + */ +export function bufferToHex(buffer) { + const bytes = new Uint8Array(buffer); + return Array.prototype.map.call(bytes, byteToHex).join(""); +} +/** + * Converts a byte to a hexadecimal string. + * @param byte - An integer representation of a byte. + * @internal + */ +function byteToHex(byte) { + const hex = byte.toString(16); + return hex.length === 2 ? hex : `0${hex}`; +} +//# sourceMappingURL=hex.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/hex.js.map b/node_modules/@azure/core-util/dist-esm/src/hex.js.map new file mode 100644 index 0000000..704dfab --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/hex.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hex.js","sourceRoot":"","sources":["../../src/hex.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,MAAmB;IAC7C,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED;;;;GAIG;AACH,SAAS,SAAS,CAAC,IAAY;IAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC9B,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Converts an ArrayBuffer to a hexadecimal string.\n * @param buffer - Raw binary data.\n * @internal\n */\nexport function bufferToHex(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n return Array.prototype.map.call(bytes, byteToHex).join(\"\");\n}\n\n/**\n * Converts a byte to a hexadecimal string.\n * @param byte - An integer representation of a byte.\n * @internal\n */\nfunction byteToHex(byte: number): string {\n const hex = byte.toString(16);\n return hex.length === 2 ? hex : `0${hex}`;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/index.js b/node_modules/@azure/core-util/dist-esm/src/index.js new file mode 100644 index 0000000..41ba101 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/index.js @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export { isNode } from "./isNode"; +export { delay } from "./delay"; +export { createAbortablePromise } from "./createAbortablePromise"; +export { getRandomIntegerInclusive } from "./random"; +export { isObject } from "./object"; +export { isError, getErrorMessage } from "./error"; +export { computeSha256Hash, computeSha256Hmac } from "./sha256"; +export { isDefined, isObjectWithProperties, objectHasProperty } from "./typeGuards"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/index.js.map b/node_modules/@azure/core-util/dist-esm/src/index.js.map new file mode 100644 index 0000000..20bc15d --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,KAAK,EAAgB,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAiC,MAAM,0BAA0B,CAAC;AACjG,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAiB,MAAM,UAAU,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { isNode } from \"./isNode\";\nexport { delay, DelayOptions } from \"./delay\";\nexport { createAbortablePromise, CreateAbortablePromiseOptions } from \"./createAbortablePromise\";\nexport { getRandomIntegerInclusive } from \"./random\";\nexport { isObject, UnknownObject } from \"./object\";\nexport { isError, getErrorMessage } from \"./error\";\nexport { computeSha256Hash, computeSha256Hmac } from \"./sha256\";\nexport { isDefined, isObjectWithProperties, objectHasProperty } from \"./typeGuards\";\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js b/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js new file mode 100644 index 0000000..b1bbe8c --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export const isNode = false; +//# sourceMappingURL=isNode.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js.map b/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js.map new file mode 100644 index 0000000..2bfec9f --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/isNode.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"isNode.browser.js","sourceRoot":"","sources":["../../src/isNode.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A constant that indicates whether the environment the code is running is Node.JS.\n */\nexport const isNode = false;\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/isNode.js b/node_modules/@azure/core-util/dist-esm/src/isNode.js new file mode 100644 index 0000000..45f7afc --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/isNode.js @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node); +//# sourceMappingURL=isNode.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/isNode.js.map b/node_modules/@azure/core-util/dist-esm/src/isNode.js.map new file mode 100644 index 0000000..0c10a03 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/isNode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"isNode.js","sourceRoot":"","sources":["../../src/isNode.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAA,OAAO,CAAC,QAAQ,0CAAE,IAAI,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A constant that indicates whether the environment the code is running is Node.JS.\n */\nexport const isNode =\n typeof process !== \"undefined\" && Boolean(process.version) && Boolean(process.versions?.node);\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/object.js b/node_modules/@azure/core-util/dist-esm/src/object.js new file mode 100644 index 0000000..ff04af8 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/object.js @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +export function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); +} +//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/object.js.map b/node_modules/@azure/core-util/dist-esm/src/object.js.map new file mode 100644 index 0000000..3a5f096 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object.js","sourceRoot":"","sources":["../../src/object.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAOlC;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACrB,CAAC,CAAC,KAAK,YAAY,MAAM,CAAC;QAC1B,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CACzB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A generic shape for a plain JS object.\n */\nexport type UnknownObject = { [s: string]: unknown };\n\n/**\n * Helper to determine when an input is a generic JS object.\n * @returns true when input is an object type that is not null, Array, RegExp, or Date.\n */\nexport function isObject(input: unknown): input is UnknownObject {\n return (\n typeof input === \"object\" &&\n input !== null &&\n !Array.isArray(input) &&\n !(input instanceof RegExp) &&\n !(input instanceof Date)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/random.js b/node_modules/@azure/core-util/dist-esm/src/random.js new file mode 100644 index 0000000..aef3288 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/random.js @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +export function getRandomIntegerInclusive(min, max) { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/random.js.map b/node_modules/@azure/core-util/dist-esm/src/random.js.map new file mode 100644 index 0000000..93d4d74 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/random.js.map @@ -0,0 +1 @@ +{"version":3,"file":"random.js","sourceRoot":"","sources":["../../src/random.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;;;;GAOG;AACH,MAAM,UAAU,yBAAyB,CAAC,GAAW,EAAE,GAAW;IAChE,iCAAiC;IACjC,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACrB,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACtB,2DAA2D;IAC3D,+EAA+E;IAC/E,yEAAyE;IACzE,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IAC3D,OAAO,MAAM,GAAG,GAAG,CAAC;AACtB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Returns a random integer value between a lower and upper bound,\n * inclusive of both bounds.\n * Note that this uses Math.random and isn't secure. If you need to use\n * this for any kind of security purpose, find a better source of random.\n * @param min - The smallest integer value allowed.\n * @param max - The largest integer value allowed.\n */\nexport function getRandomIntegerInclusive(min: number, max: number): number {\n // Make sure inputs are integers.\n min = Math.ceil(min);\n max = Math.floor(max);\n // Pick a random offset from zero to the size of the range.\n // Since Math.random() can never return 1, we have to make the range one larger\n // in order to be inclusive of the maximum value after we take the floor.\n const offset = Math.floor(Math.random() * (max - min + 1));\n return offset + min;\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js b/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js new file mode 100644 index 0000000..3cdba8e --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { base64ToBytes, bufferToBase64 } from "./base64.browser"; +import { bufferToHex } from "./hex"; +import { utf8ToBytes } from "./utf8.browser"; +let subtleCrypto; +/** + * Returns a cached reference to the Web API crypto.subtle object. + * @internal + */ +function getCrypto() { + if (subtleCrypto) { + return subtleCrypto; + } + if (!self.crypto || !self.crypto.subtle) { + throw new Error("Your browser environment does not support cryptography functions."); + } + subtleCrypto = self.crypto.subtle; + return subtleCrypto; +} +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +export async function computeSha256Hmac(key, stringToSign, encoding) { + const crypto = getCrypto(); + const keyBytes = base64ToBytes(key); + const stringToSignBytes = utf8ToBytes(stringToSign); + const cryptoKey = await crypto.importKey("raw", keyBytes, { + name: "HMAC", + hash: { name: "SHA-256" }, + }, false, ["sign"]); + const signature = await crypto.sign({ + name: "HMAC", + hash: { name: "SHA-256" }, + }, cryptoKey, stringToSignBytes); + switch (encoding) { + case "base64": + return bufferToBase64(signature); + case "hex": + return bufferToHex(signature); + } +} +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +export async function computeSha256Hash(content, encoding) { + const contentBytes = utf8ToBytes(content); + const digest = await getCrypto().digest({ name: "SHA-256" }, contentBytes); + switch (encoding) { + case "base64": + return bufferToBase64(digest); + case "hex": + return bufferToHex(digest); + } +} +//# sourceMappingURL=sha256.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js.map b/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js.map new file mode 100644 index 0000000..a92331f --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/sha256.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.browser.js","sourceRoot":"","sources":["../../src/sha256.browser.ts"],"names":[],"mappings":"A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;QACnC,KAAK,KAAK;YACR,OAAO,WAAW,CAAC,SAAS,CAAC,CAAC;KACjC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAe,EACf,QAA0B;IAE1B,MAAM,YAAY,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,MAAM,SAAS,EAAE,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,YAAY,CAAC,CAAC;IAE3E,QAAQ,QAAQ,EAAE;QAChB,KAAK,QAAQ;YACX,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;QAChC,KAAK,KAAK;YACR,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC;KAC9B;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { base64ToBytes, bufferToBase64 } from \"./base64.browser\";\nimport { bufferToHex } from \"./hex\";\nimport { utf8ToBytes } from \"./utf8.browser\";\n\n// stubs for browser self.crypto\ninterface JsonWebKey {}\ninterface CryptoKey {}\ntype KeyUsage =\n | \"decrypt\"\n | \"deriveBits\"\n | \"deriveKey\"\n | \"encrypt\"\n | \"sign\"\n | \"unwrapKey\"\n | \"verify\"\n | \"wrapKey\";\ninterface Algorithm {\n name: string;\n}\ninterface SubtleCrypto {\n importKey(\n format: string,\n keyData: JsonWebKey,\n algorithm: HmacImportParams,\n extractable: boolean,\n usage: KeyUsage[]\n ): Promise;\n sign(\n algorithm: HmacImportParams,\n key: CryptoKey,\n data: ArrayBufferView | ArrayBuffer\n ): Promise;\n digest(algorithm: Algorithm, data: ArrayBufferView | ArrayBuffer): Promise;\n}\ninterface Crypto {\n readonly subtle: SubtleCrypto;\n getRandomValues(array: T): T;\n}\ndeclare const self: {\n crypto: Crypto;\n};\ninterface HmacImportParams {\n name: string;\n hash: Algorithm;\n length?: number;\n}\n\nlet subtleCrypto: SubtleCrypto | undefined;\n\n/**\n * Returns a cached reference to the Web API crypto.subtle object.\n * @internal\n */\nfunction getCrypto(): SubtleCrypto {\n if (subtleCrypto) {\n return subtleCrypto;\n }\n\n if (!self.crypto || !self.crypto.subtle) {\n throw new Error(\"Your browser environment does not support cryptography functions.\");\n }\n\n subtleCrypto = self.crypto.subtle;\n return subtleCrypto;\n}\n\n/**\n * Generates a SHA-256 HMAC signature.\n * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.\n * @param stringToSign - The data to be signed.\n * @param encoding - The textual encoding to use for the returned HMAC digest.\n */\nexport async function computeSha256Hmac(\n key: string,\n stringToSign: string,\n encoding: \"base64\" | \"hex\"\n): Promise {\n const crypto = getCrypto();\n const keyBytes = base64ToBytes(key);\n const stringToSignBytes = utf8ToBytes(stringToSign);\n\n const cryptoKey = await crypto.importKey(\n \"raw\",\n keyBytes,\n {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n },\n false,\n [\"sign\"]\n );\n const signature = await crypto.sign(\n {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n },\n cryptoKey,\n stringToSignBytes\n );\n\n switch (encoding) {\n case \"base64\":\n return bufferToBase64(signature);\n case \"hex\":\n return bufferToHex(signature);\n }\n}\n\n/**\n * Generates a SHA-256 hash.\n * @param content - The data to be included in the hash.\n * @param encoding - The textual encoding to use for the returned hash.\n */\nexport async function computeSha256Hash(\n content: string,\n encoding: \"base64\" | \"hex\"\n): Promise {\n const contentBytes = utf8ToBytes(content);\n const digest = await getCrypto().digest({ name: \"SHA-256\" }, contentBytes);\n\n switch (encoding) {\n case \"base64\":\n return bufferToBase64(digest);\n case \"hex\":\n return bufferToHex(digest);\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/sha256.js b/node_modules/@azure/core-util/dist-esm/src/sha256.js new file mode 100644 index 0000000..6704d38 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/sha256.js @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { createHash, createHmac } from "crypto"; +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +export async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return createHmac("sha256", decodedKey).update(stringToSign).digest(encoding); +} +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +export async function computeSha256Hash(content, encoding) { + return createHash("sha256").update(content).digest(encoding); +} +//# sourceMappingURL=sha256.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/sha256.js.map b/node_modules/@azure/core-util/dist-esm/src/sha256.js.map new file mode 100644 index 0000000..f21f808 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/sha256.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha256.js","sourceRoot":"","sources":["../../src/sha256.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,GAAW,EACX,YAAoB,EACpB,QAA0B;IAE1B,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE9C,OAAO,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAChF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAe,EACf,QAA0B;IAE1B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createHash, createHmac } from \"crypto\";\n\n/**\n * Generates a SHA-256 HMAC signature.\n * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.\n * @param stringToSign - The data to be signed.\n * @param encoding - The textual encoding to use for the returned HMAC digest.\n */\nexport async function computeSha256Hmac(\n key: string,\n stringToSign: string,\n encoding: \"base64\" | \"hex\"\n): Promise {\n const decodedKey = Buffer.from(key, \"base64\");\n\n return createHmac(\"sha256\", decodedKey).update(stringToSign).digest(encoding);\n}\n\n/**\n * Generates a SHA-256 hash.\n * @param content - The data to be included in the hash.\n * @param encoding - The textual encoding to use for the returned hash.\n */\nexport async function computeSha256Hash(\n content: string,\n encoding: \"base64\" | \"hex\"\n): Promise {\n return createHash(\"sha256\").update(content).digest(encoding);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/typeGuards.js b/node_modules/@azure/core-util/dist-esm/src/typeGuards.js new file mode 100644 index 0000000..f45852d --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/typeGuards.js @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +export function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +export function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +export function objectHasProperty(thing, property) { + return (isDefined(thing) && typeof thing === "object" && property in thing); +} +//# sourceMappingURL=typeGuards.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/typeGuards.js.map b/node_modules/@azure/core-util/dist-esm/src/typeGuards.js.map new file mode 100644 index 0000000..04e168f --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/typeGuards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typeGuards.js","sourceRoot":"","sources":["../../src/typeGuards.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAI,KAA2B;IACtD,OAAO,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,IAAI,CAAC;AACxD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAY,EACZ,UAA0B;IAE1B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE;QACjC,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE;YACvC,OAAO,KAAK,CAAC;SACd;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAY,EACZ,QAAsB;IAEtB,OAAO,CACL,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAK,KAAiC,CAChG,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Helper TypeGuard that checks if something is defined or not.\n * @param thing - Anything\n */\nexport function isDefined(thing: T | undefined | null): thing is T {\n return typeof thing !== \"undefined\" && thing !== null;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified properties.\n * @param thing - Anything.\n * @param properties - The name of the properties that should appear in the object.\n */\nexport function isObjectWithProperties(\n thing: Thing,\n properties: PropertyName[]\n): thing is Thing & Record {\n if (!isDefined(thing) || typeof thing !== \"object\") {\n return false;\n }\n\n for (const property of properties) {\n if (!objectHasProperty(thing, property)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified property.\n * @param thing - Any object.\n * @param property - The name of the property that should appear in the object.\n */\nexport function objectHasProperty(\n thing: Thing,\n property: PropertyName\n): thing is Thing & Record {\n return (\n isDefined(thing) && typeof thing === \"object\" && property in (thing as Record)\n );\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js b/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js new file mode 100644 index 0000000..f31af48 --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +let encoder; +/** + * Returns a cached TextEncoder. + * @internal + */ +function getTextEncoder() { + if (encoder) { + return encoder; + } + if (typeof TextEncoder === "undefined") { + throw new Error(`Your browser environment is missing "TextEncoder".`); + } + encoder = new TextEncoder(); + return encoder; +} +/** + * Converts a utf8 string into a byte array. + * @param content - The utf8 string to convert. + * @internal + */ +export function utf8ToBytes(content) { + return getTextEncoder().encode(content); +} +//# sourceMappingURL=utf8.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js.map b/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js.map new file mode 100644 index 0000000..2c6588b --- /dev/null +++ b/node_modules/@azure/core-util/dist-esm/src/utf8.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utf8.browser.js","sourceRoot":"","sources":["../../src/utf8.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAalC,IAAI,OAAgC,CAAC;AAErC;;;GAGG;AACH,SAAS,cAAc;IACrB,IAAI,OAAO,EAAE;QACX,OAAO,OAAO,CAAC;KAChB;IAED,IAAI,OAAO,WAAW,KAAK,WAAW,EAAE;QACtC,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;KACvE;IAED,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAC5B,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,OAAO,cAAc,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n// stubs for browser TextEncoder\ninterface TextEncoder {\n encode(input?: string): Uint8Array;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\ndeclare const TextEncoder: {\n prototype: TextEncoder;\n new (): TextEncoder;\n};\n\nlet encoder: TextEncoder | undefined;\n\n/**\n * Returns a cached TextEncoder.\n * @internal\n */\nfunction getTextEncoder(): TextEncoder {\n if (encoder) {\n return encoder;\n }\n\n if (typeof TextEncoder === \"undefined\") {\n throw new Error(`Your browser environment is missing \"TextEncoder\".`);\n }\n\n encoder = new TextEncoder();\n return encoder;\n}\n\n/**\n * Converts a utf8 string into a byte array.\n * @param content - The utf8 string to convert.\n * @internal\n */\nexport function utf8ToBytes(content: string): Uint8Array {\n return getTextEncoder().encode(content);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/core-util/package.json b/node_modules/@azure/core-util/package.json new file mode 100644 index 0000000..b230380 --- /dev/null +++ b/node_modules/@azure/core-util/package.json @@ -0,0 +1,109 @@ +{ + "name": "@azure/core-util", + "version": "1.2.0", + "description": "Core library for shared utility methods", + "sdk-type": "client", + "main": "dist/index.js", + "module": "dist-esm/src/index.js", + "browser": { + "./dist-esm/src/isNode.js": "./dist-esm/src/isNode.browser.js", + "./dist-esm/src/sha256.js": "./dist-esm/src/sha256.browser.js" + }, + "react-native": { + "./dist/index.js": "./dist-esm/src/index.js" + }, + "types": "types/latest/core-util.d.ts", + "typesVersions": { + "<3.6": { + "types/latest/*": [ + "types/3.1/*" + ] + } + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build:types": "downlevel-dts types/latest/ types/3.1/", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local && npm run build:types", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "karma start --single-run", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/latest/core-util.d.ts", + "types/3.1/core-util.d.ts", + "README.md", + "LICENSE" + ], + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "engines": { + "node": ">=14.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-util/", + "sideEffects": false, + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "devDependencies": { + "@azure/dev-tool": "^1.0.0", + "@microsoft/api-extractor": "^7.31.1", + "@types/chai": "^4.1.6", + "@types/chai-as-promised": "^7.1.4", + "@types/mocha": "^7.0.2", + "@types/node": "^14.0.0", + "@types/sinon": "^9.0.4", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "chai": "^4.2.0", + "chai-as-promised": "^7.1.1", + "downlevel-dts": "^0.10.0", + "cross-env": "^7.0.2", + "eslint": "^8.0.0", + "inherits": "^2.0.3", + "karma": "^6.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-edge-launcher": "^0.4.2", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.3.8", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "prettier": "^2.5.1", + "rimraf": "^3.0.0", + "sinon": "^9.0.2", + "typescript": "~4.8.0", + "util": "^0.12.1" + } +} diff --git a/node_modules/@azure/core-util/types/3.1/core-util.d.ts b/node_modules/@azure/core-util/types/3.1/core-util.d.ts new file mode 100644 index 0000000..98edd15 --- /dev/null +++ b/node_modules/@azure/core-util/types/3.1/core-util.d.ts @@ -0,0 +1,106 @@ +import { AbortSignalLike } from '@azure/abort-controller'; +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +export declare function computeSha256Hash(content: string, encoding: "base64" | "hex"): Promise; +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +export declare function computeSha256Hmac(key: string, stringToSign: string, encoding: "base64" | "hex"): Promise; +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +export declare function createAbortablePromise(buildPromise: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void, options?: CreateAbortablePromiseOptions): Promise; +/** + * Options for the createAbortablePromise function. + */ +export declare interface CreateAbortablePromiseOptions { + /** A function to be called if the promise was aborted */ + cleanupBeforeAbort?: () => void; + /** An abort signal */ + abortSignal?: AbortSignalLike; + /** An abort error message */ + abortErrorMsg?: string; +} +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +export declare function delay(timeInMs: number, options?: DelayOptions): Promise; +/** + * Options for support abort functionality for the delay method + */ +export declare interface DelayOptions { + /** + * The abortSignal associated with containing operation. + */ + abortSignal?: AbortSignalLike; + /** + * The abort error message associated with containing operation. + */ + abortErrorMsg?: string; +} +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +export declare function getErrorMessage(e: unknown): string; +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +export declare function getRandomIntegerInclusive(min: number, max: number): number; +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +export declare function isDefined(thing: T | undefined | null): thing is T; +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +export declare function isError(e: unknown): e is Error; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export declare const isNode: boolean; +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +export declare function isObject(input: unknown): input is UnknownObject; +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +export declare function isObjectWithProperties(thing: Thing, properties: PropertyName[]): thing is Thing & Record; +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +export declare function objectHasProperty(thing: Thing, property: PropertyName): thing is Thing & Record; +/** + * A generic shape for a plain JS object. + */ +export declare type UnknownObject = { + [s: string]: unknown; +}; +export {}; diff --git a/node_modules/@azure/core-util/types/latest/core-util.d.ts b/node_modules/@azure/core-util/types/latest/core-util.d.ts new file mode 100644 index 0000000..df3cff1 --- /dev/null +++ b/node_modules/@azure/core-util/types/latest/core-util.d.ts @@ -0,0 +1,122 @@ +import { AbortSignalLike } from '@azure/abort-controller'; + +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +export declare function computeSha256Hash(content: string, encoding: "base64" | "hex"): Promise; + +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +export declare function computeSha256Hmac(key: string, stringToSign: string, encoding: "base64" | "hex"): Promise; + +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +export declare function createAbortablePromise(buildPromise: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void, options?: CreateAbortablePromiseOptions): Promise; + +/** + * Options for the createAbortablePromise function. + */ +export declare interface CreateAbortablePromiseOptions { + /** A function to be called if the promise was aborted */ + cleanupBeforeAbort?: () => void; + /** An abort signal */ + abortSignal?: AbortSignalLike; + /** An abort error message */ + abortErrorMsg?: string; +} + +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +export declare function delay(timeInMs: number, options?: DelayOptions): Promise; + +/** + * Options for support abort functionality for the delay method + */ +export declare interface DelayOptions { + /** + * The abortSignal associated with containing operation. + */ + abortSignal?: AbortSignalLike; + /** + * The abort error message associated with containing operation. + */ + abortErrorMsg?: string; +} + +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +export declare function getErrorMessage(e: unknown): string; + +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +export declare function getRandomIntegerInclusive(min: number, max: number): number; + +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +export declare function isDefined(thing: T | undefined | null): thing is T; + +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +export declare function isError(e: unknown): e is Error; + +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +export declare const isNode: boolean; + +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +export declare function isObject(input: unknown): input is UnknownObject; + +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +export declare function isObjectWithProperties(thing: Thing, properties: PropertyName[]): thing is Thing & Record; + +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +export declare function objectHasProperty(thing: Thing, property: PropertyName): thing is Thing & Record; + +/** + * A generic shape for a plain JS object. + */ +export declare type UnknownObject = { + [s: string]: unknown; +}; + +export { } diff --git a/node_modules/@azure/logger/LICENSE b/node_modules/@azure/logger/LICENSE new file mode 100644 index 0000000..ea8fb15 --- /dev/null +++ b/node_modules/@azure/logger/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Microsoft + +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. diff --git a/node_modules/@azure/logger/README.md b/node_modules/@azure/logger/README.md new file mode 100644 index 0000000..058b5db --- /dev/null +++ b/node_modules/@azure/logger/README.md @@ -0,0 +1,132 @@ +# Azure Logger client library for JavaScript + +The `@azure/logger` package can be used to enable logging in the Azure SDKs for JavaScript. + +Logging can be enabled for the Azure SDK in the following ways: + +- Setting the AZURE_LOG_LEVEL environment variable +- Calling setLogLevel imported from "@azure/logger" +- Calling enable() on specific loggers +- Using the `DEBUG` environment variable. + +Note that AZURE_LOG_LEVEL, if set, takes precedence over DEBUG. Only use DEBUG without specifying AZURE_LOG_LEVEL or calling setLogLevel. + +## Getting started + +### Installation + +Install this library using npm as follows + +``` +npm install @azure/logger +``` + +## Key Concepts + +The `@azure/logger` package supports the following log levels +specified in order of most verbose to least verbose: + +- verbose +- info +- warning +- error + +When setting a log level, either programmatically or via the `AZURE_LOG_LEVEL` environment variable, +any logs that are written using a log level equal to or less than the one you choose +will be emitted. + +For example, setting the log level to `warning` will cause all logs that have the log +level `warning` or `error` to be emitted. + + +**NOTE**: When logging requests and responses, we sanitize these objects to make sure things like `Authorization` headers that contain secrets are not logged. + +Request and response bodies are never logged. Headers are redacted by default, unless present in the following list or explicitly allowed by the client SDK: +- "x-ms-client-request-id", +- "x-ms-return-client-request-id", +- "x-ms-useragent", +- "x-ms-correlation-request-id", +- "x-ms-request-id", +- "client-request-id", +- "ms-cv", +- "return-client-request-id", +- "traceparent", +- "Access-Control-Allow-Credentials", +- "Access-Control-Allow-Headers", +- "Access-Control-Allow-Methods", +- "Access-Control-Allow-Origin", +- "Access-Control-Expose-Headers", +- "Access-Control-Max-Age", +- "Access-Control-Request-Headers", +- "Access-Control-Request-Method", +- "Origin", +- "Accept", +- "Accept-Encoding", +- "Cache-Control", +- "Connection", +- "Content-Length", +- "Content-Type", +- "Date", +- "ETag", +- "Expires", +- "If-Match", +- "If-Modified-Since", +- "If-None-Match", +- "If-Unmodified-Since", +- "Last-Modified", +- "Pragma", +- "Request-Id", +- "Retry-After", +- "Server", +- "Transfer-Encoding", +- "User-Agent", +- "WWW-Authenticate", + +## Examples + +### Example 1 - basic usage + +```js +const { EventHubClient } = require('@azure/event-hubs'); + +const logger = require('@azure/logger'); +logger.setLogLevel('info'); + +// operations will now emit info, warning, and error logs +const client = new EventHubClient(/* params */); +client.getPartitionIds() + .then(ids => { /* do work */ }) + .catch(e => { /* do work */ }); +}); +``` + +### Example 2 - redirect log output + +```js +const { AzureLogger, setLogLevel } = require("@azure/logger"); + +setLogLevel("verbose"); + +// override logging to output to console.log (default location is stderr) +AzureLogger.log = (...args) => { + console.log(...args); +}; +``` + +Using `AzureLogger`, it is possible to redirect the logging output from the Azure SDKs by +overriding the `AzureLogger.log` method. This may be useful if you want to redirect logs to +a location other than stderr. + +## Next steps + +You can build and run the tests locally by executing `rushx test`. Explore the `test` folder to see advanced usage and behavior of the public classes. + +## Troubleshooting + +If you run into issues while using this library, please feel free to [file an issue](https://github.com/Azure/azure-sdk-for-js/issues/new). + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcore%2Flogger%2FREADME.png) diff --git a/node_modules/@azure/logger/dist-esm/src/debug.js b/node_modules/@azure/logger/dist-esm/src/debug.js new file mode 100644 index 0000000..d202779 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/debug.js @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { log } from "./log"; +const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; +let enabledString; +let enabledNamespaces = []; +let skippedNamespaces = []; +const debuggers = []; +if (debugEnvVariable) { + enable(debugEnvVariable); +} +const debugObj = Object.assign((namespace) => { + return createDebugger(namespace); +}, { + enable, + enabled, + disable, + log, +}); +function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } + else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } +} +function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; +} +function disable() { + const result = enabledString || ""; + enable(""); + return result; +} +function createDebugger(namespace) { + const newDebugger = Object.assign(debug, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend, + }); + function debug(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; +} +function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; +} +function extend(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; +} +export default debugObj; +//# sourceMappingURL=debug.js.map \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/debug.js.map b/node_modules/@azure/logger/dist-esm/src/debug.js.map new file mode 100644 index 0000000..9dc639a --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/debug.js.map @@ -0,0 +1 @@ +{"version":3,"file":"debug.js","sourceRoot":"","sources":["../../src/debug.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAgE5B,MAAM,gBAAgB,GACpB,CAAC,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC;AAEpF,IAAI,aAAiC,CAAC;AACtC,IAAI,iBAAiB,GAAa,EAAE,CAAC;AACrC,IAAI,iBAAiB,GAAa,EAAE,CAAC;AACrC,MAAM,SAAS,GAAe,EAAE,CAAC;AAEjC,IAAI,gBAAgB,EAAE;IACpB,MAAM,CAAC,gBAAgB,CAAC,CAAC;CAC1B;AAED,MAAM,QAAQ,GAAU,MAAM,CAAC,MAAM,CACnC,CAAC,SAAiB,EAAY,EAAE;IAC9B,OAAO,cAAc,CAAC,SAAS,CAAC,CAAC;AACnC,CAAC,EACD;IACE,MAAM;IACN,OAAO;IACP,OAAO;IACP,GAAG;CACJ,CACF,CAAC;AAEF,SAA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microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { log } from \"./log\";\n\n/**\n * A simple mechanism for enabling logging.\n * Intended to mimic the publicly available `debug` package.\n */\nexport interface Debug {\n /**\n * Creates a new logger with the given namespace.\n */\n (namespace: string): Debugger;\n /**\n * The default log method (defaults to console)\n */\n log: (...args: any[]) => void;\n /**\n * Enables a particular set of namespaces.\n * To enable multiple separate them with commas, e.g. \"info,debug\".\n * Supports wildcards, e.g. \"azure:*\"\n * Supports skip syntax, e.g. \"azure:*,-azure:storage:*\" will enable\n * everything under azure except for things under azure:storage.\n */\n enable: (namespaces: string) => void;\n /**\n * Checks if a particular namespace is enabled.\n */\n enabled: (namespace: string) => boolean;\n /**\n * Disables all logging, returns what was previously enabled.\n */\n disable: () => string;\n}\n\n/**\n * A log function that can be dynamically enabled and redirected.\n */\nexport interface Debugger {\n /**\n * Logs the given arguments to the `log` method.\n */\n (...args: any[]): void;\n /**\n * True if this logger is active and logging.\n */\n enabled: boolean;\n /**\n * Used to cleanup/remove this logger.\n */\n destroy: () => boolean;\n /**\n * The current log method. Can be overridden to redirect output.\n */\n log: (...args: any[]) => void;\n /**\n * The namespace of this logger.\n */\n namespace: string;\n /**\n * Extends this logger with a child namespace.\n * Namespaces are separated with a ':' character.\n */\n extend: (namespace: string) => Debugger;\n}\n\nconst debugEnvVariable =\n (typeof process !== \"undefined\" && process.env && process.env.DEBUG) || undefined;\n\nlet enabledString: string | undefined;\nlet enabledNamespaces: RegExp[] = [];\nlet skippedNamespaces: RegExp[] = [];\nconst debuggers: Debugger[] = [];\n\nif (debugEnvVariable) {\n enable(debugEnvVariable);\n}\n\nconst debugObj: Debug = Object.assign(\n (namespace: string): Debugger => {\n return createDebugger(namespace);\n },\n {\n enable,\n enabled,\n disable,\n log,\n }\n);\n\nfunction enable(namespaces: string): void {\n enabledString = namespaces;\n enabledNamespaces = [];\n skippedNamespaces = [];\n const wildcard = /\\*/g;\n const namespaceList = namespaces.split(\",\").map((ns) => ns.trim().replace(wildcard, \".*?\"));\n for (const ns of namespaceList) {\n if (ns.startsWith(\"-\")) {\n skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));\n } else {\n enabledNamespaces.push(new RegExp(`^${ns}$`));\n }\n }\n for (const instance of debuggers) {\n instance.enabled = enabled(instance.namespace);\n }\n}\n\nfunction enabled(namespace: string): boolean {\n if (namespace.endsWith(\"*\")) {\n return true;\n }\n\n for (const skipped of skippedNamespaces) {\n if (skipped.test(namespace)) {\n return false;\n }\n }\n for (const enabledNamespace of enabledNamespaces) {\n if (enabledNamespace.test(namespace)) {\n return true;\n }\n }\n return false;\n}\n\nfunction disable(): string {\n const result = enabledString || \"\";\n enable(\"\");\n return result;\n}\n\nfunction createDebugger(namespace: string): Debugger {\n const newDebugger: Debugger = Object.assign(debug, {\n enabled: enabled(namespace),\n destroy,\n log: debugObj.log,\n namespace,\n extend,\n });\n\n function debug(...args: any[]): void {\n if (!newDebugger.enabled) {\n return;\n }\n if (args.length > 0) {\n args[0] = `${namespace} ${args[0]}`;\n }\n newDebugger.log(...args);\n }\n\n debuggers.push(newDebugger);\n\n return newDebugger;\n}\n\nfunction destroy(this: Debugger): boolean {\n const index = debuggers.indexOf(this);\n if (index >= 0) {\n debuggers.splice(index, 1);\n return true;\n }\n return false;\n}\n\nfunction extend(this: Debugger, namespace: string): Debugger {\n const newDebugger = createDebugger(`${this.namespace}:${namespace}`);\n newDebugger.log = this.log;\n return newDebugger;\n}\n\nexport default debugObj;\n"]} \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/index.js b/node_modules/@azure/logger/dist-esm/src/index.js new file mode 100644 index 0000000..cc25720 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/index.js @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import debug from "./debug"; +const registeredLoggers = new Set(); +const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; +let azureLogLevel; +/** + * The AzureLogger provides a mechanism for overriding where logs are output to. + * By default, logs are sent to stderr. + * Override the `log` method to redirect logs to another location. + */ +export const AzureLogger = debug("azure"); +AzureLogger.log = (...args) => { + debug.log(...args); +}; +const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +if (logLevelFromEnv) { + // avoid calling setLogLevel because we don't want a mis-set environment variable to crash + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } + else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } +} +/** + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * @param level - The log level to enable for logging. + * Options from most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +export function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces.push(logger.namespace); + } + } + debug.enable(enabledNamespaces.join(",")); +} +/** + * Retrieves the currently specified log level. + */ +export function getLogLevel() { + return azureLogLevel; +} +const levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100, +}; +/** + * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. + * @param namespace - The name of the SDK package. + * @hidden + */ +export function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose"), + }; +} +function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; +} +function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level, + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces = debug.disable(); + debug.enable(enabledNamespaces + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; +} +function shouldEnable(logger) { + return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); +} +function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/index.js.map b/node_modules/@azure/logger/dist-esm/src/index.js.map new file mode 100644 index 0000000..53332f2 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAmB,MAAM,SAAS,CAAC;AAG1C,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAiB,CAAC;AACnD,MAAM,eAAe,GACnB,CAAC,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,SAAS,CAAC;AAE9F,IAAI,aAAwC,CAAC;AAE7C;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAsB,KAAK,CAAC,OAAO,CAAC,CAAC;AAC7D,WAAW,CAAC,GAAG,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE;IAC5B,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;AACrB,CAAC,CAAC;AAWF,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AASjE,IAAI,eAAe,EAAE;IACnB,0FAA0F;IAC1F,IAAI,eAAe,CAAC,eAAe,CAAC,EAAE;QACpC,WAAW,CAAC,eAAe,CAAC,CAAC;KAC9B;SAAM;QACL,OAAO,CAAC,KAAK,CACX,6CAA6C,eAAe,iDAAiD,gBAAgB,CAAC,IAAI,CAChI,IAAI,CACL,GAAG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,CAAC,MAAyB,EAAE,KAAwC;IACzF,KAAK,CAAC,GAAG,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE;QACtB,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;IACtB,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,MAAyB,EAAE,KAAoB;IACnE,MAAM,MAAM,GAAkB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;QAChE,KAAK;KACN,CAAC,CAAC;IAEH,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE/B,IAAI,YAAY,CAAC,MAAM,CAAC,EAAE;QACxB,MAAM,iBAAiB,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;QAC1C,KAAK,CAAC,MAAM,CAAC,iBAAiB,GAAG,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;KAC1D;IAED,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAE9B,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,YAAY,CAAC,MAAqB;IACzC,OAAO,OAAO,CAAC,aAAa,IAAI,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC;AACrF,CAAC;AAED,SAAS,eAAe,CAAC,QAAgB;IACvC,OAAO,gBAAgB,CAAC,QAAQ,CAAC,QAAe,CAAC,CAAC;AACpD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport debug, { Debugger } from \"./debug\";\nexport { Debugger } from \"./debug\";\n\nconst registeredLoggers = new Set();\nconst logLevelFromEnv =\n (typeof process !== \"undefined\" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;\n\nlet azureLogLevel: AzureLogLevel | undefined;\n\n/**\n * The AzureLogger provides a mechanism for overriding where logs are output to.\n * By default, logs are sent to stderr.\n * Override the `log` method to redirect logs to another location.\n */\nexport const AzureLogger: AzureClientLogger = debug(\"azure\");\nAzureLogger.log = (...args) => {\n debug.log(...args);\n};\n\n/**\n * The log levels supported by the logger.\n * The log levels in order of most verbose to least verbose are:\n * - verbose\n * - info\n * - warning\n * - error\n */\nexport type AzureLogLevel = \"verbose\" | \"info\" | \"warning\" | \"error\";\nconst AZURE_LOG_LEVELS = [\"verbose\", \"info\", \"warning\", \"error\"];\n\ntype AzureDebugger = Debugger & { level: AzureLogLevel };\n\n/**\n * An AzureClientLogger is a function that can log to an appropriate severity level.\n */\nexport type AzureClientLogger = Debugger;\n\nif (logLevelFromEnv) {\n // avoid calling setLogLevel because we don't want a mis-set environment variable to crash\n if (isAzureLogLevel(logLevelFromEnv)) {\n setLogLevel(logLevelFromEnv);\n } else {\n console.error(\n `AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(\n \", \"\n )}.`\n );\n }\n}\n\n/**\n * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.\n * @param level - The log level to enable for logging.\n * Options from most verbose to least verbose are:\n * - verbose\n * - info\n * - warning\n * - error\n */\nexport function setLogLevel(level?: AzureLogLevel): void {\n if (level && !isAzureLogLevel(level)) {\n throw new Error(\n `Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(\",\")}`\n );\n }\n azureLogLevel = level;\n\n const enabledNamespaces = [];\n for (const logger of registeredLoggers) {\n if (shouldEnable(logger)) {\n enabledNamespaces.push(logger.namespace);\n }\n }\n\n debug.enable(enabledNamespaces.join(\",\"));\n}\n\n/**\n * Retrieves the currently specified log level.\n */\nexport function getLogLevel(): AzureLogLevel | undefined {\n return azureLogLevel;\n}\n\nconst levelMap = {\n verbose: 400,\n info: 300,\n warning: 200,\n error: 100,\n};\n\n/**\n * Defines the methods available on the SDK-facing logger.\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport interface AzureLogger {\n /**\n * Used for failures the program is unlikely to recover from,\n * such as Out of Memory.\n */\n error: Debugger;\n /**\n * Used when a function fails to perform its intended task.\n * Usually this means the function will throw an exception.\n * Not used for self-healing events (e.g. automatic retry)\n */\n warning: Debugger;\n /**\n * Used when a function operates normally.\n */\n info: Debugger;\n /**\n * Used for detailed troubleshooting scenarios. This is\n * intended for use by developers / system administrators\n * for diagnosing specific failures.\n */\n verbose: Debugger;\n}\n\n/**\n * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.\n * @param namespace - The name of the SDK package.\n * @hidden\n */\nexport function createClientLogger(namespace: string): AzureLogger {\n const clientRootLogger: AzureClientLogger = AzureLogger.extend(namespace);\n patchLogMethod(AzureLogger, clientRootLogger);\n return {\n error: createLogger(clientRootLogger, \"error\"),\n warning: createLogger(clientRootLogger, \"warning\"),\n info: createLogger(clientRootLogger, \"info\"),\n verbose: createLogger(clientRootLogger, \"verbose\"),\n };\n}\n\nfunction patchLogMethod(parent: AzureClientLogger, child: AzureClientLogger | AzureDebugger): void {\n child.log = (...args) => {\n parent.log(...args);\n };\n}\n\nfunction createLogger(parent: AzureClientLogger, level: AzureLogLevel): AzureDebugger {\n const logger: AzureDebugger = Object.assign(parent.extend(level), {\n level,\n });\n\n patchLogMethod(parent, logger);\n\n if (shouldEnable(logger)) {\n const enabledNamespaces = debug.disable();\n debug.enable(enabledNamespaces + \",\" + logger.namespace);\n }\n\n registeredLoggers.add(logger);\n\n return logger;\n}\n\nfunction shouldEnable(logger: AzureDebugger): boolean {\n return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);\n}\n\nfunction isAzureLogLevel(logLevel: string): logLevel is AzureLogLevel {\n return AZURE_LOG_LEVELS.includes(logLevel as any);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/log.browser.js b/node_modules/@azure/logger/dist-esm/src/log.browser.js new file mode 100644 index 0000000..3f69bb2 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/log.browser.js @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +export function log(...args) { + if (args.length > 0) { + const firstArg = String(args[0]); + if (firstArg.includes(":error")) { + console.error(...args); + } + else if (firstArg.includes(":warning")) { + console.warn(...args); + } + else if (firstArg.includes(":info")) { + console.info(...args); + } + else if (firstArg.includes(":verbose")) { + console.debug(...args); + } + else { + console.debug(...args); + } + } +} +//# sourceMappingURL=log.browser.js.map \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/log.browser.js.map b/node_modules/@azure/logger/dist-esm/src/log.browser.js.map new file mode 100644 index 0000000..4542a4e --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/log.browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"log.browser.js","sourceRoot":"","sources":["../../src/log.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,UAAU,GAAG,CAAC,GAAG,IAAW;IAChC,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;QACnB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACjC,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;YAC/B,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;SACxB;aAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;YACxC,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;SACvB;aAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YACrC,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;SACvB;aAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;SACxB;aAAM;YACL,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;SACxB;KACF;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport function log(...args: any[]): void {\n if (args.length > 0) {\n const firstArg = String(args[0]);\n if (firstArg.includes(\":error\")) {\n console.error(...args);\n } else if (firstArg.includes(\":warning\")) {\n console.warn(...args);\n } else if (firstArg.includes(\":info\")) {\n console.info(...args);\n } else if (firstArg.includes(\":verbose\")) {\n console.debug(...args);\n } else {\n console.debug(...args);\n }\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/log.js b/node_modules/@azure/logger/dist-esm/src/log.js new file mode 100644 index 0000000..74a1f11 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/log.js @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import { EOL } from "os"; +import util from "util"; +export function log(message, ...args) { + process.stderr.write(`${util.format(message, ...args)}${EOL}`); +} +//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/node_modules/@azure/logger/dist-esm/src/log.js.map b/node_modules/@azure/logger/dist-esm/src/log.js.map new file mode 100644 index 0000000..9581d18 --- /dev/null +++ b/node_modules/@azure/logger/dist-esm/src/log.js.map @@ -0,0 +1 @@ +{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,GAAG,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,MAAM,UAAU,GAAG,CAAC,OAAgB,EAAE,GAAG,IAAW;IAClD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC;AACjE,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { EOL } from \"os\";\nimport util from \"util\";\n\nexport function log(message: unknown, ...args: any[]): void {\n process.stderr.write(`${util.format(message, ...args)}${EOL}`);\n}\n"]} \ No newline at end of file diff --git a/node_modules/@azure/logger/package.json b/node_modules/@azure/logger/package.json new file mode 100644 index 0000000..ddb4e17 --- /dev/null +++ b/node_modules/@azure/logger/package.json @@ -0,0 +1,105 @@ +{ + "name": "@azure/logger", + "sdk-type": "client", + "version": "1.0.4", + "description": "Microsoft Azure SDK for JavaScript - Logger", + "main": "./dist/index.js", + "module": "dist-esm/src/index.js", + "browser": { + "./dist-esm/src/log.js": "./dist-esm/src/log.browser.js", + "process": false + }, + "react-native": { + "./dist/index.js": "./dist-esm/src/index.js" + }, + "engines": { + "node": ">=14.0.0" + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:samples": "echo Obsolete", + "build:test": "tsc -p . && dev-tool run bundle", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local --local", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "pretest": "npm run build:test", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run clean && tsc -p . && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && tsc -p . && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "unit-test:browser": "karma start --single-run", + "unit-test:node": "mocha -r esm -r ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 1200000 --full-trace --exclude \"test/**/browser/*.spec.ts\" \"test/**/*.spec.ts\"", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "types": "./types/logger.d.ts", + "files": [ + "dist/", + "dist-esm/src/", + "types/logger.d.ts", + "README.md", + "LICENSE" + ], + "repository": "github:Azure/azure-sdk-for-js", + "keywords": [ + "azure", + "log", + "logger", + "logging", + "node.js", + "typescript", + "javascript", + "browser", + "cloud" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger/README.md", + "sideEffects": false, + "dependencies": { + "tslib": "^2.2.0" + }, + "devDependencies": { + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@microsoft/api-extractor": "^7.31.1", + "@types/chai": "^4.1.6", + "@types/mocha": "^7.0.2", + "@types/node": "^14.0.0", + "@types/sinon": "^9.0.4", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "dotenv": "^16.0.0", + "eslint": "^8.0.0", + "karma": "^6.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-edge-launcher": "^0.4.2", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.3.8", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "nyc": "^15.0.0", + "prettier": "^2.5.1", + "puppeteer": "^19.2.2", + "rimraf": "^3.0.0", + "sinon": "^9.0.2", + "ts-node": "^10.0.0", + "typescript": "~4.8.0" + } +} diff --git a/node_modules/@azure/logger/types/logger.d.ts b/node_modules/@azure/logger/types/logger.d.ts new file mode 100644 index 0000000..68f3e8f --- /dev/null +++ b/node_modules/@azure/logger/types/logger.d.ts @@ -0,0 +1,104 @@ +/** + * An AzureClientLogger is a function that can log to an appropriate severity level. + */ +export declare type AzureClientLogger = Debugger; + +/** + * The AzureLogger provides a mechanism for overriding where logs are output to. + * By default, logs are sent to stderr. + * Override the `log` method to redirect logs to another location. + */ +export declare const AzureLogger: AzureClientLogger; + +/** + * Defines the methods available on the SDK-facing logger. + */ +export declare interface AzureLogger { + /** + * Used for failures the program is unlikely to recover from, + * such as Out of Memory. + */ + error: Debugger; + /** + * Used when a function fails to perform its intended task. + * Usually this means the function will throw an exception. + * Not used for self-healing events (e.g. automatic retry) + */ + warning: Debugger; + /** + * Used when a function operates normally. + */ + info: Debugger; + /** + * Used for detailed troubleshooting scenarios. This is + * intended for use by developers / system administrators + * for diagnosing specific failures. + */ + verbose: Debugger; +} + +/** + * The log levels supported by the logger. + * The log levels in order of most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +export declare type AzureLogLevel = "verbose" | "info" | "warning" | "error"; + +/** + * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. + * @param namespace - The name of the SDK package. + * @hidden + */ +export declare function createClientLogger(namespace: string): AzureLogger; + +/** + * A log function that can be dynamically enabled and redirected. + */ +export declare interface Debugger { + /** + * Logs the given arguments to the `log` method. + */ + (...args: any[]): void; + /** + * True if this logger is active and logging. + */ + enabled: boolean; + /** + * Used to cleanup/remove this logger. + */ + destroy: () => boolean; + /** + * The current log method. Can be overridden to redirect output. + */ + log: (...args: any[]) => void; + /** + * The namespace of this logger. + */ + namespace: string; + /** + * Extends this logger with a child namespace. + * Namespaces are separated with a ':' character. + */ + extend: (namespace: string) => Debugger; +} + +/** + * Retrieves the currently specified log level. + */ +export declare function getLogLevel(): AzureLogLevel | undefined; + +/** + * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. + * @param level - The log level to enable for logging. + * Options from most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +export declare function setLogLevel(level?: AzureLogLevel): void; + +export { } diff --git a/node_modules/@babel/runtime/LICENSE b/node_modules/@babel/runtime/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/runtime/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other 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. diff --git a/node_modules/@babel/runtime/README.md b/node_modules/@babel/runtime/README.md new file mode 100644 index 0000000..be27e83 --- /dev/null +++ b/node_modules/@babel/runtime/README.md @@ -0,0 +1,19 @@ +# @babel/runtime + +> babel's modular runtime helpers + +See our website [@babel/runtime](https://babeljs.io/docs/en/babel-runtime) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/runtime +``` + +or using yarn: + +```sh +yarn add @babel/runtime +``` diff --git a/node_modules/@babel/runtime/helpers/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/AsyncGenerator.js new file mode 100644 index 0000000..c3379a9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AsyncGenerator.js @@ -0,0 +1,64 @@ +var OverloadYield = require("./OverloadYield.js"); +function AsyncGenerator(gen) { + var front, back; + function resume(key, arg) { + try { + var result = gen[key](arg), + value = result.value, + overloaded = value instanceof OverloadYield; + Promise.resolve(overloaded ? value.v : value).then(function (arg) { + if (overloaded) { + var nextKey = "return" === key ? "return" : "next"; + if (!value.k || arg.done) return resume(nextKey, arg); + arg = gen[nextKey](arg).value; + } + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: !0 + }); + break; + case "throw": + front.reject(value); + break; + default: + front.resolve({ + value: value, + done: !1 + }); + } + (front = front.next) ? resume(front.key, front.arg) : back = null; + } + this._invoke = function (key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + back ? back = back.next = request : (front = back = request, resume(key, arg)); + }); + }, "function" != typeof gen["return"] && (this["return"] = void 0); +} +AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}, AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}, AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}, AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; +module.exports = AsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/AwaitValue.js b/node_modules/@babel/runtime/helpers/AwaitValue.js new file mode 100644 index 0000000..7681c2d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AwaitValue.js @@ -0,0 +1,4 @@ +function _AwaitValue(value) { + this.wrapped = value; +} +module.exports = _AwaitValue, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/OverloadYield.js b/node_modules/@babel/runtime/helpers/OverloadYield.js new file mode 100644 index 0000000..b133113 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/OverloadYield.js @@ -0,0 +1,4 @@ +function _OverloadYield(value, kind) { + this.v = value, this.k = kind; +} +module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js new file mode 100644 index 0000000..98810d6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js @@ -0,0 +1,24 @@ +function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + return desc; +} +module.exports = _applyDecoratedDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecs.js b/node_modules/@babel/runtime/helpers/applyDecs.js new file mode 100644 index 0000000..68a08c2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecs.js @@ -0,0 +1,236 @@ +var _typeof = require("./typeof.js")["default"]; +function old_createMetadataMethodsForProperty(metadataMap, kind, property, decoratorFinishedRef) { + return { + getMetadata: function getMetadata(key) { + old_assertNotFinished(decoratorFinishedRef, "getMetadata"), old_assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 !== metadataForKey) if (1 === kind) { + var pub = metadataForKey["public"]; + if (void 0 !== pub) return pub[property]; + } else if (2 === kind) { + var priv = metadataForKey["private"]; + if (void 0 !== priv) return priv.get(property); + } else if (Object.hasOwnProperty.call(metadataForKey, "constructor")) return metadataForKey.constructor; + }, + setMetadata: function setMetadata(key, value) { + old_assertNotFinished(decoratorFinishedRef, "setMetadata"), old_assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 === metadataForKey && (metadataForKey = metadataMap[key] = {}), 1 === kind) { + var pub = metadataForKey["public"]; + void 0 === pub && (pub = metadataForKey["public"] = {}), pub[property] = value; + } else if (2 === kind) { + var priv = metadataForKey.priv; + void 0 === priv && (priv = metadataForKey["private"] = new Map()), priv.set(property, value); + } else metadataForKey.constructor = value; + } + }; +} +function old_convertMetadataMapToFinal(obj, metadataMap) { + var parentMetadataMap = obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")], + metadataKeys = Object.getOwnPropertySymbols(metadataMap); + if (0 !== metadataKeys.length) { + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i], + metaForKey = metadataMap[key], + parentMetaForKey = parentMetadataMap ? parentMetadataMap[key] : null, + pub = metaForKey["public"], + parentPub = parentMetaForKey ? parentMetaForKey["public"] : null; + pub && parentPub && Object.setPrototypeOf(pub, parentPub); + var priv = metaForKey["private"]; + if (priv) { + var privArr = Array.from(priv.values()), + parentPriv = parentMetaForKey ? parentMetaForKey["private"] : null; + parentPriv && (privArr = privArr.concat(parentPriv)), metaForKey["private"] = privArr; + } + parentMetaForKey && Object.setPrototypeOf(metaForKey, parentMetaForKey); + } + parentMetadataMap && Object.setPrototypeOf(metadataMap, parentMetadataMap), obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")] = metadataMap; + } +} +function old_createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + old_assertNotFinished(decoratorFinishedRef, "addInitializer"), old_assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} +function old_memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var metadataKind, + metadataName, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + isStatic: isStatic, + isPrivate: isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + if (0 !== kind && (ctx.addInitializer = old_createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate) { + metadataKind = 2, metadataName = Symbol(name); + var access = {}; + 0 === kind ? (access.get = desc.get, access.set = desc.set) : 2 === kind ? access.get = function () { + return desc.value; + } : (1 !== kind && 3 !== kind || (access.get = function () { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (access.set = function (v) { + desc.set.call(this, v); + })), ctx.access = access; + } else metadataKind = 1, metadataName = name; + try { + return dec(value, Object.assign(ctx, old_createMetadataMethodsForProperty(metadataMap, metadataKind, metadataName, decoratorFinishedRef))); + } finally { + decoratorFinishedRef.v = !0; + } +} +function old_assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} +function old_assertMetadataKey(key) { + if ("symbol" != _typeof(key)) throw new TypeError("Metadata keys must be symbols, received: " + key); +} +function old_assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} +function old_assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && old_assertCallable(value.get, "accessor.get"), void 0 !== value.set && old_assertCallable(value.set, "accessor.set"), void 0 !== value.init && old_assertCallable(value.init, "accessor.init"), void 0 !== value.initializer && old_assertCallable(value.initializer, "accessor.initializer"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} +function old_getInit(desc) { + var initializer; + return null == (initializer = desc.init) && (initializer = desc.initializer) && "undefined" != typeof console && console.warn(".initializer has been renamed to .init as of March 2022"), initializer; +} +function old_applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers) { + var desc, + initializer, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = old_memberDec(decs, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value)) && (old_assertValidReturnValue(kind, newValue), 0 === kind ? initializer = newValue : 1 === kind ? (initializer = old_getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = old_memberDec(decs[i], name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value))) old_assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = old_getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === initializer ? initializer = newInit : "function" == typeof initializer ? initializer = [initializer, newInit] : initializer.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === initializer) initializer = function initializer(instance, init) { + return init; + };else if ("function" != typeof initializer) { + var ownInitializers = initializer; + initializer = function initializer(instance, init) { + for (var value = init, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = initializer; + initializer = function initializer(instance, init) { + return originalInitializer.call(instance, init); + }; + } + ret.push(initializer); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} +function old_applyMemberDecs(ret, Class, protoMetadataMap, staticMetadataMap, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + metadataMap, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, metadataMap = staticMetadataMap, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, metadataMap = protoMetadataMap, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + old_applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers); + } + } + old_pushInitializers(ret, protoInitializers), old_pushInitializers(ret, staticInitializers); +} +function old_pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); +} +function old_applyClassDecs(ret, targetClass, metadataMap, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var ctx = Object.assign({ + kind: "class", + name: name, + addInitializer: old_createAddInitializerMethod(initializers, decoratorFinishedRef) + }, old_createMetadataMethodsForProperty(metadataMap, 0, name, decoratorFinishedRef)), + nextNewClass = classDecs[i](newClass, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (old_assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }); + } +} +function applyDecs(targetClass, memberDecs, classDecs) { + var ret = [], + staticMetadataMap = {}, + protoMetadataMap = {}; + return old_applyMemberDecs(ret, targetClass, protoMetadataMap, staticMetadataMap, memberDecs), old_convertMetadataMapToFinal(targetClass.prototype, protoMetadataMap), old_applyClassDecs(ret, targetClass, staticMetadataMap, classDecs), old_convertMetadataMapToFinal(targetClass, staticMetadataMap), ret; +} +module.exports = applyDecs, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecs2203.js b/node_modules/@babel/runtime/helpers/applyDecs2203.js new file mode 100644 index 0000000..b15c001 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecs2203.js @@ -0,0 +1,187 @@ +var _typeof = require("./typeof.js")["default"]; +function applyDecs2203Factory() { + function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + !function (decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); + }(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; + } + function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + 0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), 0 === kind ? isPrivate ? (get = desc.get, set = desc.set) : (get = function get() { + return this[name]; + }, set = function set(v) { + this[name] = v; + }) : 2 === kind ? get = function get() { + return desc.value; + } : (1 !== kind && 3 !== kind || (get = function get() { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (set = function set(v) { + desc.set.call(this, v); + })), ctx.access = get && set ? { + get: get, + set: set + } : get ? { + get: get + } : { + set: set + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + } + function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); + } + function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } + } + function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); + } + function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); + } + return function (targetClass, memberDecs, classDecs) { + var ret = []; + return function (ret, Class, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, 0 != (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers); + } + } + pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers); + }(ret, targetClass, memberDecs), function (ret, targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }); + } + }(ret, targetClass, classDecs), ret; + }; +} +var applyDecs2203Impl; +function applyDecs2203(targetClass, memberDecs, classDecs) { + return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(targetClass, memberDecs, classDecs); +} +module.exports = applyDecs2203, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecs2203R.js b/node_modules/@babel/runtime/helpers/applyDecs2203R.js new file mode 100644 index 0000000..ef0ece5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecs2203R.js @@ -0,0 +1,191 @@ +var _typeof = require("./typeof.js")["default"]; +function applyDecs2203RFactory() { + function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + !function (decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); + }(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; + } + function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + 0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), 0 === kind ? isPrivate ? (get = desc.get, set = desc.set) : (get = function get() { + return this[name]; + }, set = function set(v) { + this[name] = v; + }) : 2 === kind ? get = function get() { + return desc.value; + } : (1 !== kind && 3 !== kind || (get = function get() { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (set = function set(v) { + desc.set.call(this, v); + })), ctx.access = get && set ? { + get: get, + set: set + } : get ? { + get: get + } : { + set: set + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + } + function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); + } + function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } + } + function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); + } + function applyMemberDecs(Class, decInfos) { + for (var protoInitializers, staticInitializers, ret = [], existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers); + } + } + return pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers), ret; + } + function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); + } + return function (targetClass, memberDecs, classDecs) { + return { + e: applyMemberDecs(targetClass, memberDecs), + get c() { + return function (targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + return [newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }]; + } + }(targetClass, classDecs); + } + }; + }; +} +function applyDecs2203R(targetClass, memberDecs, classDecs) { + return (module.exports = applyDecs2203R = applyDecs2203RFactory(), module.exports.__esModule = true, module.exports["default"] = module.exports)(targetClass, memberDecs, classDecs); +} +module.exports = applyDecs2203R, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecs2301.js b/node_modules/@babel/runtime/helpers/applyDecs2301.js new file mode 100644 index 0000000..0f700a6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecs2301.js @@ -0,0 +1,221 @@ +var _typeof = require("./typeof.js")["default"]; +var checkInRHS = require("./checkInRHS.js"); +function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + assertNotFinished(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} +function assertInstanceIfPrivate(has, target) { + if (!has(target)) throw new TypeError("Attempted to access private element on non-instance"); +} +function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + if (0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate || 0 !== kind && 2 !== kind) { + if (2 === kind) get = function get(target) { + return assertInstanceIfPrivate(hasPrivateBrand, target), desc.value; + };else { + var t = 0 === kind || 1 === kind; + (t || 3 === kind) && (get = isPrivate ? function (target) { + return assertInstanceIfPrivate(hasPrivateBrand, target), desc.get.call(target); + } : function (target) { + return desc.get.call(target); + }), (t || 4 === kind) && (set = isPrivate ? function (target, value) { + assertInstanceIfPrivate(hasPrivateBrand, target), desc.set.call(target, value); + } : function (target, value) { + desc.set.call(target, value); + }); + } + } else get = function get(target) { + return target[name]; + }, 0 === kind && (set = function set(target, v) { + target[name] = v; + }); + var has = isPrivate ? hasPrivateBrand.bind() : function (target) { + return name in target; + }; + ctx.access = get && set ? { + get: get, + set: set, + has: has + } : get ? { + get: get, + has: has + } : { + set: set, + has: has + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } +} +function assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} +function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} +function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} +function curryThis1(fn) { + return function () { + return fn(this); + }; +} +function curryThis2(fn) { + return function (value) { + fn(this, value); + }; +} +function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: curryThis1(decInfo[3]), + set: curryThis2(decInfo[4]) + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} +function applyMemberDecs(Class, decInfos, instanceBrand) { + for (var protoInitializers, staticInitializers, staticBrand, ret = [], existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5, + hasPrivateBrand = instanceBrand; + if (isStatic ? (base = Class, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || []), isPrivate && !staticBrand && (staticBrand = function staticBrand(_) { + return checkInRHS(_) === Class; + }), hasPrivateBrand = staticBrand) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand); + } + } + return pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers), ret; +} +function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); +} +function applyClassDecs(targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + return [newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }]; + } +} +function applyDecs2301(targetClass, memberDecs, classDecs, instanceBrand) { + return { + e: applyMemberDecs(targetClass, memberDecs, instanceBrand), + get c() { + return applyClassDecs(targetClass, classDecs); + } + }; +} +module.exports = applyDecs2301, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js new file mode 100644 index 0000000..3686540 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js @@ -0,0 +1,6 @@ +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} +module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/arrayWithHoles.js new file mode 100644 index 0000000..ad0cc6b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithHoles.js @@ -0,0 +1,4 @@ +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} +module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js new file mode 100644 index 0000000..6d4b76d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js @@ -0,0 +1,5 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} +module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/assertThisInitialized.js new file mode 100644 index 0000000..71487e5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/assertThisInitialized.js @@ -0,0 +1,7 @@ +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self; +} +module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js new file mode 100644 index 0000000..c272bcd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js @@ -0,0 +1,24 @@ +var OverloadYield = require("./OverloadYield.js"); +function _asyncGeneratorDelegate(inner) { + var iter = {}, + waiting = !1; + function pump(key, value) { + return waiting = !0, value = new Promise(function (resolve) { + resolve(inner[key](value)); + }), { + done: !1, + value: new OverloadYield(value, 1) + }; + } + return iter["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { + return this; + }, iter.next = function (value) { + return waiting ? (waiting = !1, value) : pump("next", value); + }, "function" == typeof inner["throw"] && (iter["throw"] = function (value) { + if (waiting) throw waiting = !1, value; + return pump("throw", value); + }), "function" == typeof inner["return"] && (iter["return"] = function (value) { + return waiting ? (waiting = !1, value) : pump("return", value); + }), iter; +} +module.exports = _asyncGeneratorDelegate, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncIterator.js b/node_modules/@babel/runtime/helpers/asyncIterator.js new file mode 100644 index 0000000..420ef08 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncIterator.js @@ -0,0 +1,45 @@ +function _asyncIterator(iterable) { + var method, + async, + sync, + retry = 2; + for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { + if (async && null != (method = iterable[async])) return method.call(iterable); + if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); + async = "@@asyncIterator", sync = "@@iterator"; + } + throw new TypeError("Object is not async iterable"); +} +function AsyncFromSyncIterator(s) { + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); + var done = r.done; + return Promise.resolve(r.value).then(function (value) { + return { + value: value, + done: done + }; + }); + } + return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { + this.s = s, this.n = s.next; + }, AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function next() { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + "return": function _return(value) { + var ret = this.s["return"]; + return void 0 === ret ? Promise.resolve({ + value: value, + done: !0 + }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); + }, + "throw": function _throw(value) { + var thr = this.s["return"]; + return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); + } + }, new AsyncFromSyncIterator(s); +} +module.exports = _asyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/asyncToGenerator.js new file mode 100644 index 0000000..6b9697a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncToGenerator.js @@ -0,0 +1,31 @@ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(undefined); + }); + }; +} +module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js new file mode 100644 index 0000000..7d4e951 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js @@ -0,0 +1,5 @@ +var OverloadYield = require("./OverloadYield.js"); +function _awaitAsyncGenerator(value) { + return new OverloadYield(value, 0); +} +module.exports = _awaitAsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/checkInRHS.js b/node_modules/@babel/runtime/helpers/checkInRHS.js new file mode 100644 index 0000000..e6ba638 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/checkInRHS.js @@ -0,0 +1,6 @@ +var _typeof = require("./typeof.js")["default"]; +function _checkInRHS(value) { + if (Object(value) !== value) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== value ? _typeof(value) : "null")); + return value; +} +module.exports = _checkInRHS, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js b/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js new file mode 100644 index 0000000..1bbfd34 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/checkPrivateRedeclaration.js @@ -0,0 +1,6 @@ +function _checkPrivateRedeclaration(obj, privateCollection) { + if (privateCollection.has(obj)) { + throw new TypeError("Cannot initialize the same private elements twice on an object"); + } +} +module.exports = _checkPrivateRedeclaration, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..3ebfed8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js @@ -0,0 +1,18 @@ +function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + }; + } + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + return descriptor; + } +} +module.exports = _classApplyDescriptorDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js new file mode 100644 index 0000000..af3555d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js @@ -0,0 +1,7 @@ +function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + return descriptor.value; +} +module.exports = _classApplyDescriptorGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js new file mode 100644 index 0000000..71bbf1d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js @@ -0,0 +1,11 @@ +function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + descriptor.value = value; + } +} +module.exports = _classApplyDescriptorSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCallCheck.js b/node_modules/@babel/runtime/helpers/classCallCheck.js new file mode 100644 index 0000000..eab7e52 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCallCheck.js @@ -0,0 +1,6 @@ +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} +module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..3487684 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js @@ -0,0 +1,6 @@ +function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} +module.exports = _classCheckPrivateStaticAccess, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..b937d15 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,6 @@ +function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} +module.exports = _classCheckPrivateStaticFieldDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js new file mode 100644 index 0000000..e6f4725 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js @@ -0,0 +1,7 @@ +function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + return privateMap.get(receiver); +} +module.exports = _classExtractFieldDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classNameTDZError.js b/node_modules/@babel/runtime/helpers/classNameTDZError.js new file mode 100644 index 0000000..9f84697 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classNameTDZError.js @@ -0,0 +1,4 @@ +function _classNameTDZError(name) { + throw new ReferenceError("Class \"" + name + "\" cannot be referenced in computed property keys."); +} +module.exports = _classNameTDZError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..07f777d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js @@ -0,0 +1,7 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); +function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} +module.exports = _classPrivateFieldDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js new file mode 100644 index 0000000..a67951e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js @@ -0,0 +1,7 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); +function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} +module.exports = _classPrivateFieldGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js b/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js new file mode 100644 index 0000000..e55873a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldInitSpec.js @@ -0,0 +1,6 @@ +var checkPrivateRedeclaration = require("./checkPrivateRedeclaration.js"); +function _classPrivateFieldInitSpec(obj, privateMap, value) { + checkPrivateRedeclaration(obj, privateMap); + privateMap.set(obj, value); +} +module.exports = _classPrivateFieldInitSpec, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..bb16c0b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js @@ -0,0 +1,7 @@ +function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + return receiver; +} +module.exports = _classPrivateFieldBase, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..b3d546f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js @@ -0,0 +1,5 @@ +var id = 0; +function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} +module.exports = _classPrivateFieldKey, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js new file mode 100644 index 0000000..ffb73a1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js @@ -0,0 +1,8 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); +function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} +module.exports = _classPrivateFieldSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js new file mode 100644 index 0000000..6a8436d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js @@ -0,0 +1,7 @@ +function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return fn; +} +module.exports = _classPrivateMethodGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js b/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js new file mode 100644 index 0000000..3106476 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodInitSpec.js @@ -0,0 +1,6 @@ +var checkPrivateRedeclaration = require("./checkPrivateRedeclaration.js"); +function _classPrivateMethodInitSpec(obj, privateSet) { + checkPrivateRedeclaration(obj, privateSet); + privateSet.add(obj); +} +module.exports = _classPrivateMethodInitSpec, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js new file mode 100644 index 0000000..a44fd78 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js @@ -0,0 +1,4 @@ +function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} +module.exports = _classPrivateMethodSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..734aaaf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,9 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); +function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} +module.exports = _classStaticPrivateFieldDestructureSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..e8e295f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,9 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); +function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} +module.exports = _classStaticPrivateFieldSpecGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..b02e4c0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,10 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); +function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} +module.exports = _classStaticPrivateFieldSpecSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..d3bb996 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js @@ -0,0 +1,6 @@ +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); +function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} +module.exports = _classStaticPrivateMethodGet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..72560e6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js @@ -0,0 +1,4 @@ +function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} +module.exports = _classStaticPrivateMethodSet, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/construct.js b/node_modules/@babel/runtime/helpers/construct.js new file mode 100644 index 0000000..3d3c232 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/construct.js @@ -0,0 +1,18 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + } + return _construct.apply(null, arguments); +} +module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createClass.js b/node_modules/@babel/runtime/helpers/createClass.js new file mode 100644 index 0000000..201dcdf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createClass.js @@ -0,0 +1,19 @@ +var toPropertyKey = require("./toPropertyKey.js"); +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); + } +} +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} +module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js new file mode 100644 index 0000000..19b6f14 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js @@ -0,0 +1,53 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + var F = function F() {}; + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} +module.exports = _createForOfIteratorHelper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..b8eb550 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js @@ -0,0 +1,20 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createSuper.js b/node_modules/@babel/runtime/helpers/createSuper.js new file mode 100644 index 0000000..bd72679 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createSuper.js @@ -0,0 +1,18 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); +var possibleConstructorReturn = require("./possibleConstructorReturn.js"); +function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return possibleConstructorReturn(this, result); + }; +} +module.exports = _createSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/decorate.js b/node_modules/@babel/runtime/helpers/decorate.js new file mode 100644 index 0000000..457741f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/decorate.js @@ -0,0 +1,343 @@ +var toArray = require("./toArray.js"); +var toPropertyKey = require("./toPropertyKey.js"); +function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + var newExtras = elementFinisherExtras.extras; + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + extras.push.apply(extras, newExtras); + } + } + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + var finisher = _optionalCallableProperty(elementObject, "finisher"); + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + var finisher = _optionalCallableProperty(obj, "finisher"); + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + constructor = newConstructor; + } + } + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} +function _coalesceClassElements(elements) { + var newElements = []; + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + other.decorators = element.decorators; + } + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + return newElements; +} +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + return value; +} +module.exports = _decorate, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defaults.js b/node_modules/@babel/runtime/helpers/defaults.js new file mode 100644 index 0000000..86641e9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defaults.js @@ -0,0 +1,12 @@ +function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + return obj; +} +module.exports = _defaults, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineAccessor.js b/node_modules/@babel/runtime/helpers/defineAccessor.js new file mode 100644 index 0000000..c722427 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineAccessor.js @@ -0,0 +1,8 @@ +function _defineAccessor(type, obj, key, fn) { + var desc = { + configurable: !0, + enumerable: !0 + }; + return desc[type] = fn, Object.defineProperty(obj, key, desc); +} +module.exports = _defineAccessor, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js new file mode 100644 index 0000000..a04e602 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js @@ -0,0 +1,20 @@ +function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + return obj; +} +module.exports = _defineEnumerableProperties, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineProperty.js b/node_modules/@babel/runtime/helpers/defineProperty.js new file mode 100644 index 0000000..8762046 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineProperty.js @@ -0,0 +1,16 @@ +var toPropertyKey = require("./toPropertyKey.js"); +function _defineProperty(obj, key, value) { + key = toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} +module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js new file mode 100644 index 0000000..5df93d4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js @@ -0,0 +1,63 @@ +import OverloadYield from "./OverloadYield.js"; +export default function AsyncGenerator(gen) { + var front, back; + function resume(key, arg) { + try { + var result = gen[key](arg), + value = result.value, + overloaded = value instanceof OverloadYield; + Promise.resolve(overloaded ? value.v : value).then(function (arg) { + if (overloaded) { + var nextKey = "return" === key ? "return" : "next"; + if (!value.k || arg.done) return resume(nextKey, arg); + arg = gen[nextKey](arg).value; + } + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: !0 + }); + break; + case "throw": + front.reject(value); + break; + default: + front.resolve({ + value: value, + done: !1 + }); + } + (front = front.next) ? resume(front.key, front.arg) : back = null; + } + this._invoke = function (key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + back ? back = back.next = request : (front = back = request, resume(key, arg)); + }); + }, "function" != typeof gen["return"] && (this["return"] = void 0); +} +AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}, AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}, AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}, AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AwaitValue.js b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js new file mode 100644 index 0000000..5237e18 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js @@ -0,0 +1,3 @@ +export default function _AwaitValue(value) { + this.wrapped = value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/OverloadYield.js b/node_modules/@babel/runtime/helpers/esm/OverloadYield.js new file mode 100644 index 0000000..0dd12e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/OverloadYield.js @@ -0,0 +1,3 @@ +export default function _OverloadYield(value, kind) { + this.v = value, this.k = kind; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js new file mode 100644 index 0000000..5137e85 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js @@ -0,0 +1,23 @@ +export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + return desc; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecs.js b/node_modules/@babel/runtime/helpers/esm/applyDecs.js new file mode 100644 index 0000000..84988df --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecs.js @@ -0,0 +1,235 @@ +import _typeof from "./typeof.js"; +function old_createMetadataMethodsForProperty(metadataMap, kind, property, decoratorFinishedRef) { + return { + getMetadata: function getMetadata(key) { + old_assertNotFinished(decoratorFinishedRef, "getMetadata"), old_assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 !== metadataForKey) if (1 === kind) { + var pub = metadataForKey["public"]; + if (void 0 !== pub) return pub[property]; + } else if (2 === kind) { + var priv = metadataForKey["private"]; + if (void 0 !== priv) return priv.get(property); + } else if (Object.hasOwnProperty.call(metadataForKey, "constructor")) return metadataForKey.constructor; + }, + setMetadata: function setMetadata(key, value) { + old_assertNotFinished(decoratorFinishedRef, "setMetadata"), old_assertMetadataKey(key); + var metadataForKey = metadataMap[key]; + if (void 0 === metadataForKey && (metadataForKey = metadataMap[key] = {}), 1 === kind) { + var pub = metadataForKey["public"]; + void 0 === pub && (pub = metadataForKey["public"] = {}), pub[property] = value; + } else if (2 === kind) { + var priv = metadataForKey.priv; + void 0 === priv && (priv = metadataForKey["private"] = new Map()), priv.set(property, value); + } else metadataForKey.constructor = value; + } + }; +} +function old_convertMetadataMapToFinal(obj, metadataMap) { + var parentMetadataMap = obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")], + metadataKeys = Object.getOwnPropertySymbols(metadataMap); + if (0 !== metadataKeys.length) { + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i], + metaForKey = metadataMap[key], + parentMetaForKey = parentMetadataMap ? parentMetadataMap[key] : null, + pub = metaForKey["public"], + parentPub = parentMetaForKey ? parentMetaForKey["public"] : null; + pub && parentPub && Object.setPrototypeOf(pub, parentPub); + var priv = metaForKey["private"]; + if (priv) { + var privArr = Array.from(priv.values()), + parentPriv = parentMetaForKey ? parentMetaForKey["private"] : null; + parentPriv && (privArr = privArr.concat(parentPriv)), metaForKey["private"] = privArr; + } + parentMetaForKey && Object.setPrototypeOf(metaForKey, parentMetaForKey); + } + parentMetadataMap && Object.setPrototypeOf(metadataMap, parentMetadataMap), obj[Symbol.metadata || Symbol["for"]("Symbol.metadata")] = metadataMap; + } +} +function old_createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + old_assertNotFinished(decoratorFinishedRef, "addInitializer"), old_assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} +function old_memberDec(dec, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var metadataKind, + metadataName, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + isStatic: isStatic, + isPrivate: isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + if (0 !== kind && (ctx.addInitializer = old_createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate) { + metadataKind = 2, metadataName = Symbol(name); + var access = {}; + 0 === kind ? (access.get = desc.get, access.set = desc.set) : 2 === kind ? access.get = function () { + return desc.value; + } : (1 !== kind && 3 !== kind || (access.get = function () { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (access.set = function (v) { + desc.set.call(this, v); + })), ctx.access = access; + } else metadataKind = 1, metadataName = name; + try { + return dec(value, Object.assign(ctx, old_createMetadataMethodsForProperty(metadataMap, metadataKind, metadataName, decoratorFinishedRef))); + } finally { + decoratorFinishedRef.v = !0; + } +} +function old_assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} +function old_assertMetadataKey(key) { + if ("symbol" != _typeof(key)) throw new TypeError("Metadata keys must be symbols, received: " + key); +} +function old_assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} +function old_assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && old_assertCallable(value.get, "accessor.get"), void 0 !== value.set && old_assertCallable(value.set, "accessor.set"), void 0 !== value.init && old_assertCallable(value.init, "accessor.init"), void 0 !== value.initializer && old_assertCallable(value.initializer, "accessor.initializer"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} +function old_getInit(desc) { + var initializer; + return null == (initializer = desc.init) && (initializer = desc.initializer) && "undefined" != typeof console && console.warn(".initializer has been renamed to .init as of March 2022"), initializer; +} +function old_applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers) { + var desc, + initializer, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = old_memberDec(decs, name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value)) && (old_assertValidReturnValue(kind, newValue), 0 === kind ? initializer = newValue : 1 === kind ? (initializer = old_getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = old_memberDec(decs[i], name, desc, metadataMap, initializers, kind, isStatic, isPrivate, value))) old_assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = old_getInit(newValue), get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === initializer ? initializer = newInit : "function" == typeof initializer ? initializer = [initializer, newInit] : initializer.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === initializer) initializer = function initializer(instance, init) { + return init; + };else if ("function" != typeof initializer) { + var ownInitializers = initializer; + initializer = function initializer(instance, init) { + for (var value = init, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = initializer; + initializer = function initializer(instance, init) { + return originalInitializer.call(instance, init); + }; + } + ret.push(initializer); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} +function old_applyMemberDecs(ret, Class, protoMetadataMap, staticMetadataMap, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + metadataMap, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, metadataMap = staticMetadataMap, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, metadataMap = protoMetadataMap, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + old_applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, metadataMap, initializers); + } + } + old_pushInitializers(ret, protoInitializers), old_pushInitializers(ret, staticInitializers); +} +function old_pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); +} +function old_applyClassDecs(ret, targetClass, metadataMap, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var ctx = Object.assign({ + kind: "class", + name: name, + addInitializer: old_createAddInitializerMethod(initializers, decoratorFinishedRef) + }, old_createMetadataMethodsForProperty(metadataMap, 0, name, decoratorFinishedRef)), + nextNewClass = classDecs[i](newClass, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (old_assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }); + } +} +export default function applyDecs(targetClass, memberDecs, classDecs) { + var ret = [], + staticMetadataMap = {}, + protoMetadataMap = {}; + return old_applyMemberDecs(ret, targetClass, protoMetadataMap, staticMetadataMap, memberDecs), old_convertMetadataMapToFinal(targetClass.prototype, protoMetadataMap), old_applyClassDecs(ret, targetClass, staticMetadataMap, classDecs), old_convertMetadataMapToFinal(targetClass, staticMetadataMap), ret; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecs2203.js b/node_modules/@babel/runtime/helpers/esm/applyDecs2203.js new file mode 100644 index 0000000..3f2f8b8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecs2203.js @@ -0,0 +1,186 @@ +import _typeof from "./typeof.js"; +function applyDecs2203Factory() { + function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + !function (decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); + }(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; + } + function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + 0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), 0 === kind ? isPrivate ? (get = desc.get, set = desc.set) : (get = function get() { + return this[name]; + }, set = function set(v) { + this[name] = v; + }) : 2 === kind ? get = function get() { + return desc.value; + } : (1 !== kind && 3 !== kind || (get = function get() { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (set = function set(v) { + desc.set.call(this, v); + })), ctx.access = get && set ? { + get: get, + set: set + } : get ? { + get: get + } : { + set: set + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + } + function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); + } + function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } + } + function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); + } + function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); + } + return function (targetClass, memberDecs, classDecs) { + var ret = []; + return function (ret, Class, decInfos) { + for (var protoInitializers, staticInitializers, existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, 0 != (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers); + } + } + pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers); + }(ret, targetClass, memberDecs), function (ret, targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + ret.push(newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }); + } + }(ret, targetClass, classDecs), ret; + }; +} +var applyDecs2203Impl; +export default function applyDecs2203(targetClass, memberDecs, classDecs) { + return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(targetClass, memberDecs, classDecs); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecs2203R.js b/node_modules/@babel/runtime/helpers/esm/applyDecs2203R.js new file mode 100644 index 0000000..ed1bc20 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecs2203R.js @@ -0,0 +1,190 @@ +import _typeof from "./typeof.js"; +function applyDecs2203RFactory() { + function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + !function (decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); + }(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; + } + function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + 0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), 0 === kind ? isPrivate ? (get = desc.get, set = desc.set) : (get = function get() { + return this[name]; + }, set = function set(v) { + this[name] = v; + }) : 2 === kind ? get = function get() { + return desc.value; + } : (1 !== kind && 3 !== kind || (get = function get() { + return desc.get.call(this); + }), 1 !== kind && 4 !== kind || (set = function set(v) { + desc.set.call(this, v); + })), ctx.access = get && set ? { + get: get, + set: set + } : get ? { + get: get + } : { + set: set + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } + } + function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); + } + function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } + } + function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: decInfo[3], + set: decInfo[4] + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); + } + function applyMemberDecs(Class, decInfos) { + for (var protoInitializers, staticInitializers, ret = [], existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5; + if (isStatic ? (base = Class, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || [])) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers); + } + } + return pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers), ret; + } + function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); + } + return function (targetClass, memberDecs, classDecs) { + return { + e: applyMemberDecs(targetClass, memberDecs), + get c() { + return function (targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + return [newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }]; + } + }(targetClass, classDecs); + } + }; + }; +} +export default function applyDecs2203R(targetClass, memberDecs, classDecs) { + return (applyDecs2203R = applyDecs2203RFactory())(targetClass, memberDecs, classDecs); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecs2301.js b/node_modules/@babel/runtime/helpers/esm/applyDecs2301.js new file mode 100644 index 0000000..ae87485 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecs2301.js @@ -0,0 +1,220 @@ +import _typeof from "./typeof.js"; +import checkInRHS from "./checkInRHS.js"; +function createAddInitializerMethod(initializers, decoratorFinishedRef) { + return function (initializer) { + assertNotFinished(decoratorFinishedRef, "addInitializer"), assertCallable(initializer, "An initializer"), initializers.push(initializer); + }; +} +function assertInstanceIfPrivate(has, target) { + if (!has(target)) throw new TypeError("Attempted to access private element on non-instance"); +} +function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand) { + var kindStr; + switch (kind) { + case 1: + kindStr = "accessor"; + break; + case 2: + kindStr = "method"; + break; + case 3: + kindStr = "getter"; + break; + case 4: + kindStr = "setter"; + break; + default: + kindStr = "field"; + } + var get, + set, + ctx = { + kind: kindStr, + name: isPrivate ? "#" + name : name, + "static": isStatic, + "private": isPrivate + }, + decoratorFinishedRef = { + v: !1 + }; + if (0 !== kind && (ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef)), isPrivate || 0 !== kind && 2 !== kind) { + if (2 === kind) get = function get(target) { + return assertInstanceIfPrivate(hasPrivateBrand, target), desc.value; + };else { + var t = 0 === kind || 1 === kind; + (t || 3 === kind) && (get = isPrivate ? function (target) { + return assertInstanceIfPrivate(hasPrivateBrand, target), desc.get.call(target); + } : function (target) { + return desc.get.call(target); + }), (t || 4 === kind) && (set = isPrivate ? function (target, value) { + assertInstanceIfPrivate(hasPrivateBrand, target), desc.set.call(target, value); + } : function (target, value) { + desc.set.call(target, value); + }); + } + } else get = function get(target) { + return target[name]; + }, 0 === kind && (set = function set(target, v) { + target[name] = v; + }); + var has = isPrivate ? hasPrivateBrand.bind() : function (target) { + return name in target; + }; + ctx.access = get && set ? { + get: get, + set: set, + has: has + } : get ? { + get: get, + has: has + } : { + set: set, + has: has + }; + try { + return dec(value, ctx); + } finally { + decoratorFinishedRef.v = !0; + } +} +function assertNotFinished(decoratorFinishedRef, fnName) { + if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished"); +} +function assertCallable(fn, hint) { + if ("function" != typeof fn) throw new TypeError(hint + " must be a function"); +} +function assertValidReturnValue(kind, value) { + var type = _typeof(value); + if (1 === kind) { + if ("object" !== type || null === value) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); + void 0 !== value.get && assertCallable(value.get, "accessor.get"), void 0 !== value.set && assertCallable(value.set, "accessor.set"), void 0 !== value.init && assertCallable(value.init, "accessor.init"); + } else if ("function" !== type) { + var hint; + throw hint = 0 === kind ? "field" : 10 === kind ? "class" : "method", new TypeError(hint + " decorators must return a function or void 0"); + } +} +function curryThis1(fn) { + return function () { + return fn(this); + }; +} +function curryThis2(fn) { + return function (value) { + fn(this, value); + }; +} +function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand) { + var desc, + init, + value, + newValue, + get, + set, + decs = decInfo[0]; + if (isPrivate ? desc = 0 === kind || 1 === kind ? { + get: curryThis1(decInfo[3]), + set: curryThis2(decInfo[4]) + } : 3 === kind ? { + get: decInfo[3] + } : 4 === kind ? { + set: decInfo[3] + } : { + value: decInfo[3] + } : 0 !== kind && (desc = Object.getOwnPropertyDescriptor(base, name)), 1 === kind ? value = { + get: desc.get, + set: desc.set + } : 2 === kind ? value = desc.value : 3 === kind ? value = desc.get : 4 === kind && (value = desc.set), "function" == typeof decs) void 0 !== (newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand)) && (assertValidReturnValue(kind, newValue), 0 === kind ? init = newValue : 1 === kind ? (init = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue);else for (var i = decs.length - 1; i >= 0; i--) { + var newInit; + if (void 0 !== (newValue = memberDec(decs[i], name, desc, initializers, kind, isStatic, isPrivate, value, hasPrivateBrand))) assertValidReturnValue(kind, newValue), 0 === kind ? newInit = newValue : 1 === kind ? (newInit = newValue.init, get = newValue.get || value.get, set = newValue.set || value.set, value = { + get: get, + set: set + }) : value = newValue, void 0 !== newInit && (void 0 === init ? init = newInit : "function" == typeof init ? init = [init, newInit] : init.push(newInit)); + } + if (0 === kind || 1 === kind) { + if (void 0 === init) init = function init(instance, _init) { + return _init; + };else if ("function" != typeof init) { + var ownInitializers = init; + init = function init(instance, _init2) { + for (var value = _init2, i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value); + return value; + }; + } else { + var originalInitializer = init; + init = function init(instance, _init3) { + return originalInitializer.call(instance, _init3); + }; + } + ret.push(init); + } + 0 !== kind && (1 === kind ? (desc.get = value.get, desc.set = value.set) : 2 === kind ? desc.value = value : 3 === kind ? desc.get = value : 4 === kind && (desc.set = value), isPrivate ? 1 === kind ? (ret.push(function (instance, args) { + return value.get.call(instance, args); + }), ret.push(function (instance, args) { + return value.set.call(instance, args); + })) : 2 === kind ? ret.push(value) : ret.push(function (instance, args) { + return value.call(instance, args); + }) : Object.defineProperty(base, name, desc)); +} +function applyMemberDecs(Class, decInfos, instanceBrand) { + for (var protoInitializers, staticInitializers, staticBrand, ret = [], existingProtoNonFields = new Map(), existingStaticNonFields = new Map(), i = 0; i < decInfos.length; i++) { + var decInfo = decInfos[i]; + if (Array.isArray(decInfo)) { + var base, + initializers, + kind = decInfo[1], + name = decInfo[2], + isPrivate = decInfo.length > 3, + isStatic = kind >= 5, + hasPrivateBrand = instanceBrand; + if (isStatic ? (base = Class, 0 !== (kind -= 5) && (initializers = staticInitializers = staticInitializers || []), isPrivate && !staticBrand && (staticBrand = function staticBrand(_) { + return checkInRHS(_) === Class; + }), hasPrivateBrand = staticBrand) : (base = Class.prototype, 0 !== kind && (initializers = protoInitializers = protoInitializers || [])), 0 !== kind && !isPrivate) { + var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields, + existingKind = existingNonFields.get(name) || 0; + if (!0 === existingKind || 3 === existingKind && 4 !== kind || 4 === existingKind && 3 !== kind) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name); + !existingKind && kind > 2 ? existingNonFields.set(name, kind) : existingNonFields.set(name, !0); + } + applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, hasPrivateBrand); + } + } + return pushInitializers(ret, protoInitializers), pushInitializers(ret, staticInitializers), ret; +} +function pushInitializers(ret, initializers) { + initializers && ret.push(function (instance) { + for (var i = 0; i < initializers.length; i++) initializers[i].call(instance); + return instance; + }); +} +function applyClassDecs(targetClass, classDecs) { + if (classDecs.length > 0) { + for (var initializers = [], newClass = targetClass, name = targetClass.name, i = classDecs.length - 1; i >= 0; i--) { + var decoratorFinishedRef = { + v: !1 + }; + try { + var nextNewClass = classDecs[i](newClass, { + kind: "class", + name: name, + addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef) + }); + } finally { + decoratorFinishedRef.v = !0; + } + void 0 !== nextNewClass && (assertValidReturnValue(10, nextNewClass), newClass = nextNewClass); + } + return [newClass, function () { + for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass); + }]; + } +} +export default function applyDecs2301(targetClass, memberDecs, classDecs, instanceBrand) { + return { + e: applyMemberDecs(targetClass, memberDecs, instanceBrand), + get c() { + return applyClassDecs(targetClass, classDecs); + } + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js new file mode 100644 index 0000000..8a9fad8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js @@ -0,0 +1,5 @@ +export default function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js new file mode 100644 index 0000000..be734fc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js @@ -0,0 +1,3 @@ +export default function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js new file mode 100644 index 0000000..f7d8dc7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js @@ -0,0 +1,4 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js new file mode 100644 index 0000000..1f8fcf4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js @@ -0,0 +1,6 @@ +export default function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js new file mode 100644 index 0000000..d393d55 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js @@ -0,0 +1,23 @@ +import OverloadYield from "./OverloadYield.js"; +export default function _asyncGeneratorDelegate(inner) { + var iter = {}, + waiting = !1; + function pump(key, value) { + return waiting = !0, value = new Promise(function (resolve) { + resolve(inner[key](value)); + }), { + done: !1, + value: new OverloadYield(value, 1) + }; + } + return iter["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { + return this; + }, iter.next = function (value) { + return waiting ? (waiting = !1, value) : pump("next", value); + }, "function" == typeof inner["throw"] && (iter["throw"] = function (value) { + if (waiting) throw waiting = !1, value; + return pump("throw", value); + }), "function" == typeof inner["return"] && (iter["return"] = function (value) { + return waiting ? (waiting = !1, value) : pump("return", value); + }), iter; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncIterator.js b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js new file mode 100644 index 0000000..ae8aa39 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js @@ -0,0 +1,44 @@ +export default function _asyncIterator(iterable) { + var method, + async, + sync, + retry = 2; + for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { + if (async && null != (method = iterable[async])) return method.call(iterable); + if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); + async = "@@asyncIterator", sync = "@@iterator"; + } + throw new TypeError("Object is not async iterable"); +} +function AsyncFromSyncIterator(s) { + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); + var done = r.done; + return Promise.resolve(r.value).then(function (value) { + return { + value: value, + done: done + }; + }); + } + return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { + this.s = s, this.n = s.next; + }, AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function next() { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + "return": function _return(value) { + var ret = this.s["return"]; + return void 0 === ret ? Promise.resolve({ + value: value, + done: !0 + }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); + }, + "throw": function _throw(value) { + var thr = this.s["return"]; + return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); + } + }, new AsyncFromSyncIterator(s); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js new file mode 100644 index 0000000..c37aa2c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js @@ -0,0 +1,30 @@ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} +export default function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(undefined); + }); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js new file mode 100644 index 0000000..cfa0522 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js @@ -0,0 +1,4 @@ +import OverloadYield from "./OverloadYield.js"; +export default function _awaitAsyncGenerator(value) { + return new OverloadYield(value, 0); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/checkInRHS.js b/node_modules/@babel/runtime/helpers/esm/checkInRHS.js new file mode 100644 index 0000000..928d53d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/checkInRHS.js @@ -0,0 +1,5 @@ +import _typeof from "./typeof.js"; +export default function _checkInRHS(value) { + if (Object(value) !== value) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== value ? _typeof(value) : "null")); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js b/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js new file mode 100644 index 0000000..9901403 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/checkPrivateRedeclaration.js @@ -0,0 +1,5 @@ +export default function _checkPrivateRedeclaration(obj, privateCollection) { + if (privateCollection.has(obj)) { + throw new TypeError("Cannot initialize the same private elements twice on an object"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..68684f2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js @@ -0,0 +1,17 @@ +export default function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + }; + } + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + return descriptor; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js new file mode 100644 index 0000000..727e9e9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js @@ -0,0 +1,6 @@ +export default function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + return descriptor.value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js new file mode 100644 index 0000000..b4df6d3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js @@ -0,0 +1,10 @@ +export default function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + descriptor.value = value; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCallCheck.js b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js new file mode 100644 index 0000000..2f1738a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js @@ -0,0 +1,5 @@ +export default function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..098ed30 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..0ef34b8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js new file mode 100644 index 0000000..1a8d71b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js @@ -0,0 +1,6 @@ +export default function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + return privateMap.get(receiver); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js new file mode 100644 index 0000000..46eea93 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js @@ -0,0 +1,3 @@ +export default function _classNameTDZError(name) { + throw new ReferenceError("Class \"" + name + "\" cannot be referenced in computed property keys."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..fb58833 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js new file mode 100644 index 0000000..53cd137 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js new file mode 100644 index 0000000..2253dd8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldInitSpec.js @@ -0,0 +1,5 @@ +import checkPrivateRedeclaration from "./checkPrivateRedeclaration.js"; +export default function _classPrivateFieldInitSpec(obj, privateMap, value) { + checkPrivateRedeclaration(obj, privateMap); + privateMap.set(obj, value); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..09e9330 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js @@ -0,0 +1,6 @@ +export default function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + return receiver; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..5b7e5ac --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js @@ -0,0 +1,4 @@ +var id = 0; +export default function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js new file mode 100644 index 0000000..ad91be4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js @@ -0,0 +1,7 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js new file mode 100644 index 0000000..f32a3da --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js @@ -0,0 +1,6 @@ +export default function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return fn; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js new file mode 100644 index 0000000..18d1291 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodInitSpec.js @@ -0,0 +1,5 @@ +import checkPrivateRedeclaration from "./checkPrivateRedeclaration.js"; +export default function _classPrivateMethodInitSpec(obj, privateSet) { + checkPrivateRedeclaration(obj, privateSet); + privateSet.add(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js new file mode 100644 index 0000000..2bbaf3a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..77afcfb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..d253d31 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..b0b0cc6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,9 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..fddc7b2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js @@ -0,0 +1,5 @@ +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..d5ab60a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/construct.js b/node_modules/@babel/runtime/helpers/esm/construct.js new file mode 100644 index 0000000..3860bdd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/construct.js @@ -0,0 +1,17 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +export default function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + return _construct.apply(null, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createClass.js b/node_modules/@babel/runtime/helpers/esm/createClass.js new file mode 100644 index 0000000..bbacdfe --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createClass.js @@ -0,0 +1,18 @@ +import toPropertyKey from "./toPropertyKey.js"; +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); + } +} +export default function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js new file mode 100644 index 0000000..5e0e0f1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js @@ -0,0 +1,52 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + var F = function F() {}; + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..043857d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js @@ -0,0 +1,19 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createSuper.js b/node_modules/@babel/runtime/helpers/esm/createSuper.js new file mode 100644 index 0000000..7c96297 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createSuper.js @@ -0,0 +1,17 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +import possibleConstructorReturn from "./possibleConstructorReturn.js"; +export default function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return possibleConstructorReturn(this, result); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/decorate.js b/node_modules/@babel/runtime/helpers/esm/decorate.js new file mode 100644 index 0000000..e511dfe --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/decorate.js @@ -0,0 +1,342 @@ +import toArray from "./toArray.js"; +import toPropertyKey from "./toPropertyKey.js"; +export default function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + var newExtras = elementFinisherExtras.extras; + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + extras.push.apply(extras, newExtras); + } + } + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + var finisher = _optionalCallableProperty(elementObject, "finisher"); + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + var finisher = _optionalCallableProperty(obj, "finisher"); + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + constructor = newConstructor; + } + } + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} +function _coalesceClassElements(elements) { + var newElements = []; + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + other.decorators = element.decorators; + } + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + return newElements; +} +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defaults.js b/node_modules/@babel/runtime/helpers/esm/defaults.js new file mode 100644 index 0000000..9e59e9a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defaults.js @@ -0,0 +1,11 @@ +export default function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineAccessor.js b/node_modules/@babel/runtime/helpers/esm/defineAccessor.js new file mode 100644 index 0000000..154271d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineAccessor.js @@ -0,0 +1,7 @@ +export default function _defineAccessor(type, obj, key, fn) { + var desc = { + configurable: !0, + enumerable: !0 + }; + return desc[type] = fn, Object.defineProperty(obj, key, desc); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js new file mode 100644 index 0000000..0c04128 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js @@ -0,0 +1,19 @@ +export default function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineProperty.js b/node_modules/@babel/runtime/helpers/esm/defineProperty.js new file mode 100644 index 0000000..56c06a2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineProperty.js @@ -0,0 +1,15 @@ +import toPropertyKey from "./toPropertyKey.js"; +export default function _defineProperty(obj, key, value) { + key = toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/extends.js b/node_modules/@babel/runtime/helpers/esm/extends.js new file mode 100644 index 0000000..ab17131 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/extends.js @@ -0,0 +1,14 @@ +export default function _extends() { + _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/get.js b/node_modules/@babel/runtime/helpers/esm/get.js new file mode 100644 index 0000000..0705d5f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/get.js @@ -0,0 +1,17 @@ +import superPropBase from "./superPropBase.js"; +export default function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get.bind(); + } else { + _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } + return desc.value; + }; + } + return _get.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js new file mode 100644 index 0000000..e9bb1d5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js @@ -0,0 +1,6 @@ +export default function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/identity.js b/node_modules/@babel/runtime/helpers/esm/identity.js new file mode 100644 index 0000000..a1e7e4c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/identity.js @@ -0,0 +1,3 @@ +export default function _identity(x) { + return x; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inherits.js b/node_modules/@babel/runtime/helpers/esm/inherits.js new file mode 100644 index 0000000..0b0a0ea --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inherits.js @@ -0,0 +1,17 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js new file mode 100644 index 0000000..90bb796 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js @@ -0,0 +1,6 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js new file mode 100644 index 0000000..26fdea0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js @@ -0,0 +1,9 @@ +export default function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js new file mode 100644 index 0000000..30d518c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js @@ -0,0 +1,3 @@ +export default function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/instanceof.js b/node_modules/@babel/runtime/helpers/esm/instanceof.js new file mode 100644 index 0000000..8c43b71 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/instanceof.js @@ -0,0 +1,7 @@ +export default function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js new file mode 100644 index 0000000..c2df7b6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js @@ -0,0 +1,5 @@ +export default function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js new file mode 100644 index 0000000..6ec6309 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js @@ -0,0 +1,40 @@ +import _typeof from "./typeof.js"; +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +export default function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== "default" && 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; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js new file mode 100644 index 0000000..7b1bc82 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js @@ -0,0 +1,3 @@ +export default function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js new file mode 100644 index 0000000..6184080 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js @@ -0,0 +1,11 @@ +export default function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArray.js b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js new file mode 100644 index 0000000..cfe9fbd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js @@ -0,0 +1,3 @@ +export default function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js new file mode 100644 index 0000000..5c31a59 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js @@ -0,0 +1,27 @@ +export default function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; + } finally { + try { + if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..9237c30 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js @@ -0,0 +1,9 @@ +export default function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && ("undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]); + if (null != _i) { + var _s, + _arr = []; + for (_i = _i.call(arr); arr.length < i && !(_s = _i.next()).done;) _arr.push(_s.value); + return _arr; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/jsx.js b/node_modules/@babel/runtime/helpers/esm/jsx.js new file mode 100644 index 0000000..742afd5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/jsx.js @@ -0,0 +1,21 @@ +var REACT_ELEMENT_TYPE; +export default function _createRawReactElement(type, props, key, children) { + REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103); + var defaultProps = type && type.defaultProps, + childrenLength = arguments.length - 3; + if (props || 0 === childrenLength || (props = { + children: void 0 + }), 1 === childrenLength) props.children = children;else if (childrenLength > 1) { + for (var childArray = new Array(childrenLength), i = 0; i < childrenLength; i++) childArray[i] = arguments[i + 3]; + props.children = childArray; + } + if (props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]);else props || (props = defaultProps || {}); + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: void 0 === key ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js new file mode 100644 index 0000000..38fd78f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js @@ -0,0 +1,8 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + return next(arr, i); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js new file mode 100644 index 0000000..d6cd864 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js @@ -0,0 +1,5 @@ +export default function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js new file mode 100644 index 0000000..b349d00 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js @@ -0,0 +1,3 @@ +export default function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js new file mode 100644 index 0000000..82d8296 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js @@ -0,0 +1,3 @@ +export default function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js new file mode 100644 index 0000000..251b859 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js @@ -0,0 +1,3 @@ +export default function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure " + obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread.js b/node_modules/@babel/runtime/helpers/esm/objectSpread.js new file mode 100644 index 0000000..a4e05e5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread.js @@ -0,0 +1,16 @@ +import defineProperty from "./defineProperty.js"; +export default function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread2.js b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js new file mode 100644 index 0000000..7d69acc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js @@ -0,0 +1,22 @@ +import defineProperty from "./defineProperty.js"; +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; +} +export default function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js new file mode 100644 index 0000000..36804a3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js @@ -0,0 +1,16 @@ +import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js"; +export default function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..4b308bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js @@ -0,0 +1,12 @@ +export default function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/package.json b/node_modules/@babel/runtime/helpers/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js new file mode 100644 index 0000000..8778824 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js @@ -0,0 +1,10 @@ +import _typeof from "./typeof.js"; +import assertThisInitialized from "./assertThisInitialized.js"; +export default function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return assertThisInitialized(self); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/readOnlyError.js b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js new file mode 100644 index 0000000..166e40e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js @@ -0,0 +1,3 @@ +export default function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js b/node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js new file mode 100644 index 0000000..562d811 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js @@ -0,0 +1,303 @@ +import _typeof from "./typeof.js"; +export default function _regeneratorRuntime() { + "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + _regeneratorRuntime = function _regeneratorRuntime() { + return exports; + }; + var exports = {}, + Op = Object.prototype, + hasOwn = Op.hasOwnProperty, + defineProperty = Object.defineProperty || function (obj, key, desc) { + obj[key] = desc.value; + }, + $Symbol = "function" == typeof Symbol ? Symbol : {}, + iteratorSymbol = $Symbol.iterator || "@@iterator", + asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", + toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + function define(obj, key, value) { + return Object.defineProperty(obj, key, { + value: value, + enumerable: !0, + configurable: !0, + writable: !0 + }), obj[key]; + } + try { + define({}, ""); + } catch (err) { + define = function define(obj, key, value) { + return obj[key] = value; + }; + } + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, + generator = Object.create(protoGenerator.prototype), + context = new Context(tryLocsList || []); + return defineProperty(generator, "_invoke", { + value: makeInvokeMethod(innerFn, self, context) + }), generator; + } + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; + } + } + exports.wrap = wrap; + var ContinueSentinel = {}; + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf, + NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); + } + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if ("throw" !== record.type) { + var result = record.arg, + value = result.value; + return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }) : PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped, resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); + } + reject(record.arg); + } + var previousPromise; + defineProperty(this, "_invoke", { + value: function value(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + }); + } + function makeInvokeMethod(innerFn, self, context) { + var state = "suspendedStart"; + return function (method, arg) { + if ("executing" === state) throw new Error("Generator is already running"); + if ("completed" === state) { + if ("throw" === method) throw arg; + return doneResult(); + } + for (context.method = method, context.arg = arg;;) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { + if ("suspendedStart" === state) throw state = "completed", context.arg; + context.dispatchException(context.arg); + } else "return" === context.method && context.abrupt("return", context.arg); + state = "executing"; + var record = tryCatch(innerFn, self, context); + if ("normal" === record.type) { + if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; + return { + value: record.arg, + done: context.done + }; + } + "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); + } + }; + } + function maybeInvokeDelegate(delegate, context) { + var methodName = context.method, + method = delegate.iterator[methodName]; + if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; + var record = tryCatch(method, delegate.iterator, context.arg); + if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; + var info = record.arg; + return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + } + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); + } + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal", delete record.arg, entry.completion = record; + } + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); + } + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) return iteratorMethod.call(iterable); + if ("function" == typeof iterable.next) return iterable; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; + return next.value = undefined, next.done = !0, next; + }; + return next.next = next; + } + } + return { + next: doneResult + }; + } + function doneResult() { + return { + value: undefined, + done: !0 + }; + } + return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { + value: GeneratorFunctionPrototype, + configurable: !0 + }), defineProperty(GeneratorFunctionPrototype, "constructor", { + value: GeneratorFunction, + configurable: !0 + }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { + var ctor = "function" == typeof genFun && genFun.constructor; + return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); + }, exports.mark = function (genFun) { + return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; + }, exports.awrap = function (arg) { + return { + __await: arg + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + void 0 === PromiseImpl && (PromiseImpl = Promise); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { + return this; + }), define(Gp, "toString", function () { + return "[object Generator]"; + }), exports.keys = function (val) { + var object = Object(val), + keys = []; + for (var key in object) keys.push(key); + return keys.reverse(), function next() { + for (; keys.length;) { + var key = keys.pop(); + if (key in object) return next.value = key, next.done = !1, next; + } + return next.done = !0, next; + }; + }, exports.values = values, Context.prototype = { + constructor: Context, + reset: function reset(skipTempReset) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); + }, + stop: function stop() { + this.done = !0; + var rootRecord = this.tryEntries[0].completion; + if ("throw" === rootRecord.type) throw rootRecord.arg; + return this.rval; + }, + dispatchException: function dispatchException(exception) { + if (this.done) throw exception; + var context = this; + function handle(loc, caught) { + return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; + } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i], + record = entry.completion; + if ("root" === entry.tryLoc) return handle("end"); + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"), + hasFinally = hasOwn.call(entry, "finallyLoc"); + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } else if (hasCatch) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + } else { + if (!hasFinally) throw new Error("try statement without catch or finally"); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } + } + } + }, + abrupt: function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); + var record = finallyEntry ? finallyEntry.completion : {}; + return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); + }, + complete: function complete(record, afterLoc) { + if ("throw" === record.type) throw record.arg; + return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; + }, + finish: function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; + } + }, + "catch": function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if ("throw" === record.type) { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(iterable, resultName, nextLoc) { + return this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }, "next" === this.method && (this.arg = undefined), ContinueSentinel; + } + }, exports; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/set.js b/node_modules/@babel/runtime/helpers/esm/set.js new file mode 100644 index 0000000..c9ee6c7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/set.js @@ -0,0 +1,40 @@ +import superPropBase from "./superPropBase.js"; +import defineProperty from "./defineProperty.js"; +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + desc = Object.getOwnPropertyDescriptor(receiver, property); + if (desc) { + if (!desc.writable) { + return false; + } + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + return true; + }; + } + return set(target, property, value, receiver); +} +export default function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + if (!s && isStrict) { + throw new TypeError('failed to set property'); + } + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js new file mode 100644 index 0000000..905e13c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js @@ -0,0 +1,7 @@ +export default function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js new file mode 100644 index 0000000..cadd9bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js @@ -0,0 +1,7 @@ +export default function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArray.js b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js new file mode 100644 index 0000000..618200b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimit from "./iterableToArrayLimit.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js new file mode 100644 index 0000000..efc7429 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimitLoose from "./iterableToArrayLimitLoose.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/superPropBase.js b/node_modules/@babel/runtime/helpers/esm/superPropBase.js new file mode 100644 index 0000000..605724d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/superPropBase.js @@ -0,0 +1,8 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +export default function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + return object; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js new file mode 100644 index 0000000..990d5e4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js @@ -0,0 +1,10 @@ +export default function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..9fcba32 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js @@ -0,0 +1,7 @@ +export default function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + strings.raw = raw; + return strings; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/tdz.js b/node_modules/@babel/runtime/helpers/esm/tdz.js new file mode 100644 index 0000000..d5d0adc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/tdz.js @@ -0,0 +1,3 @@ +export default function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalRef.js b/node_modules/@babel/runtime/helpers/esm/temporalRef.js new file mode 100644 index 0000000..b25f7c4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalRef.js @@ -0,0 +1,5 @@ +import undef from "./temporalUndefined.js"; +import err from "./tdz.js"; +export default function _temporalRef(val, name) { + return val === undef ? err(name) : val; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js new file mode 100644 index 0000000..1a35717 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js @@ -0,0 +1 @@ +export default function _temporalUndefined() {} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toArray.js b/node_modules/@babel/runtime/helpers/esm/toArray.js new file mode 100644 index 0000000..ad7c871 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js new file mode 100644 index 0000000..bd91285 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js @@ -0,0 +1,7 @@ +import arrayWithoutHoles from "./arrayWithoutHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableSpread from "./nonIterableSpread.js"; +export default function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPrimitive.js b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js new file mode 100644 index 0000000..cbfabb7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js @@ -0,0 +1,11 @@ +import _typeof from "./typeof.js"; +export default function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js new file mode 100644 index 0000000..0fcc93b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js @@ -0,0 +1,6 @@ +import _typeof from "./typeof.js"; +import toPrimitive from "./toPrimitive.js"; +export default function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/typeof.js b/node_modules/@babel/runtime/helpers/esm/typeof.js new file mode 100644 index 0000000..92100c6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/typeof.js @@ -0,0 +1,9 @@ +export default function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js new file mode 100644 index 0000000..c0f63bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js @@ -0,0 +1,9 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js new file mode 100644 index 0000000..723b2dd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js @@ -0,0 +1,6 @@ +import AsyncGenerator from "./AsyncGenerator.js"; +export default function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js new file mode 100644 index 0000000..43d0ded --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js @@ -0,0 +1,30 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeFunction from "./isNativeFunction.js"; +import construct from "./construct.js"; +export default function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + _cache.set(Class, Wrapper); + } + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + return _wrapNativeSuper(Class); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js new file mode 100644 index 0000000..620d84c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js @@ -0,0 +1,50 @@ +import _typeof from "./typeof.js"; +import setPrototypeOf from "./setPrototypeOf.js"; +import inherits from "./inherits.js"; +export default function _wrapRegExp() { + _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, void 0, groups); + }; + var _super = RegExp.prototype, + _groups = new WeakMap(); + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); + } + function buildGroups(result, re) { + var g = _groups.get(re); + return Object.keys(g).reduce(function (groups, name) { + var i = g[name]; + if ("number" == typeof i) groups[name] = result[i];else { + for (var k = 0; void 0 === result[i[k]] && k + 1 < i.length;) k++; + groups[name] = result[i[k]]; + } + return groups; + }, Object.create(null)); + } + return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + if (result) { + result.groups = buildGroups(result, this); + var indices = result.indices; + indices && (indices.groups = buildGroups(indices, this)); + } + return result; + }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if ("string" == typeof substitution) { + var groups = _groups.get(this); + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + var group = groups[name]; + return "$" + (Array.isArray(group) ? group.join("$") : group); + })); + } + if ("function" == typeof substitution) { + var _this = this; + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); + }); + } + return _super[Symbol.replace].call(this, str, substitution); + }, _wrapRegExp.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js new file mode 100644 index 0000000..9170bd4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js @@ -0,0 +1,3 @@ +export default function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/extends.js b/node_modules/@babel/runtime/helpers/extends.js new file mode 100644 index 0000000..bb11160 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/extends.js @@ -0,0 +1,15 @@ +function _extends() { + module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _extends.apply(this, arguments); +} +module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/get.js b/node_modules/@babel/runtime/helpers/get.js new file mode 100644 index 0000000..9b44d2f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/get.js @@ -0,0 +1,18 @@ +var superPropBase = require("./superPropBase.js"); +function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + module.exports = _get = Reflect.get.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } + return desc.value; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + } + return _get.apply(this, arguments); +} +module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/getPrototypeOf.js new file mode 100644 index 0000000..0639a65 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/getPrototypeOf.js @@ -0,0 +1,7 @@ +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _getPrototypeOf(o); +} +module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/identity.js b/node_modules/@babel/runtime/helpers/identity.js new file mode 100644 index 0000000..7dd82dc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/identity.js @@ -0,0 +1,4 @@ +function _identity(x) { + return x; +} +module.exports = _identity, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inherits.js b/node_modules/@babel/runtime/helpers/inherits.js new file mode 100644 index 0000000..6521cce --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inherits.js @@ -0,0 +1,18 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) setPrototypeOf(subClass, superClass); +} +module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inheritsLoose.js b/node_modules/@babel/runtime/helpers/inheritsLoose.js new file mode 100644 index 0000000..19a60c9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inheritsLoose.js @@ -0,0 +1,7 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} +module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js new file mode 100644 index 0000000..7f35d50 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js @@ -0,0 +1,10 @@ +function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} +module.exports = _initializerDefineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js new file mode 100644 index 0000000..c58b04e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js @@ -0,0 +1,4 @@ +function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} +module.exports = _initializerWarningHelper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/instanceof.js b/node_modules/@babel/runtime/helpers/instanceof.js new file mode 100644 index 0000000..bc3d9e7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/instanceof.js @@ -0,0 +1,8 @@ +function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} +module.exports = _instanceof, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/interopRequireDefault.js new file mode 100644 index 0000000..429b270 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireDefault.js @@ -0,0 +1,6 @@ +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} +module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js new file mode 100644 index 0000000..3765dcc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js @@ -0,0 +1,41 @@ +var _typeof = require("./typeof.js")["default"]; +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== "default" && 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; +} +module.exports = _interopRequireWildcard, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeFunction.js b/node_modules/@babel/runtime/helpers/isNativeFunction.js new file mode 100644 index 0000000..ea59535 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeFunction.js @@ -0,0 +1,4 @@ +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} +module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js new file mode 100644 index 0000000..6b4e73f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js @@ -0,0 +1,12 @@ +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} +module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArray.js b/node_modules/@babel/runtime/helpers/iterableToArray.js new file mode 100644 index 0000000..8960752 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArray.js @@ -0,0 +1,4 @@ +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} +module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js new file mode 100644 index 0000000..20a1835 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js @@ -0,0 +1,28 @@ +function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; + } finally { + try { + if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } +} +module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..c56bebd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js @@ -0,0 +1,10 @@ +function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && ("undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]); + if (null != _i) { + var _s, + _arr = []; + for (_i = _i.call(arr); arr.length < i && !(_s = _i.next()).done;) _arr.push(_s.value); + return _arr; + } +} +module.exports = _iterableToArrayLimitLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/jsx.js b/node_modules/@babel/runtime/helpers/jsx.js new file mode 100644 index 0000000..8c6de76 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/jsx.js @@ -0,0 +1,22 @@ +var REACT_ELEMENT_TYPE; +function _createRawReactElement(type, props, key, children) { + REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103); + var defaultProps = type && type.defaultProps, + childrenLength = arguments.length - 3; + if (props || 0 === childrenLength || (props = { + children: void 0 + }), 1 === childrenLength) props.children = children;else if (childrenLength > 1) { + for (var childArray = new Array(childrenLength), i = 0; i < childrenLength; i++) childArray[i] = arguments[i + 3]; + props.children = childArray; + } + if (props && defaultProps) for (var propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]);else props || (props = defaultProps || {}); + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: void 0 === key ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} +module.exports = _createRawReactElement, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/maybeArrayLike.js new file mode 100644 index 0000000..5d00097 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/maybeArrayLike.js @@ -0,0 +1,9 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); +function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + return next(arr, i); +} +module.exports = _maybeArrayLike, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/newArrowCheck.js b/node_modules/@babel/runtime/helpers/newArrowCheck.js new file mode 100644 index 0000000..9c680c8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/newArrowCheck.js @@ -0,0 +1,6 @@ +function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} +module.exports = _newArrowCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableRest.js b/node_modules/@babel/runtime/helpers/nonIterableRest.js new file mode 100644 index 0000000..95265ba --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableRest.js @@ -0,0 +1,4 @@ +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/nonIterableSpread.js new file mode 100644 index 0000000..3fcf23f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableSpread.js @@ -0,0 +1,4 @@ +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js new file mode 100644 index 0000000..5b405e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js @@ -0,0 +1,4 @@ +function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure " + obj); +} +module.exports = _objectDestructuringEmpty, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread.js b/node_modules/@babel/runtime/helpers/objectSpread.js new file mode 100644 index 0000000..f393403 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread.js @@ -0,0 +1,17 @@ +var defineProperty = require("./defineProperty.js"); +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + return target; +} +module.exports = _objectSpread, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread2.js b/node_modules/@babel/runtime/helpers/objectSpread2.js new file mode 100644 index 0000000..214f9e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread2.js @@ -0,0 +1,23 @@ +var defineProperty = require("./defineProperty.js"); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; +} +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; +} +module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js new file mode 100644 index 0000000..cf526bc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js @@ -0,0 +1,17 @@ +var objectWithoutPropertiesLoose = require("./objectWithoutPropertiesLoose.js"); +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + return target; +} +module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..3c65a9d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js @@ -0,0 +1,13 @@ +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; +} +module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js new file mode 100644 index 0000000..b2424b0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js @@ -0,0 +1,11 @@ +var _typeof = require("./typeof.js")["default"]; +var assertThisInitialized = require("./assertThisInitialized.js"); +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return assertThisInitialized(self); +} +module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/readOnlyError.js b/node_modules/@babel/runtime/helpers/readOnlyError.js new file mode 100644 index 0000000..6637a0e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/readOnlyError.js @@ -0,0 +1,4 @@ +function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} +module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/regeneratorRuntime.js b/node_modules/@babel/runtime/helpers/regeneratorRuntime.js new file mode 100644 index 0000000..98db591 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/regeneratorRuntime.js @@ -0,0 +1,304 @@ +var _typeof = require("./typeof.js")["default"]; +function _regeneratorRuntime() { + "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + module.exports = _regeneratorRuntime = function _regeneratorRuntime() { + return exports; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + var exports = {}, + Op = Object.prototype, + hasOwn = Op.hasOwnProperty, + defineProperty = Object.defineProperty || function (obj, key, desc) { + obj[key] = desc.value; + }, + $Symbol = "function" == typeof Symbol ? Symbol : {}, + iteratorSymbol = $Symbol.iterator || "@@iterator", + asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", + toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + function define(obj, key, value) { + return Object.defineProperty(obj, key, { + value: value, + enumerable: !0, + configurable: !0, + writable: !0 + }), obj[key]; + } + try { + define({}, ""); + } catch (err) { + define = function define(obj, key, value) { + return obj[key] = value; + }; + } + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, + generator = Object.create(protoGenerator.prototype), + context = new Context(tryLocsList || []); + return defineProperty(generator, "_invoke", { + value: makeInvokeMethod(innerFn, self, context) + }), generator; + } + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; + } + } + exports.wrap = wrap; + var ContinueSentinel = {}; + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf, + NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); + } + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if ("throw" !== record.type) { + var result = record.arg, + value = result.value; + return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }) : PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped, resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); + } + reject(record.arg); + } + var previousPromise; + defineProperty(this, "_invoke", { + value: function value(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + }); + } + function makeInvokeMethod(innerFn, self, context) { + var state = "suspendedStart"; + return function (method, arg) { + if ("executing" === state) throw new Error("Generator is already running"); + if ("completed" === state) { + if ("throw" === method) throw arg; + return doneResult(); + } + for (context.method = method, context.arg = arg;;) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { + if ("suspendedStart" === state) throw state = "completed", context.arg; + context.dispatchException(context.arg); + } else "return" === context.method && context.abrupt("return", context.arg); + state = "executing"; + var record = tryCatch(innerFn, self, context); + if ("normal" === record.type) { + if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; + return { + value: record.arg, + done: context.done + }; + } + "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); + } + }; + } + function maybeInvokeDelegate(delegate, context) { + var methodName = context.method, + method = delegate.iterator[methodName]; + if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; + var record = tryCatch(method, delegate.iterator, context.arg); + if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; + var info = record.arg; + return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + } + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); + } + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal", delete record.arg, entry.completion = record; + } + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); + } + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) return iteratorMethod.call(iterable); + if ("function" == typeof iterable.next) return iterable; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; + return next.value = undefined, next.done = !0, next; + }; + return next.next = next; + } + } + return { + next: doneResult + }; + } + function doneResult() { + return { + value: undefined, + done: !0 + }; + } + return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { + value: GeneratorFunctionPrototype, + configurable: !0 + }), defineProperty(GeneratorFunctionPrototype, "constructor", { + value: GeneratorFunction, + configurable: !0 + }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { + var ctor = "function" == typeof genFun && genFun.constructor; + return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); + }, exports.mark = function (genFun) { + return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; + }, exports.awrap = function (arg) { + return { + __await: arg + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + void 0 === PromiseImpl && (PromiseImpl = Promise); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { + return this; + }), define(Gp, "toString", function () { + return "[object Generator]"; + }), exports.keys = function (val) { + var object = Object(val), + keys = []; + for (var key in object) keys.push(key); + return keys.reverse(), function next() { + for (; keys.length;) { + var key = keys.pop(); + if (key in object) return next.value = key, next.done = !1, next; + } + return next.done = !0, next; + }; + }, exports.values = values, Context.prototype = { + constructor: Context, + reset: function reset(skipTempReset) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); + }, + stop: function stop() { + this.done = !0; + var rootRecord = this.tryEntries[0].completion; + if ("throw" === rootRecord.type) throw rootRecord.arg; + return this.rval; + }, + dispatchException: function dispatchException(exception) { + if (this.done) throw exception; + var context = this; + function handle(loc, caught) { + return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; + } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i], + record = entry.completion; + if ("root" === entry.tryLoc) return handle("end"); + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"), + hasFinally = hasOwn.call(entry, "finallyLoc"); + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } else if (hasCatch) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + } else { + if (!hasFinally) throw new Error("try statement without catch or finally"); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } + } + } + }, + abrupt: function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); + var record = finallyEntry ? finallyEntry.completion : {}; + return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); + }, + complete: function complete(record, afterLoc) { + if ("throw" === record.type) throw record.arg; + return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; + }, + finish: function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; + } + }, + "catch": function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if ("throw" === record.type) { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(iterable, resultName, nextLoc) { + return this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }, "next" === this.method && (this.arg = undefined), ContinueSentinel; + } + }, exports; +} +module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/set.js b/node_modules/@babel/runtime/helpers/set.js new file mode 100644 index 0000000..e135624 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/set.js @@ -0,0 +1,41 @@ +var superPropBase = require("./superPropBase.js"); +var defineProperty = require("./defineProperty.js"); +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + desc = Object.getOwnPropertyDescriptor(receiver, property); + if (desc) { + if (!desc.writable) { + return false; + } + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + return true; + }; + } + return set(target, property, value, receiver); +} +function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + if (!s && isStrict) { + throw new TypeError('failed to set property'); + } + return value; +} +module.exports = _set, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/setPrototypeOf.js new file mode 100644 index 0000000..e0d8b51 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/setPrototypeOf.js @@ -0,0 +1,8 @@ +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _setPrototypeOf(o, p); +} +module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js new file mode 100644 index 0000000..ca269aa --- /dev/null +++ b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js @@ -0,0 +1,8 @@ +function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} +module.exports = _skipFirstGeneratorNext, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArray.js b/node_modules/@babel/runtime/helpers/slicedToArray.js new file mode 100644 index 0000000..534b61a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArray.js @@ -0,0 +1,8 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); +var iterableToArrayLimit = require("./iterableToArrayLimit.js"); +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +var nonIterableRest = require("./nonIterableRest.js"); +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} +module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js new file mode 100644 index 0000000..b1989b4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js @@ -0,0 +1,8 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); +var iterableToArrayLimitLoose = require("./iterableToArrayLimitLoose.js"); +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +var nonIterableRest = require("./nonIterableRest.js"); +function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} +module.exports = _slicedToArrayLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/superPropBase.js b/node_modules/@babel/runtime/helpers/superPropBase.js new file mode 100644 index 0000000..e43a029 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/superPropBase.js @@ -0,0 +1,9 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + return object; +} +module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js new file mode 100644 index 0000000..1ab0e7a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js @@ -0,0 +1,11 @@ +function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} +module.exports = _taggedTemplateLiteral, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..904e1a7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js @@ -0,0 +1,8 @@ +function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + strings.raw = raw; + return strings; +} +module.exports = _taggedTemplateLiteralLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/tdz.js b/node_modules/@babel/runtime/helpers/tdz.js new file mode 100644 index 0000000..0641c76 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/tdz.js @@ -0,0 +1,4 @@ +function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} +module.exports = _tdzError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalRef.js b/node_modules/@babel/runtime/helpers/temporalRef.js new file mode 100644 index 0000000..a9be53d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalRef.js @@ -0,0 +1,6 @@ +var temporalUndefined = require("./temporalUndefined.js"); +var tdz = require("./tdz.js"); +function _temporalRef(val, name) { + return val === temporalUndefined ? tdz(name) : val; +} +module.exports = _temporalRef, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalUndefined.js b/node_modules/@babel/runtime/helpers/temporalUndefined.js new file mode 100644 index 0000000..f8def80 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalUndefined.js @@ -0,0 +1,2 @@ +function _temporalUndefined() {} +module.exports = _temporalUndefined, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toArray.js b/node_modules/@babel/runtime/helpers/toArray.js new file mode 100644 index 0000000..5c808c2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toArray.js @@ -0,0 +1,8 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); +var iterableToArray = require("./iterableToArray.js"); +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +var nonIterableRest = require("./nonIterableRest.js"); +function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} +module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toConsumableArray.js b/node_modules/@babel/runtime/helpers/toConsumableArray.js new file mode 100644 index 0000000..547c6c4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toConsumableArray.js @@ -0,0 +1,8 @@ +var arrayWithoutHoles = require("./arrayWithoutHoles.js"); +var iterableToArray = require("./iterableToArray.js"); +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); +var nonIterableSpread = require("./nonIterableSpread.js"); +function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} +module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPrimitive.js b/node_modules/@babel/runtime/helpers/toPrimitive.js new file mode 100644 index 0000000..adf63bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPrimitive.js @@ -0,0 +1,12 @@ +var _typeof = require("./typeof.js")["default"]; +function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPropertyKey.js b/node_modules/@babel/runtime/helpers/toPropertyKey.js new file mode 100644 index 0000000..320bb2b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPropertyKey.js @@ -0,0 +1,7 @@ +var _typeof = require("./typeof.js")["default"]; +var toPrimitive = require("./toPrimitive.js"); +function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} +module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/typeof.js b/node_modules/@babel/runtime/helpers/typeof.js new file mode 100644 index 0000000..aa88477 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/typeof.js @@ -0,0 +1,10 @@ +function _typeof(obj) { + "@babel/helpers - typeof"; + + return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); +} +module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js new file mode 100644 index 0000000..b7d18c6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js @@ -0,0 +1,10 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} +module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js new file mode 100644 index 0000000..a62dcf0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js @@ -0,0 +1,7 @@ +var AsyncGenerator = require("./AsyncGenerator.js"); +function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} +module.exports = _wrapAsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js new file mode 100644 index 0000000..b6ea60c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js @@ -0,0 +1,31 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); +var setPrototypeOf = require("./setPrototypeOf.js"); +var isNativeFunction = require("./isNativeFunction.js"); +var construct = require("./construct.js"); +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + _cache.set(Class, Wrapper); + } + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _wrapNativeSuper(Class); +} +module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapRegExp.js b/node_modules/@babel/runtime/helpers/wrapRegExp.js new file mode 100644 index 0000000..da710f8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapRegExp.js @@ -0,0 +1,51 @@ +var _typeof = require("./typeof.js")["default"]; +var setPrototypeOf = require("./setPrototypeOf.js"); +var inherits = require("./inherits.js"); +function _wrapRegExp() { + module.exports = _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, void 0, groups); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + var _super = RegExp.prototype, + _groups = new WeakMap(); + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + return _groups.set(_this, groups || _groups.get(re)), setPrototypeOf(_this, BabelRegExp.prototype); + } + function buildGroups(result, re) { + var g = _groups.get(re); + return Object.keys(g).reduce(function (groups, name) { + var i = g[name]; + if ("number" == typeof i) groups[name] = result[i];else { + for (var k = 0; void 0 === result[i[k]] && k + 1 < i.length;) k++; + groups[name] = result[i[k]]; + } + return groups; + }, Object.create(null)); + } + return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + if (result) { + result.groups = buildGroups(result, this); + var indices = result.indices; + indices && (indices.groups = buildGroups(indices, this)); + } + return result; + }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if ("string" == typeof substitution) { + var groups = _groups.get(this); + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + var group = groups[name]; + return "$" + (Array.isArray(group) ? group.join("$") : group); + })); + } + if ("function" == typeof substitution) { + var _this = this; + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + return "object" != _typeof(args[args.length - 1]) && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args); + }); + } + return _super[Symbol.replace].call(this, str, substitution); + }, _wrapRegExp.apply(this, arguments); +} +module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/writeOnlyError.js b/node_modules/@babel/runtime/helpers/writeOnlyError.js new file mode 100644 index 0000000..c66c6f2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/writeOnlyError.js @@ -0,0 +1,4 @@ +function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} +module.exports = _writeOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@babel/runtime/package.json b/node_modules/@babel/runtime/package.json new file mode 100644 index 0000000..f92f541 --- /dev/null +++ b/node_modules/@babel/runtime/package.json @@ -0,0 +1,930 @@ +{ + "name": "@babel/runtime", + "version": "7.21.0", + "description": "babel's modular runtime helpers", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-runtime" + }, + "homepage": "https://babel.dev/docs/en/next/babel-runtime", + "author": "The Babel Team (https://babel.dev/team)", + "dependencies": { + "regenerator-runtime": "^0.13.11" + }, + "exports": { + "./helpers/AsyncGenerator": [ + { + "node": "./helpers/AsyncGenerator.js", + "import": "./helpers/esm/AsyncGenerator.js", + "default": "./helpers/AsyncGenerator.js" + }, + "./helpers/AsyncGenerator.js" + ], + "./helpers/esm/AsyncGenerator": "./helpers/esm/AsyncGenerator.js", + "./helpers/OverloadYield": [ + { + "node": "./helpers/OverloadYield.js", + "import": "./helpers/esm/OverloadYield.js", + "default": "./helpers/OverloadYield.js" + }, + "./helpers/OverloadYield.js" + ], + "./helpers/esm/OverloadYield": "./helpers/esm/OverloadYield.js", + "./helpers/applyDecs": [ + { + "node": "./helpers/applyDecs.js", + "import": "./helpers/esm/applyDecs.js", + "default": "./helpers/applyDecs.js" + }, + "./helpers/applyDecs.js" + ], + "./helpers/esm/applyDecs": "./helpers/esm/applyDecs.js", + "./helpers/applyDecs2203": [ + { + "node": "./helpers/applyDecs2203.js", + "import": "./helpers/esm/applyDecs2203.js", + "default": "./helpers/applyDecs2203.js" + }, + "./helpers/applyDecs2203.js" + ], + "./helpers/esm/applyDecs2203": "./helpers/esm/applyDecs2203.js", + "./helpers/applyDecs2203R": [ + { + "node": "./helpers/applyDecs2203R.js", + "import": "./helpers/esm/applyDecs2203R.js", + "default": "./helpers/applyDecs2203R.js" + }, + "./helpers/applyDecs2203R.js" + ], + "./helpers/esm/applyDecs2203R": "./helpers/esm/applyDecs2203R.js", + "./helpers/applyDecs2301": [ + { + "node": "./helpers/applyDecs2301.js", + "import": "./helpers/esm/applyDecs2301.js", + "default": "./helpers/applyDecs2301.js" + }, + "./helpers/applyDecs2301.js" + ], + "./helpers/esm/applyDecs2301": "./helpers/esm/applyDecs2301.js", + "./helpers/asyncGeneratorDelegate": [ + { + "node": "./helpers/asyncGeneratorDelegate.js", + "import": "./helpers/esm/asyncGeneratorDelegate.js", + "default": "./helpers/asyncGeneratorDelegate.js" + }, + "./helpers/asyncGeneratorDelegate.js" + ], + "./helpers/esm/asyncGeneratorDelegate": "./helpers/esm/asyncGeneratorDelegate.js", + "./helpers/asyncIterator": [ + { + "node": "./helpers/asyncIterator.js", + "import": "./helpers/esm/asyncIterator.js", + "default": "./helpers/asyncIterator.js" + }, + "./helpers/asyncIterator.js" + ], + "./helpers/esm/asyncIterator": "./helpers/esm/asyncIterator.js", + "./helpers/awaitAsyncGenerator": [ + { + "node": "./helpers/awaitAsyncGenerator.js", + "import": "./helpers/esm/awaitAsyncGenerator.js", + "default": "./helpers/awaitAsyncGenerator.js" + }, + "./helpers/awaitAsyncGenerator.js" + ], + "./helpers/esm/awaitAsyncGenerator": "./helpers/esm/awaitAsyncGenerator.js", + "./helpers/checkInRHS": [ + { + "node": "./helpers/checkInRHS.js", + "import": "./helpers/esm/checkInRHS.js", + "default": "./helpers/checkInRHS.js" + }, + "./helpers/checkInRHS.js" + ], + "./helpers/esm/checkInRHS": "./helpers/esm/checkInRHS.js", + "./helpers/defineAccessor": [ + { + "node": "./helpers/defineAccessor.js", + "import": "./helpers/esm/defineAccessor.js", + "default": "./helpers/defineAccessor.js" + }, + "./helpers/defineAccessor.js" + ], + "./helpers/esm/defineAccessor": "./helpers/esm/defineAccessor.js", + "./helpers/iterableToArrayLimit": [ + { + "node": "./helpers/iterableToArrayLimit.js", + "import": "./helpers/esm/iterableToArrayLimit.js", + "default": "./helpers/iterableToArrayLimit.js" + }, + "./helpers/iterableToArrayLimit.js" + ], + "./helpers/esm/iterableToArrayLimit": "./helpers/esm/iterableToArrayLimit.js", + "./helpers/iterableToArrayLimitLoose": [ + { + "node": "./helpers/iterableToArrayLimitLoose.js", + "import": "./helpers/esm/iterableToArrayLimitLoose.js", + "default": "./helpers/iterableToArrayLimitLoose.js" + }, + "./helpers/iterableToArrayLimitLoose.js" + ], + "./helpers/esm/iterableToArrayLimitLoose": "./helpers/esm/iterableToArrayLimitLoose.js", + "./helpers/jsx": [ + { + "node": "./helpers/jsx.js", + "import": "./helpers/esm/jsx.js", + "default": "./helpers/jsx.js" + }, + "./helpers/jsx.js" + ], + "./helpers/esm/jsx": "./helpers/esm/jsx.js", + "./helpers/objectSpread2": [ + { + "node": "./helpers/objectSpread2.js", + "import": "./helpers/esm/objectSpread2.js", + "default": "./helpers/objectSpread2.js" + }, + "./helpers/objectSpread2.js" + ], + "./helpers/esm/objectSpread2": "./helpers/esm/objectSpread2.js", + "./helpers/regeneratorRuntime": [ + { + "node": "./helpers/regeneratorRuntime.js", + "import": "./helpers/esm/regeneratorRuntime.js", + "default": "./helpers/regeneratorRuntime.js" + }, + "./helpers/regeneratorRuntime.js" + ], + "./helpers/esm/regeneratorRuntime": "./helpers/esm/regeneratorRuntime.js", + "./helpers/typeof": [ + { + "node": "./helpers/typeof.js", + "import": "./helpers/esm/typeof.js", + "default": "./helpers/typeof.js" + }, + "./helpers/typeof.js" + ], + "./helpers/esm/typeof": "./helpers/esm/typeof.js", + "./helpers/wrapRegExp": [ + { + "node": "./helpers/wrapRegExp.js", + "import": "./helpers/esm/wrapRegExp.js", + "default": "./helpers/wrapRegExp.js" + }, + "./helpers/wrapRegExp.js" + ], + "./helpers/esm/wrapRegExp": "./helpers/esm/wrapRegExp.js", + "./helpers/AwaitValue": [ + { + "node": "./helpers/AwaitValue.js", + "import": "./helpers/esm/AwaitValue.js", + "default": "./helpers/AwaitValue.js" + }, + "./helpers/AwaitValue.js" + ], + "./helpers/esm/AwaitValue": "./helpers/esm/AwaitValue.js", + "./helpers/wrapAsyncGenerator": [ + { + "node": "./helpers/wrapAsyncGenerator.js", + "import": "./helpers/esm/wrapAsyncGenerator.js", + "default": "./helpers/wrapAsyncGenerator.js" + }, + "./helpers/wrapAsyncGenerator.js" + ], + "./helpers/esm/wrapAsyncGenerator": "./helpers/esm/wrapAsyncGenerator.js", + "./helpers/asyncToGenerator": [ + { + "node": "./helpers/asyncToGenerator.js", + "import": "./helpers/esm/asyncToGenerator.js", + "default": "./helpers/asyncToGenerator.js" + }, + "./helpers/asyncToGenerator.js" + ], + "./helpers/esm/asyncToGenerator": "./helpers/esm/asyncToGenerator.js", + "./helpers/classCallCheck": [ + { + "node": "./helpers/classCallCheck.js", + "import": "./helpers/esm/classCallCheck.js", + "default": "./helpers/classCallCheck.js" + }, + "./helpers/classCallCheck.js" + ], + "./helpers/esm/classCallCheck": "./helpers/esm/classCallCheck.js", + "./helpers/createClass": [ + { + "node": "./helpers/createClass.js", + "import": "./helpers/esm/createClass.js", + "default": "./helpers/createClass.js" + }, + "./helpers/createClass.js" + ], + "./helpers/esm/createClass": "./helpers/esm/createClass.js", + "./helpers/defineEnumerableProperties": [ + { + "node": "./helpers/defineEnumerableProperties.js", + "import": "./helpers/esm/defineEnumerableProperties.js", + "default": "./helpers/defineEnumerableProperties.js" + }, + "./helpers/defineEnumerableProperties.js" + ], + "./helpers/esm/defineEnumerableProperties": "./helpers/esm/defineEnumerableProperties.js", + "./helpers/defaults": [ + { + "node": "./helpers/defaults.js", + "import": "./helpers/esm/defaults.js", + "default": "./helpers/defaults.js" + }, + "./helpers/defaults.js" + ], + "./helpers/esm/defaults": "./helpers/esm/defaults.js", + "./helpers/defineProperty": [ + { + "node": "./helpers/defineProperty.js", + "import": "./helpers/esm/defineProperty.js", + "default": "./helpers/defineProperty.js" + }, + "./helpers/defineProperty.js" + ], + "./helpers/esm/defineProperty": "./helpers/esm/defineProperty.js", + "./helpers/extends": [ + { + "node": "./helpers/extends.js", + "import": "./helpers/esm/extends.js", + "default": "./helpers/extends.js" + }, + "./helpers/extends.js" + ], + "./helpers/esm/extends": "./helpers/esm/extends.js", + "./helpers/objectSpread": [ + { + "node": "./helpers/objectSpread.js", + "import": "./helpers/esm/objectSpread.js", + "default": "./helpers/objectSpread.js" + }, + "./helpers/objectSpread.js" + ], + "./helpers/esm/objectSpread": "./helpers/esm/objectSpread.js", + "./helpers/inherits": [ + { + "node": "./helpers/inherits.js", + "import": "./helpers/esm/inherits.js", + "default": "./helpers/inherits.js" + }, + "./helpers/inherits.js" + ], + "./helpers/esm/inherits": "./helpers/esm/inherits.js", + "./helpers/inheritsLoose": [ + { + "node": "./helpers/inheritsLoose.js", + "import": "./helpers/esm/inheritsLoose.js", + "default": "./helpers/inheritsLoose.js" + }, + "./helpers/inheritsLoose.js" + ], + "./helpers/esm/inheritsLoose": "./helpers/esm/inheritsLoose.js", + "./helpers/getPrototypeOf": [ + { + "node": "./helpers/getPrototypeOf.js", + "import": "./helpers/esm/getPrototypeOf.js", + "default": "./helpers/getPrototypeOf.js" + }, + "./helpers/getPrototypeOf.js" + ], + "./helpers/esm/getPrototypeOf": "./helpers/esm/getPrototypeOf.js", + "./helpers/setPrototypeOf": [ + { + "node": "./helpers/setPrototypeOf.js", + "import": "./helpers/esm/setPrototypeOf.js", + "default": "./helpers/setPrototypeOf.js" + }, + "./helpers/setPrototypeOf.js" + ], + "./helpers/esm/setPrototypeOf": "./helpers/esm/setPrototypeOf.js", + "./helpers/isNativeReflectConstruct": [ + { + "node": "./helpers/isNativeReflectConstruct.js", + "import": "./helpers/esm/isNativeReflectConstruct.js", + "default": "./helpers/isNativeReflectConstruct.js" + }, + "./helpers/isNativeReflectConstruct.js" + ], + "./helpers/esm/isNativeReflectConstruct": "./helpers/esm/isNativeReflectConstruct.js", + "./helpers/construct": [ + { + "node": "./helpers/construct.js", + "import": "./helpers/esm/construct.js", + "default": "./helpers/construct.js" + }, + "./helpers/construct.js" + ], + "./helpers/esm/construct": "./helpers/esm/construct.js", + "./helpers/isNativeFunction": [ + { + "node": "./helpers/isNativeFunction.js", + "import": "./helpers/esm/isNativeFunction.js", + "default": "./helpers/isNativeFunction.js" + }, + "./helpers/isNativeFunction.js" + ], + "./helpers/esm/isNativeFunction": "./helpers/esm/isNativeFunction.js", + "./helpers/wrapNativeSuper": [ + { + "node": "./helpers/wrapNativeSuper.js", + "import": "./helpers/esm/wrapNativeSuper.js", + "default": "./helpers/wrapNativeSuper.js" + }, + "./helpers/wrapNativeSuper.js" + ], + "./helpers/esm/wrapNativeSuper": "./helpers/esm/wrapNativeSuper.js", + "./helpers/instanceof": [ + { + "node": "./helpers/instanceof.js", + "import": "./helpers/esm/instanceof.js", + "default": "./helpers/instanceof.js" + }, + "./helpers/instanceof.js" + ], + "./helpers/esm/instanceof": "./helpers/esm/instanceof.js", + "./helpers/interopRequireDefault": [ + { + "node": "./helpers/interopRequireDefault.js", + "import": "./helpers/esm/interopRequireDefault.js", + "default": "./helpers/interopRequireDefault.js" + }, + "./helpers/interopRequireDefault.js" + ], + "./helpers/esm/interopRequireDefault": "./helpers/esm/interopRequireDefault.js", + "./helpers/interopRequireWildcard": [ + { + "node": "./helpers/interopRequireWildcard.js", + "import": "./helpers/esm/interopRequireWildcard.js", + "default": "./helpers/interopRequireWildcard.js" + }, + "./helpers/interopRequireWildcard.js" + ], + "./helpers/esm/interopRequireWildcard": "./helpers/esm/interopRequireWildcard.js", + "./helpers/newArrowCheck": [ + { + "node": "./helpers/newArrowCheck.js", + "import": "./helpers/esm/newArrowCheck.js", + "default": "./helpers/newArrowCheck.js" + }, + "./helpers/newArrowCheck.js" + ], + "./helpers/esm/newArrowCheck": "./helpers/esm/newArrowCheck.js", + "./helpers/objectDestructuringEmpty": [ + { + "node": "./helpers/objectDestructuringEmpty.js", + "import": "./helpers/esm/objectDestructuringEmpty.js", + "default": "./helpers/objectDestructuringEmpty.js" + }, + "./helpers/objectDestructuringEmpty.js" + ], + "./helpers/esm/objectDestructuringEmpty": "./helpers/esm/objectDestructuringEmpty.js", + "./helpers/objectWithoutPropertiesLoose": [ + { + "node": "./helpers/objectWithoutPropertiesLoose.js", + "import": "./helpers/esm/objectWithoutPropertiesLoose.js", + "default": "./helpers/objectWithoutPropertiesLoose.js" + }, + "./helpers/objectWithoutPropertiesLoose.js" + ], + "./helpers/esm/objectWithoutPropertiesLoose": "./helpers/esm/objectWithoutPropertiesLoose.js", + "./helpers/objectWithoutProperties": [ + { + "node": "./helpers/objectWithoutProperties.js", + "import": "./helpers/esm/objectWithoutProperties.js", + "default": "./helpers/objectWithoutProperties.js" + }, + "./helpers/objectWithoutProperties.js" + ], + "./helpers/esm/objectWithoutProperties": "./helpers/esm/objectWithoutProperties.js", + "./helpers/assertThisInitialized": [ + { + "node": "./helpers/assertThisInitialized.js", + "import": "./helpers/esm/assertThisInitialized.js", + "default": "./helpers/assertThisInitialized.js" + }, + "./helpers/assertThisInitialized.js" + ], + "./helpers/esm/assertThisInitialized": "./helpers/esm/assertThisInitialized.js", + "./helpers/possibleConstructorReturn": [ + { + "node": "./helpers/possibleConstructorReturn.js", + "import": "./helpers/esm/possibleConstructorReturn.js", + "default": "./helpers/possibleConstructorReturn.js" + }, + "./helpers/possibleConstructorReturn.js" + ], + "./helpers/esm/possibleConstructorReturn": "./helpers/esm/possibleConstructorReturn.js", + "./helpers/createSuper": [ + { + "node": "./helpers/createSuper.js", + "import": "./helpers/esm/createSuper.js", + "default": "./helpers/createSuper.js" + }, + "./helpers/createSuper.js" + ], + "./helpers/esm/createSuper": "./helpers/esm/createSuper.js", + "./helpers/superPropBase": [ + { + "node": "./helpers/superPropBase.js", + "import": "./helpers/esm/superPropBase.js", + "default": "./helpers/superPropBase.js" + }, + "./helpers/superPropBase.js" + ], + "./helpers/esm/superPropBase": "./helpers/esm/superPropBase.js", + "./helpers/get": [ + { + "node": "./helpers/get.js", + "import": "./helpers/esm/get.js", + "default": "./helpers/get.js" + }, + "./helpers/get.js" + ], + "./helpers/esm/get": "./helpers/esm/get.js", + "./helpers/set": [ + { + "node": "./helpers/set.js", + "import": "./helpers/esm/set.js", + "default": "./helpers/set.js" + }, + "./helpers/set.js" + ], + "./helpers/esm/set": "./helpers/esm/set.js", + "./helpers/taggedTemplateLiteral": [ + { + "node": "./helpers/taggedTemplateLiteral.js", + "import": "./helpers/esm/taggedTemplateLiteral.js", + "default": "./helpers/taggedTemplateLiteral.js" + }, + "./helpers/taggedTemplateLiteral.js" + ], + "./helpers/esm/taggedTemplateLiteral": "./helpers/esm/taggedTemplateLiteral.js", + "./helpers/taggedTemplateLiteralLoose": [ + { + "node": "./helpers/taggedTemplateLiteralLoose.js", + "import": "./helpers/esm/taggedTemplateLiteralLoose.js", + "default": "./helpers/taggedTemplateLiteralLoose.js" + }, + "./helpers/taggedTemplateLiteralLoose.js" + ], + "./helpers/esm/taggedTemplateLiteralLoose": "./helpers/esm/taggedTemplateLiteralLoose.js", + "./helpers/readOnlyError": [ + { + "node": "./helpers/readOnlyError.js", + "import": "./helpers/esm/readOnlyError.js", + "default": "./helpers/readOnlyError.js" + }, + "./helpers/readOnlyError.js" + ], + "./helpers/esm/readOnlyError": "./helpers/esm/readOnlyError.js", + "./helpers/writeOnlyError": [ + { + "node": "./helpers/writeOnlyError.js", + "import": "./helpers/esm/writeOnlyError.js", + "default": "./helpers/writeOnlyError.js" + }, + "./helpers/writeOnlyError.js" + ], + "./helpers/esm/writeOnlyError": "./helpers/esm/writeOnlyError.js", + "./helpers/classNameTDZError": [ + { + "node": "./helpers/classNameTDZError.js", + "import": "./helpers/esm/classNameTDZError.js", + "default": "./helpers/classNameTDZError.js" + }, + "./helpers/classNameTDZError.js" + ], + "./helpers/esm/classNameTDZError": "./helpers/esm/classNameTDZError.js", + "./helpers/temporalUndefined": [ + { + "node": "./helpers/temporalUndefined.js", + "import": "./helpers/esm/temporalUndefined.js", + "default": "./helpers/temporalUndefined.js" + }, + "./helpers/temporalUndefined.js" + ], + "./helpers/esm/temporalUndefined": "./helpers/esm/temporalUndefined.js", + "./helpers/tdz": [ + { + "node": "./helpers/tdz.js", + "import": "./helpers/esm/tdz.js", + "default": "./helpers/tdz.js" + }, + "./helpers/tdz.js" + ], + "./helpers/esm/tdz": "./helpers/esm/tdz.js", + "./helpers/temporalRef": [ + { + "node": "./helpers/temporalRef.js", + "import": "./helpers/esm/temporalRef.js", + "default": "./helpers/temporalRef.js" + }, + "./helpers/temporalRef.js" + ], + "./helpers/esm/temporalRef": "./helpers/esm/temporalRef.js", + "./helpers/slicedToArray": [ + { + "node": "./helpers/slicedToArray.js", + "import": "./helpers/esm/slicedToArray.js", + "default": "./helpers/slicedToArray.js" + }, + "./helpers/slicedToArray.js" + ], + "./helpers/esm/slicedToArray": "./helpers/esm/slicedToArray.js", + "./helpers/slicedToArrayLoose": [ + { + "node": "./helpers/slicedToArrayLoose.js", + "import": "./helpers/esm/slicedToArrayLoose.js", + "default": "./helpers/slicedToArrayLoose.js" + }, + "./helpers/slicedToArrayLoose.js" + ], + "./helpers/esm/slicedToArrayLoose": "./helpers/esm/slicedToArrayLoose.js", + "./helpers/toArray": [ + { + "node": "./helpers/toArray.js", + "import": "./helpers/esm/toArray.js", + "default": "./helpers/toArray.js" + }, + "./helpers/toArray.js" + ], + "./helpers/esm/toArray": "./helpers/esm/toArray.js", + "./helpers/toConsumableArray": [ + { + "node": "./helpers/toConsumableArray.js", + "import": "./helpers/esm/toConsumableArray.js", + "default": "./helpers/toConsumableArray.js" + }, + "./helpers/toConsumableArray.js" + ], + "./helpers/esm/toConsumableArray": "./helpers/esm/toConsumableArray.js", + "./helpers/arrayWithoutHoles": [ + { + "node": "./helpers/arrayWithoutHoles.js", + "import": "./helpers/esm/arrayWithoutHoles.js", + "default": "./helpers/arrayWithoutHoles.js" + }, + "./helpers/arrayWithoutHoles.js" + ], + "./helpers/esm/arrayWithoutHoles": "./helpers/esm/arrayWithoutHoles.js", + "./helpers/arrayWithHoles": [ + { + "node": "./helpers/arrayWithHoles.js", + "import": "./helpers/esm/arrayWithHoles.js", + "default": "./helpers/arrayWithHoles.js" + }, + "./helpers/arrayWithHoles.js" + ], + "./helpers/esm/arrayWithHoles": "./helpers/esm/arrayWithHoles.js", + "./helpers/maybeArrayLike": [ + { + "node": "./helpers/maybeArrayLike.js", + "import": "./helpers/esm/maybeArrayLike.js", + "default": "./helpers/maybeArrayLike.js" + }, + "./helpers/maybeArrayLike.js" + ], + "./helpers/esm/maybeArrayLike": "./helpers/esm/maybeArrayLike.js", + "./helpers/iterableToArray": [ + { + "node": "./helpers/iterableToArray.js", + "import": "./helpers/esm/iterableToArray.js", + "default": "./helpers/iterableToArray.js" + }, + "./helpers/iterableToArray.js" + ], + "./helpers/esm/iterableToArray": "./helpers/esm/iterableToArray.js", + "./helpers/unsupportedIterableToArray": [ + { + "node": "./helpers/unsupportedIterableToArray.js", + "import": "./helpers/esm/unsupportedIterableToArray.js", + "default": "./helpers/unsupportedIterableToArray.js" + }, + "./helpers/unsupportedIterableToArray.js" + ], + "./helpers/esm/unsupportedIterableToArray": "./helpers/esm/unsupportedIterableToArray.js", + "./helpers/arrayLikeToArray": [ + { + "node": "./helpers/arrayLikeToArray.js", + "import": "./helpers/esm/arrayLikeToArray.js", + "default": "./helpers/arrayLikeToArray.js" + }, + "./helpers/arrayLikeToArray.js" + ], + "./helpers/esm/arrayLikeToArray": "./helpers/esm/arrayLikeToArray.js", + "./helpers/nonIterableSpread": [ + { + "node": "./helpers/nonIterableSpread.js", + "import": "./helpers/esm/nonIterableSpread.js", + "default": "./helpers/nonIterableSpread.js" + }, + "./helpers/nonIterableSpread.js" + ], + "./helpers/esm/nonIterableSpread": "./helpers/esm/nonIterableSpread.js", + "./helpers/nonIterableRest": [ + { + "node": "./helpers/nonIterableRest.js", + "import": "./helpers/esm/nonIterableRest.js", + "default": "./helpers/nonIterableRest.js" + }, + "./helpers/nonIterableRest.js" + ], + "./helpers/esm/nonIterableRest": "./helpers/esm/nonIterableRest.js", + "./helpers/createForOfIteratorHelper": [ + { + "node": "./helpers/createForOfIteratorHelper.js", + "import": "./helpers/esm/createForOfIteratorHelper.js", + "default": "./helpers/createForOfIteratorHelper.js" + }, + "./helpers/createForOfIteratorHelper.js" + ], + "./helpers/esm/createForOfIteratorHelper": "./helpers/esm/createForOfIteratorHelper.js", + "./helpers/createForOfIteratorHelperLoose": [ + { + "node": "./helpers/createForOfIteratorHelperLoose.js", + "import": "./helpers/esm/createForOfIteratorHelperLoose.js", + "default": "./helpers/createForOfIteratorHelperLoose.js" + }, + "./helpers/createForOfIteratorHelperLoose.js" + ], + "./helpers/esm/createForOfIteratorHelperLoose": "./helpers/esm/createForOfIteratorHelperLoose.js", + "./helpers/skipFirstGeneratorNext": [ + { + "node": "./helpers/skipFirstGeneratorNext.js", + "import": "./helpers/esm/skipFirstGeneratorNext.js", + "default": "./helpers/skipFirstGeneratorNext.js" + }, + "./helpers/skipFirstGeneratorNext.js" + ], + "./helpers/esm/skipFirstGeneratorNext": "./helpers/esm/skipFirstGeneratorNext.js", + "./helpers/toPrimitive": [ + { + "node": "./helpers/toPrimitive.js", + "import": "./helpers/esm/toPrimitive.js", + "default": "./helpers/toPrimitive.js" + }, + "./helpers/toPrimitive.js" + ], + "./helpers/esm/toPrimitive": "./helpers/esm/toPrimitive.js", + "./helpers/toPropertyKey": [ + { + "node": "./helpers/toPropertyKey.js", + "import": "./helpers/esm/toPropertyKey.js", + "default": "./helpers/toPropertyKey.js" + }, + "./helpers/toPropertyKey.js" + ], + "./helpers/esm/toPropertyKey": "./helpers/esm/toPropertyKey.js", + "./helpers/initializerWarningHelper": [ + { + "node": "./helpers/initializerWarningHelper.js", + "import": "./helpers/esm/initializerWarningHelper.js", + "default": "./helpers/initializerWarningHelper.js" + }, + "./helpers/initializerWarningHelper.js" + ], + "./helpers/esm/initializerWarningHelper": "./helpers/esm/initializerWarningHelper.js", + "./helpers/initializerDefineProperty": [ + { + "node": "./helpers/initializerDefineProperty.js", + "import": "./helpers/esm/initializerDefineProperty.js", + "default": "./helpers/initializerDefineProperty.js" + }, + "./helpers/initializerDefineProperty.js" + ], + "./helpers/esm/initializerDefineProperty": "./helpers/esm/initializerDefineProperty.js", + "./helpers/applyDecoratedDescriptor": [ + { + "node": "./helpers/applyDecoratedDescriptor.js", + "import": "./helpers/esm/applyDecoratedDescriptor.js", + "default": "./helpers/applyDecoratedDescriptor.js" + }, + "./helpers/applyDecoratedDescriptor.js" + ], + "./helpers/esm/applyDecoratedDescriptor": "./helpers/esm/applyDecoratedDescriptor.js", + "./helpers/classPrivateFieldLooseKey": [ + { + "node": "./helpers/classPrivateFieldLooseKey.js", + "import": "./helpers/esm/classPrivateFieldLooseKey.js", + "default": "./helpers/classPrivateFieldLooseKey.js" + }, + "./helpers/classPrivateFieldLooseKey.js" + ], + "./helpers/esm/classPrivateFieldLooseKey": "./helpers/esm/classPrivateFieldLooseKey.js", + "./helpers/classPrivateFieldLooseBase": [ + { + "node": "./helpers/classPrivateFieldLooseBase.js", + "import": "./helpers/esm/classPrivateFieldLooseBase.js", + "default": "./helpers/classPrivateFieldLooseBase.js" + }, + "./helpers/classPrivateFieldLooseBase.js" + ], + "./helpers/esm/classPrivateFieldLooseBase": "./helpers/esm/classPrivateFieldLooseBase.js", + "./helpers/classPrivateFieldGet": [ + { + "node": "./helpers/classPrivateFieldGet.js", + "import": "./helpers/esm/classPrivateFieldGet.js", + "default": "./helpers/classPrivateFieldGet.js" + }, + "./helpers/classPrivateFieldGet.js" + ], + "./helpers/esm/classPrivateFieldGet": "./helpers/esm/classPrivateFieldGet.js", + "./helpers/classPrivateFieldSet": [ + { + "node": "./helpers/classPrivateFieldSet.js", + "import": "./helpers/esm/classPrivateFieldSet.js", + "default": "./helpers/classPrivateFieldSet.js" + }, + "./helpers/classPrivateFieldSet.js" + ], + "./helpers/esm/classPrivateFieldSet": "./helpers/esm/classPrivateFieldSet.js", + "./helpers/classPrivateFieldDestructureSet": [ + { + "node": "./helpers/classPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classPrivateFieldDestructureSet.js", + "default": "./helpers/classPrivateFieldDestructureSet.js" + }, + "./helpers/classPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classPrivateFieldDestructureSet": "./helpers/esm/classPrivateFieldDestructureSet.js", + "./helpers/classExtractFieldDescriptor": [ + { + "node": "./helpers/classExtractFieldDescriptor.js", + "import": "./helpers/esm/classExtractFieldDescriptor.js", + "default": "./helpers/classExtractFieldDescriptor.js" + }, + "./helpers/classExtractFieldDescriptor.js" + ], + "./helpers/esm/classExtractFieldDescriptor": "./helpers/esm/classExtractFieldDescriptor.js", + "./helpers/classStaticPrivateFieldSpecGet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecGet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "default": "./helpers/classStaticPrivateFieldSpecGet.js" + }, + "./helpers/classStaticPrivateFieldSpecGet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecGet": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "./helpers/classStaticPrivateFieldSpecSet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecSet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "default": "./helpers/classStaticPrivateFieldSpecSet.js" + }, + "./helpers/classStaticPrivateFieldSpecSet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecSet": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "./helpers/classStaticPrivateMethodGet": [ + { + "node": "./helpers/classStaticPrivateMethodGet.js", + "import": "./helpers/esm/classStaticPrivateMethodGet.js", + "default": "./helpers/classStaticPrivateMethodGet.js" + }, + "./helpers/classStaticPrivateMethodGet.js" + ], + "./helpers/esm/classStaticPrivateMethodGet": "./helpers/esm/classStaticPrivateMethodGet.js", + "./helpers/classStaticPrivateMethodSet": [ + { + "node": "./helpers/classStaticPrivateMethodSet.js", + "import": "./helpers/esm/classStaticPrivateMethodSet.js", + "default": "./helpers/classStaticPrivateMethodSet.js" + }, + "./helpers/classStaticPrivateMethodSet.js" + ], + "./helpers/esm/classStaticPrivateMethodSet": "./helpers/esm/classStaticPrivateMethodSet.js", + "./helpers/classApplyDescriptorGet": [ + { + "node": "./helpers/classApplyDescriptorGet.js", + "import": "./helpers/esm/classApplyDescriptorGet.js", + "default": "./helpers/classApplyDescriptorGet.js" + }, + "./helpers/classApplyDescriptorGet.js" + ], + "./helpers/esm/classApplyDescriptorGet": "./helpers/esm/classApplyDescriptorGet.js", + "./helpers/classApplyDescriptorSet": [ + { + "node": "./helpers/classApplyDescriptorSet.js", + "import": "./helpers/esm/classApplyDescriptorSet.js", + "default": "./helpers/classApplyDescriptorSet.js" + }, + "./helpers/classApplyDescriptorSet.js" + ], + "./helpers/esm/classApplyDescriptorSet": "./helpers/esm/classApplyDescriptorSet.js", + "./helpers/classApplyDescriptorDestructureSet": [ + { + "node": "./helpers/classApplyDescriptorDestructureSet.js", + "import": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "default": "./helpers/classApplyDescriptorDestructureSet.js" + }, + "./helpers/classApplyDescriptorDestructureSet.js" + ], + "./helpers/esm/classApplyDescriptorDestructureSet": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "./helpers/classStaticPrivateFieldDestructureSet": [ + { + "node": "./helpers/classStaticPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "default": "./helpers/classStaticPrivateFieldDestructureSet.js" + }, + "./helpers/classStaticPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classStaticPrivateFieldDestructureSet": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "./helpers/classCheckPrivateStaticAccess": [ + { + "node": "./helpers/classCheckPrivateStaticAccess.js", + "import": "./helpers/esm/classCheckPrivateStaticAccess.js", + "default": "./helpers/classCheckPrivateStaticAccess.js" + }, + "./helpers/classCheckPrivateStaticAccess.js" + ], + "./helpers/esm/classCheckPrivateStaticAccess": "./helpers/esm/classCheckPrivateStaticAccess.js", + "./helpers/classCheckPrivateStaticFieldDescriptor": [ + { + "node": "./helpers/classCheckPrivateStaticFieldDescriptor.js", + "import": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "default": "./helpers/classCheckPrivateStaticFieldDescriptor.js" + }, + "./helpers/classCheckPrivateStaticFieldDescriptor.js" + ], + "./helpers/esm/classCheckPrivateStaticFieldDescriptor": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "./helpers/decorate": [ + { + "node": "./helpers/decorate.js", + "import": "./helpers/esm/decorate.js", + "default": "./helpers/decorate.js" + }, + "./helpers/decorate.js" + ], + "./helpers/esm/decorate": "./helpers/esm/decorate.js", + "./helpers/classPrivateMethodGet": [ + { + "node": "./helpers/classPrivateMethodGet.js", + "import": "./helpers/esm/classPrivateMethodGet.js", + "default": "./helpers/classPrivateMethodGet.js" + }, + "./helpers/classPrivateMethodGet.js" + ], + "./helpers/esm/classPrivateMethodGet": "./helpers/esm/classPrivateMethodGet.js", + "./helpers/checkPrivateRedeclaration": [ + { + "node": "./helpers/checkPrivateRedeclaration.js", + "import": "./helpers/esm/checkPrivateRedeclaration.js", + "default": "./helpers/checkPrivateRedeclaration.js" + }, + "./helpers/checkPrivateRedeclaration.js" + ], + "./helpers/esm/checkPrivateRedeclaration": "./helpers/esm/checkPrivateRedeclaration.js", + "./helpers/classPrivateFieldInitSpec": [ + { + "node": "./helpers/classPrivateFieldInitSpec.js", + "import": "./helpers/esm/classPrivateFieldInitSpec.js", + "default": "./helpers/classPrivateFieldInitSpec.js" + }, + "./helpers/classPrivateFieldInitSpec.js" + ], + "./helpers/esm/classPrivateFieldInitSpec": "./helpers/esm/classPrivateFieldInitSpec.js", + "./helpers/classPrivateMethodInitSpec": [ + { + "node": "./helpers/classPrivateMethodInitSpec.js", + "import": "./helpers/esm/classPrivateMethodInitSpec.js", + "default": "./helpers/classPrivateMethodInitSpec.js" + }, + "./helpers/classPrivateMethodInitSpec.js" + ], + "./helpers/esm/classPrivateMethodInitSpec": "./helpers/esm/classPrivateMethodInitSpec.js", + "./helpers/classPrivateMethodSet": [ + { + "node": "./helpers/classPrivateMethodSet.js", + "import": "./helpers/esm/classPrivateMethodSet.js", + "default": "./helpers/classPrivateMethodSet.js" + }, + "./helpers/classPrivateMethodSet.js" + ], + "./helpers/esm/classPrivateMethodSet": "./helpers/esm/classPrivateMethodSet.js", + "./helpers/identity": [ + { + "node": "./helpers/identity.js", + "import": "./helpers/esm/identity.js", + "default": "./helpers/identity.js" + }, + "./helpers/identity.js" + ], + "./helpers/esm/identity": "./helpers/esm/identity.js", + "./package": "./package.json", + "./package.json": "./package.json", + "./regenerator": "./regenerator/index.js", + "./regenerator/*.js": "./regenerator/*.js", + "./regenerator/": "./regenerator/" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/regenerator/index.js b/node_modules/@babel/runtime/regenerator/index.js new file mode 100644 index 0000000..5881357 --- /dev/null +++ b/node_modules/@babel/runtime/regenerator/index.js @@ -0,0 +1,15 @@ +// TODO(Babel 8): Remove this file. + +var runtime = require("../helpers/regeneratorRuntime")(); +module.exports = runtime; + +// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } +} diff --git a/node_modules/@colors/colors/LICENSE b/node_modules/@colors/colors/LICENSE new file mode 100644 index 0000000..6b86056 --- /dev/null +++ b/node_modules/@colors/colors/LICENSE @@ -0,0 +1,26 @@ +MIT License + +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + - Copyright (c) DABH (https://github.com/DABH) + +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. diff --git a/node_modules/@colors/colors/README.md b/node_modules/@colors/colors/README.md new file mode 100644 index 0000000..e2479ce --- /dev/null +++ b/node_modules/@colors/colors/README.md @@ -0,0 +1,219 @@ +# @colors/colors ("colors.js") +[![Build Status](https://github.com/DABH/colors.js/actions/workflows/ci.yml/badge.svg)](https://github.com/DABH/colors.js/actions/workflows/ci.yml) +[![version](https://img.shields.io/npm/v/@colors/colors.svg)](https://www.npmjs.org/package/@colors/colors) + +Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback. + +## get color and style in your node.js console + +![Demo](https://raw.githubusercontent.com/DABH/colors.js/master/screenshots/colors.png) + +## Installation + + npm install @colors/colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### bright text colors + + - brightRed + - brightGreen + - brightYellow + - brightBlue + - brightMagenta + - brightCyan + - brightWhite + +### background colors + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + - bgGray + - bgGrey + +### bright background colors + + - bgBrightRed + - bgBrightGreen + - bgBrightYellow + - bgBrightBlue + - bgBrightMagenta + - bgBrightCyan + - bgBrightWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `@colors/colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('@colors/colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red); // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('@colors/colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Enabling/Disabling Colors + +The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag: + +```bash +node myapp.js --no-color +node myapp.js --color=false + +node myapp.js --color +node myapp.js --color=true +node myapp.js --color=always + +FORCE_COLOR=1 node myapp.js +``` + +Or in code: + +```javascript +var colors = require('@colors/colors'); +colors.enable(); +colors.disable(); +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Beowulf'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Beowulf' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('@colors/colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('@colors/colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +``` + +### Combining Colors + +```javascript +var colors = require('@colors/colors'); + +colors.setTheme({ + custom: ['red', 'underline'] +}); + +console.log('test'.custom); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* diff --git a/node_modules/@colors/colors/examples/normal-usage.js b/node_modules/@colors/colors/examples/normal-usage.js new file mode 100644 index 0000000..a4bfe7b --- /dev/null +++ b/node_modules/@colors/colors/examples/normal-usage.js @@ -0,0 +1,83 @@ +var colors = require('../lib/index'); + +console.log('First some yellow text'.yellow); + +console.log('Underline that text'.yellow.underline); + +console.log('Make it bold and red'.red.bold); + +console.log(('Double Raindows All Day Long').rainbow); + +console.log('Drop the bass'.trap); + +console.log('DROP THE RAINBOW BASS'.trap.rainbow); + +// styles not widely supported +console.log('Chains are also cool.'.bold.italic.underline.red); + +// styles not widely supported +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + + ' styles! '.yellow.bold); +console.log('Zebras are so fun!'.zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log('This is ' + 'not'.strikethrough + ' fun.'); + +console.log('Background color attack!'.black.bgWhite); +console.log('Use random styles on everything!'.random); +console.log('America, Heck Yeah!'.america); + +// eslint-disable-next-line max-len +console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +try { + colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); +} catch (err) { + console.log(err); +} + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +// console.log("Don't summon".zalgo) + diff --git a/node_modules/@colors/colors/examples/safe-string.js b/node_modules/@colors/colors/examples/safe-string.js new file mode 100644 index 0000000..fc66474 --- /dev/null +++ b/node_modules/@colors/colors/examples/safe-string.js @@ -0,0 +1,80 @@ +var colors = require('../safe'); + +console.log(colors.yellow('First some yellow text')); + +console.log(colors.yellow.underline('Underline that text')); + +console.log(colors.red.bold('Make it bold and red')); + +console.log(colors.rainbow('Double Raindows All Day Long')); + +console.log(colors.trap('Drop the bass')); + +console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS'))); + +// styles not widely supported +console.log(colors.bold.italic.underline.red('Chains are also cool.')); + +// styles not widely supported +console.log(colors.green('So ') + colors.underline('are') + ' ' + + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); + +console.log(colors.zebra('Zebras are so fun!')); + +console.log('This is ' + colors.strikethrough('not') + ' fun.'); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')); +console.log(colors.america('America, Heck Yeah!')); + +// eslint-disable-next-line max-len +console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +// console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'blue', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs blue text +console.log(colors.input('this is an input')); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs grey text +console.log(colors.input('this is an input')); + +// console.log(colors.zalgo("Don't summon him")) + + diff --git a/node_modules/@colors/colors/index.d.ts b/node_modules/@colors/colors/index.d.ts new file mode 100644 index 0000000..df3f2e6 --- /dev/null +++ b/node_modules/@colors/colors/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for @colors/colors 1.4+ +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/DABH/colors.js + +export interface Color { + (text: string): string; + + strip: Color; + stripColors: Color; + + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + zalgo: Color; +} + +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export let enabled: boolean; + +export const strip: Color; +export const stripColors: Color; + +export const black: Color; +export const red: Color; +export const green: Color; +export const yellow: Color; +export const blue: Color; +export const magenta: Color; +export const cyan: Color; +export const white: Color; +export const gray: Color; +export const grey: Color; + +export const bgBlack: Color; +export const bgRed: Color; +export const bgGreen: Color; +export const bgYellow: Color; +export const bgBlue: Color; +export const bgMagenta: Color; +export const bgCyan: Color; +export const bgWhite: Color; + +export const reset: Color; +export const bold: Color; +export const dim: Color; +export const italic: Color; +export const underline: Color; +export const inverse: Color; +export const hidden: Color; +export const strikethrough: Color; + +export const rainbow: Color; +export const zebra: Color; +export const america: Color; +export const trap: Color; +export const random: Color; +export const zalgo: Color; + +declare global { + interface String { + strip: string; + stripColors: string; + + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + reset: string; + // @ts-ignore + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; + zalgo: string; + } +} diff --git a/node_modules/@colors/colors/package.json b/node_modules/@colors/colors/package.json new file mode 100644 index 0000000..cb87f20 --- /dev/null +++ b/node_modules/@colors/colors/package.json @@ -0,0 +1,45 @@ +{ + "name": "@colors/colors", + "description": "get colors in your node.js console", + "version": "1.5.0", + "author": "DABH", + "contributors": [ + { + "name": "DABH", + "url": "https://github.com/DABH" + } + ], + "homepage": "https://github.com/DABH/colors.js", + "bugs": "https://github.com/DABH/colors.js/issues", + "keywords": [ + "ansi", + "terminal", + "colors" + ], + "repository": { + "type": "git", + "url": "http://github.com/DABH/colors.js.git" + }, + "license": "MIT", + "scripts": { + "lint": "eslint . --fix", + "test": "export FORCE_COLOR=1 && node tests/basic-test.js && node tests/safe-test.js" + }, + "engines": { + "node": ">=0.1.90" + }, + "main": "lib/index.js", + "files": [ + "examples", + "lib", + "LICENSE", + "safe.js", + "themes", + "index.d.ts", + "safe.d.ts" + ], + "devDependencies": { + "eslint": "^5.2.0", + "eslint-config-google": "^0.11.0" + } +} diff --git a/node_modules/@colors/colors/safe.d.ts b/node_modules/@colors/colors/safe.d.ts new file mode 100644 index 0000000..2bafc27 --- /dev/null +++ b/node_modules/@colors/colors/safe.d.ts @@ -0,0 +1,48 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/Marak/colors.js + +export const enabled: boolean; +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export function strip(str: string): string; +export function stripColors(str: string): string; + +export function black(str: string): string; +export function red(str: string): string; +export function green(str: string): string; +export function yellow(str: string): string; +export function blue(str: string): string; +export function magenta(str: string): string; +export function cyan(str: string): string; +export function white(str: string): string; +export function gray(str: string): string; +export function grey(str: string): string; + +export function bgBlack(str: string): string; +export function bgRed(str: string): string; +export function bgGreen(str: string): string; +export function bgYellow(str: string): string; +export function bgBlue(str: string): string; +export function bgMagenta(str: string): string; +export function bgCyan(str: string): string; +export function bgWhite(str: string): string; + +export function reset(str: string): string; +export function bold(str: string): string; +export function dim(str: string): string; +export function italic(str: string): string; +export function underline(str: string): string; +export function inverse(str: string): string; +export function hidden(str: string): string; +export function strikethrough(str: string): string; + +export function rainbow(str: string): string; +export function zebra(str: string): string; +export function america(str: string): string; +export function trap(str: string): string; +export function random(str: string): string; +export function zalgo(str: string): string; diff --git a/node_modules/@colors/colors/safe.js b/node_modules/@colors/colors/safe.js new file mode 100644 index 0000000..a013d54 --- /dev/null +++ b/node_modules/@colors/colors/safe.js @@ -0,0 +1,10 @@ +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; diff --git a/node_modules/@colors/colors/themes/generic-logging.js b/node_modules/@colors/colors/themes/generic-logging.js new file mode 100644 index 0000000..63adfe4 --- /dev/null +++ b/node_modules/@colors/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}; diff --git a/node_modules/@githubnext/github-copilot-cli/README.md b/node_modules/@githubnext/github-copilot-cli/README.md new file mode 100644 index 0000000..c2b94a0 --- /dev/null +++ b/node_modules/@githubnext/github-copilot-cli/README.md @@ -0,0 +1,162 @@ +## GitHub Copilot CLI + +A CLI experience for letting GitHub Copilot help you on the command line. + +NOTE: GitHub Copilot CLI is in **technical preview**. +Expect rough corners and poorly supported platforms. +To get access to GitHub Copilot CLI, [sign up on the waitlist](https://githubnext.com/projects/copilot-cli/). + +GitHub Copilot CLI translates natural language into shell commands, with modes for different domains. +After installation, you can use the following three command: + +- `??`: Translate natural language to arbitrary shell commands +- `git?`: Translate natural language to Git commands +- `gh?`: Translate natural language to GitHub CLI commands + +GitHub Copilot CLI will also try to break down and explain piece by piece what the suggested command will do. + +To use GitHub Copilot CLI, you must have access to [GitHub Copilot](https://github.com/features/copilot/). + +## Supported platforms + +GitHub Copilot CLI should basically work broadly across platforms, terminals and shells, but has a bias towards zsh on Linux. +It may therefore suggest you commands that do not work on your platform or your terminal. +If this happens, consider using the `revise` option to tell GitHub Copilot CLI what platform you're on. + +The alias commands are only tested to work on zsh and bash. + +We appreciate any and all input on how well GitHub Copilot CLI works on your platform, and how we can improve it. + +## Installation and setup + +Install GitHub Copilot CLI globally on your machine using `npm`: + +```bash +$ npm install -g @githubnext/github-copilot-cli +``` + +This adds the command `github-copilot-cli` to your `PATH`. +To authenticate with GitHub, run the following command: + +```bash +$ github-copilot-cli auth +``` + +and follow the on-screen instructions. +Once authenticated, the token will be stored on your machine and used for future requests, so this command only rarely needs to be run. + +### Setup alias convenience commands + +You can run GitHub Copilot CLI directly using `github-copilot-cli`, but we recommend you install the `??`, `git?`, and `gh?` commands in your shell. +These are not only more convenient to type, but also [provide added features](#whats-the-point-of-the-eval-and-alias-stuff). +To install them, run the following command: + +```bash + eval "$(github-copilot-cli alias -- "$0")" +``` + +These will add the commands to your shell, but only for the current session. +To make them available in all future sessions, you should add the above command on a line by itself to the bottom of your `.zshrc` or `.bashrc` or equivalent. + +## Usage instructions and tips + + + +All three modes of GitHub Copilot CLI work in the same way: +you write a natural language query to declare what you want, and GitHub Copilot CLI will try to construct a command or sequence of commands to do it. +If you're happy with the suggested command, just ask GitHub Copilot CLI to run it for you. + +### Explanations + +GitHub Copilot CLI will also explain piece-by-piece what the suggested command does. +This is important when you're learning new commands or flags: the shell is very powerful, and you may inadvertently do irreversible changes you did not intend. +Always be sure you understand what a suggested command does before running it. +Like all AI systems, GitHub Copilot CLI is not perfect, and may make mistakes. + +### Revisions + +If the command is not quite what you wanted, you can revise your query and ask GitHub Copilot CLI to suggest a new command. +This workflow can be used for different purposes: + +- GitHub Copilot CLI misunderstood your initial query, and a revision can put it back on track, e.g. `only files in current folder`. + +- The suggestion applies to a different platform than yours. Use a revision to state your platform requirements, e.g. `on fish shell`. + +- Start with a simple query, and iteratively make it more complex, e.g. building a multi-pipe command or several statements, like in the video showns above. + This tends to work better than writing all the details in the first query. + +- GitHub Copilot CLI may suggest placeholder names in the initial suggestion. You can use revise to replace them by the actual names you want to use, e.g. `on branch feature/origami-swans`. + +### Gotchas in the shell + +Since you write your query directly in the shell, there's a number of gotchas to be aware of. + +Many symbols have a special meaning in the shell and will be interpreted _before_ they are handed to GitHub Copilot CLI. +The safest way is to avoid these symbols in queries altogether. +If you do particularly need them, most of them can be escaped by prefixing them with a backslash `\`, or by enclosing the entire query in single-quotes `' ... '`. + +For instance: + +- Quotes `'` or `"`, question marks `?`, or exclamation marks `!` in your query will usually cause a shell syntax error, or cause the shell to expect a second line of your query. + In the latter case, press Ctrl-C to cancel the current shell statement, and write your query again without the offending symbol. + +- Parentheses, braces and brackets `( ) [ ] { }` will likewise usually cause a shell syntax error, or cause the shell to expect a second line of your query. + +- Asterisks `*` will be expanded to match file and folder names. This may cause sensitive file name information to appear in the query. + +- A pipe `|` will be interpreted as the shell pipe and interpret anything after it as a separate command. This will almost surely fail since GitHub Copilot CLI is an interactive application. + +- Be careful never to prepend a shell variable name with `$`: this causes the shell to expand the variable before GitHub Copilot CLI sees it, potentially sending sensitive information in the query. + +### More example videos + +### `git?` + + + +### `gh?` + + + +## Privacy and telemetry + +When using GitHub Copilot CLI, we will form a query and send it to the GitHub Copilot AI. +We are also gathering telemetry about the usage of the app. + +We are very aware that the shell is a sensitive place with access to a lot of private information. +Rest assured that GitHub Copilot CLI sends only a minimal amount of information from your shell in its query and in gathered telemetry. + +### What we never gather + +We are **never** harvesting and sending any of the following: + +- File and folder names you did not write in the query. +- Contents of any files on your system. +- Git repo, branch or status information +- The value of any environment variables set in your shell. +- The command history of your shell. +- Any shell command output, also not for the command you ask GitHub Copilot CLI to run. + +## What's the point of the `eval` and alias stuff? + +You may wonder about the somewhat round-about installation instructions for the convenience commands `??`, `git?`, and `gh?`. + +The technical reason that these commands must be installed using `eval` is that they are not executables themselves, but rather "shell functions" that wrap `github-copilot-cli`. +This enables the commands to more tightly integrate with the current shell session, and provides two key features that you do not get if you run `github-copilot-cli` directly: + +1. When you accept a suggested command, this gets run in the current shell session. + This means your commands will use the same shell state - such as environment variables - as you would get by typing the command yourself. + This sidesteps many potential points of confusion. + In fact, when you do run `github-copilot-cli` directly, we wish to avoid exactly this confusion and therefore simply print the command and ask you to copy/paste it into your shell yourself, rather than opening a subshell. + +1. When you accept a suggested command, we not only run it but also add it to your shell's command history. + This means that if you wish to run it again or edit it, you can just use up-arrow or Ctrl-R to recall it. + +## Inspiration + +[Codex CLI](https://github.com/microsoft/Codex-CLI) has a mode similar to the basic functionality of `??`. +It has other features as well that we don't yet support in GitHub Copilot CLI. + +``` + +``` diff --git a/node_modules/@githubnext/github-copilot-cli/cli.js b/node_modules/@githubnext/github-copilot-cli/cli.js new file mode 100755 index 0000000..3074be2 --- /dev/null +++ b/node_modules/@githubnext/github-copilot-cli/cli.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require("./dist/index.js"); diff --git a/node_modules/@githubnext/github-copilot-cli/package.json b/node_modules/@githubnext/github-copilot-cli/package.json new file mode 100644 index 0000000..965082e --- /dev/null +++ b/node_modules/@githubnext/github-copilot-cli/package.json @@ -0,0 +1,57 @@ +{ + "name": "@githubnext/github-copilot-cli", + "version": "0.1.21", + "description": "A CLI experience for letting GitHub Copilot help you on the command line.", + "author": "@githubnext", + "bin": { + "github-copilot-cli": "cli.js" + }, + "files": [ + "dist", + "cli.js" + ], + "scripts": { + "dev": "genversion --es6 lib/version.js && esbuild --watch --sourcemap=inline --bundle --platform=node --outfile=dist/index.js src/index.ts", + "build": "genversion --es6 lib/version.js && esbuild --minify --bundle --platform=node --outfile=dist/index.js src/index.ts", + "prepublish": "yarn build" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "applicationinsights": "^2.3.6", + "axios": "^1.1.3", + "chalk": "^5.1.0", + "cli-highlight": "^2.1.11", + "commander": "^9.4.1", + "get-stream": "^6.0.1", + "immer": "^9.0.16", + "ink": "^3.2.0", + "ink-divider": "^3.0.0", + "ink-select-input": "^4.2.1", + "ink-spinner": "^4.0.3", + "ink-text-input": "^4.0.3", + "inquirer": "^9.1.4", + "marked": "^4.2.12", + "marked-terminal": "^5.1.1", + "ora": "^6.1.2", + "radash": "^9.1.0", + "react": "17", + "react-dom": "17", + "react-query": "^3.39.2", + "tiny-invariant": "^1.3.1", + "ts-dedent": "^2.2.0", + "use-zustand": "^0.0.1", + "uuid": "^9.0.0", + "zustand": "^4.1.4" + }, + "devDependencies": { + "@types/inquirer": "^9.0.2", + "@types/node": "^18.8.3", + "@types/react": "^18.0.25", + "@types/uuid": "^8.3.4", + "esbuild": "^0.15.10", + "genversion": "^3.1.1", + "typescript": "^4.8.4" + } +} diff --git a/node_modules/@microsoft/applicationinsights-web-snippet/LICENSE b/node_modules/@microsoft/applicationinsights-web-snippet/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@microsoft/applicationinsights-web-snippet/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + 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 diff --git a/node_modules/@microsoft/applicationinsights-web-snippet/README.md b/node_modules/@microsoft/applicationinsights-web-snippet/README.md new file mode 100644 index 0000000..ecbdee0 --- /dev/null +++ b/node_modules/@microsoft/applicationinsights-web-snippet/README.md @@ -0,0 +1,54 @@ +# Microsoft Application Insights JavaScript SDK - Web Snippet + +[![Build Status](https://travis-ci.org/microsoft/ApplicationInsights-JS.svg?branch=master)](https://travis-ci.org/microsoft/ApplicationInsights-JS) +[![npm version](https://badge.fury.io/js/%40microsoft%2Fapplicationinsights-web-snippet.svg)](https://badge.fury.io/js/%40microsoft%2Fapplicationinsights-web-snippet) + +Web Snippet for the Application Insights Javascript SDK + +This project exists to publish latest Application Insights Javascript Web Snippet. + +## Basic Usage + +Add the Application Insights Web Snippet to your app's dependencies and package.json. +``` +npm i @microsoft/applicationinsights-web-snippet +``` + + +Import web snippet from the package. +``` +import { webSnippet } from "@microsoft/applicationinsights-web-snippet"; +``` + + +Replace "INSTRUMENTATION_KEY" with valid Instrumentation Key. +``` +webSnippet.replace("INSTRUMENTATION_KEY", your_valid_ikey); +``` + +More details on web snippet, see [Web Snippet](https://github.com/microsoft/ApplicationInsights-JS#snippet-setup-ignore-if-using-npm-setup). + +## Build +``` +npm install -g grunt-cli +npm install +npm run build --silent +``` + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## License + +[MIT](LICENSE) \ No newline at end of file diff --git a/node_modules/@microsoft/applicationinsights-web-snippet/dest/applicationinsights-web-snippet.ts b/node_modules/@microsoft/applicationinsights-web-snippet/dest/applicationinsights-web-snippet.ts new file mode 100644 index 0000000..c2dbf92 --- /dev/null +++ b/node_modules/@microsoft/applicationinsights-web-snippet/dest/applicationinsights-web-snippet.ts @@ -0,0 +1 @@ +export const webSnippet = "!function(T,l,y){var S=T.location,k=\"script\",D=\"instrumentationKey\",C=\"ingestionendpoint\",I=\"disableExceptionTracking\",E=\"ai.device.\",b=\"toLowerCase\",w=\"crossOrigin\",N=\"POST\",e=\"appInsightsSDK\",t=y.name||\"appInsights\";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:\"5\",version:2,config:d};function v(e,t){var n={},a=\"Browser\";return n[E+\"id\"]=a[b](),n[E+\"type\"]=a,n[\"ai.operation.name\"]=S&&S.pathname||\"_unknown_\",n[\"ai.internal.sdkVersion\"]=\"javascript:snippet_\"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=\"\"+e;return 1===t.length&&(t=\"0\"+t),t}return e.getUTCFullYear()+\"-\"+t(1+e.getUTCMonth())+\"-\"+t(e.getUTCDate())+\"T\"+t(e.getUTCHours())+\":\"+t(e.getUTCMinutes())+\":\"+t(e.getUTCSeconds())+\".\"+((e.getUTCMilliseconds()/1e3).toFixed(3)+\"\").slice(2,5)+\"Z\"}(),iKey:e,name:\"Microsoft.ApplicationInsights.\"+e.replace(/-/g,\"\")+\".\"+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(\";\"),a=0;a + +API Reference +  •   +Documentation +
+ + NPM Release + +
+

+ +This package provides everything needed to interact with the OpenTelemetry API, including all TypeScript interfaces, enums, and no-op implementations. It is intended for use both on the server and in the browser. + +The methods in this package perform no operations by default. This means they can be safely called by a library or end-user application whether there is an SDK registered or not. In order to generate and export telemetry data, you will also need an SDK such as the [OpenTelemetry JS SDK][opentelemetry-js]. + +## Tracing Quick Start + +### You Will Need + +- An application you wish to instrument +- [OpenTelemetry JS SDK][opentelemetry-js] +- Node.js >=8.5.0 (14+ is preferred) or an ECMAScript 5+ compatible browser + +**Note:** ECMAScript 5+ compatibility is for this package only. Please refer to the documentation for the SDK you are using to determine its minimum ECMAScript version. + +**Note for library authors:** Only your end users will need an OpenTelemetry SDK. If you wish to support OpenTelemetry in your library, you only need to use the OpenTelemetry API. For more information, please read the [tracing documentation][docs-tracing]. + +### Install Dependencies + +```sh +npm install @opentelemetry/api @opentelemetry/sdk-trace-base +``` + +### Trace Your Application + +In order to get started with tracing, you will need to first register an SDK. The SDK you are using may provide a convenience method which calls the registration methods for you, but if you would like to call them directly they are documented here: [sdk registration methods][docs-sdk-registration]. + +Once you have registered an SDK, you can start and end spans. A simple example of basic SDK registration and tracing a simple operation is below. The example should export spans to the console once per second. For more information, see the [tracing documentation][docs-tracing]. + +```javascript +const { trace } = require("@opentelemetry/api"); +const { BasicTracerProvider, ConsoleSpanExporter, SimpleSpanProcessor } = require("@opentelemetry/sdk-trace-base"); + +// Create and register an SDK +const provider = new BasicTracerProvider(); +provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +trace.setGlobalTracerProvider(provider); + +// Acquire a tracer from the global tracer provider which will be used to trace the application +const name = 'my-application-name'; +const version = '0.1.0'; +const tracer = trace.getTracer(name, version); + +// Trace your application by creating spans +async function operation() { + const span = tracer.startSpan("do operation"); + + // mock some work by sleeping 1 second + await new Promise((resolve, reject) => { + setTimeout(resolve, 1000); + }) + + span.end(); +} + +async function main() { + while (true) { + await operation(); + } +} + +main(); +``` + +## Version Compatibility + +Because the npm installer and node module resolution algorithm could potentially allow two or more copies of any given package to exist within the same `node_modules` structure, the OpenTelemetry API takes advantage of a variable on the `global` object to store the global API. When an API method in the API package is called, it checks if this `global` API exists and proxies calls to it if and only if it is a compatible API version. This means if a package has a dependency on an OpenTelemetry API version which is not compatible with the API used by the end user, the package will receive a no-op implementation of the API. + +## Upgrade Guidelines + +### 0.21.0 to 1.0.0 + +No breaking changes + +### 0.20.0 to 0.21.0 + +- [#78](https://github.com/open-telemetry/opentelemetry-js-api/issues/78) `api.context.bind` arguments reversed and `context` is now a required argument. +- [#46](https://github.com/open-telemetry/opentelemetry-js-api/issues/46) Noop classes and singletons are no longer exported. To create a noop span it is recommended to use `api.trace.wrapSpanContext` with `INVALID_SPAN_CONTEXT` instead of using the `NOOP_TRACER`. + +### 1.0.0-rc.3 to 0.20.0 + +- Removing `TimedEvent` which was not part of spec +- `HttpBaggage` renamed to `HttpBaggagePropagator` +- [#45](https://github.com/open-telemetry/opentelemetry-js-api/pull/45) `Span#context` renamed to `Span#spanContext` +- [#47](https://github.com/open-telemetry/opentelemetry-js-api/pull/47) `getSpan`/`setSpan`/`getSpanContext`/`setSpanContext` moved to `trace` namespace +- [#55](https://github.com/open-telemetry/opentelemetry-js-api/pull/55) `getBaggage`/`setBaggage`/`createBaggage` moved to `propagation` namespace + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[opentelemetry-js]: https://github.com/open-telemetry/opentelemetry-js + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/api/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[docs-tracing]: https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/tracing.md +[docs-sdk-registration]: https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/sdk-registration.md diff --git a/node_modules/@opentelemetry/api/package.json b/node_modules/@opentelemetry/api/package.json new file mode 100644 index 0000000..bf2a466 --- /dev/null +++ b/node_modules/@opentelemetry/api/package.json @@ -0,0 +1,91 @@ +{ + "name": "@opentelemetry/api", + "version": "1.4.1", + "description": "Public API for OpenTelemetry", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "types": "build/src/index.d.ts", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/esm/platform/index.js": "./build/esm/platform/browser/index.js", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "codecov:webworker": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../", + "precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "docs": "typedoc", + "docs:deploy": "gh-pages --dist docs/out", + "docs:test": "linkinator docs/out --silent && linkinator docs/*.md *.md --markdown --silent", + "lint:fix": "eslint . --ext .ts --fix", + "lint": "eslint . --ext .ts", + "test:browser": "nyc karma start --single-run", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "test:webworker": "nyc karma start karma.worker.js --single-run", + "cycle-check": "dpdm --exit-code circular:1 src/index.ts", + "version": "node ../scripts/version-update.js", + "prewatch": "npm run precompile", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "peer-api-check": "node ../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "browser", + "tracing", + "profiling", + "stats", + "monitoring" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "10.0.0", + "@types/node": "18.6.5", + "@types/sinon": "10.0.13", + "@types/webpack": "4.41.26", + "@types/webpack-env": "1.16.3", + "codecov": "3.8.3", + "dpdm": "3.10.0", + "istanbul-instrumenter-loader": "3.0.1", + "karma": "6.3.16", + "karma-chrome-launcher": "3.1.0", + "karma-coverage-istanbul-reporter": "3.0.3", + "karma-mocha": "2.0.1", + "karma-mocha-webworker": "1.3.0", + "karma-spec-reporter": "0.0.32", + "karma-webpack": "4.0.2", + "memfs": "3.4.9", + "mocha": "10.0.0", + "nyc": "15.1.0", + "sinon": "15.0.0", + "ts-loader": "8.4.0", + "ts-mocha": "10.0.0", + "typescript": "4.4.4", + "unionfs": "4.4.0", + "webpack": "4.46.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/api", + "sideEffects": false, + "gitHead": "56e6b1bb890f844b8963a146780d0b9cfa8abd0d" +} diff --git a/node_modules/@opentelemetry/core/LICENSE b/node_modules/@opentelemetry/core/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/@opentelemetry/core/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@opentelemetry/core/README.md b/node_modules/@opentelemetry/core/README.md new file mode 100644 index 0000000..1d543dc --- /dev/null +++ b/node_modules/@opentelemetry/core/README.md @@ -0,0 +1,73 @@ +# OpenTelemetry Core + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +This package provides default implementations of the OpenTelemetry API for trace and metrics. It's intended for use both on the server and in the browser. + +## Built-in Implementations + +- [OpenTelemetry Core](#opentelemetry-core) + - [Built-in Implementations](#built-in-implementations) + - [Built-in Propagators](#built-in-propagators) + - [W3CTraceContextPropagator Propagator](#w3ctracecontextpropagator-propagator) + - [Composite Propagator](#composite-propagator) + - [Baggage Propagator](#baggage-propagator) + - [Useful links](#useful-links) + - [License](#license) + +### Built-in Propagators + +#### W3CTraceContextPropagator Propagator + +OpenTelemetry provides a text-based approach to propagate context to remote services using the [W3C Trace Context](https://www.w3.org/TR/trace-context/) HTTP headers. + +```js +const api = require("@opentelemetry/api"); +const { W3CTraceContextPropagator } = require("@opentelemetry/core"); + +/* Set Global Propagator */ +api.propagation.setGlobalPropagator(new W3CTraceContextPropagator()); +``` + +#### Composite Propagator + +Combines multiple propagators into a single propagator. + +> This is used as a default Propagator + +```js +const api = require("@opentelemetry/api"); +const { CompositePropagator } = require("@opentelemetry/core"); + +/* Set Global Propagator */ +api.propagation.setGlobalPropagator(new CompositePropagator()); +``` + +#### Baggage Propagator + +Provides a text-based approach to propagate [baggage](https://w3c.github.io/baggage/) to remote services using the [OpenTelemetry Baggage Propagation](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/baggage/api.md#baggage-propagation) HTTP headers. + +```js +const api = require("@opentelemetry/api"); +const { W3CBaggagePropagator } = require("@opentelemetry/core"); + +/* Set Global Propagator */ +api.propagation.setGlobalPropagator(new W3CBaggagePropagator()); +``` + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[npm-url]: https://www.npmjs.com/package/@opentelemetry/core +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fcore.svg diff --git a/node_modules/@opentelemetry/core/package.json b/node_modules/@opentelemetry/core/package.json new file mode 100644 index 0000000..a8dbe76 --- /dev/null +++ b/node_modules/@opentelemetry/core/package.json @@ -0,0 +1,99 @@ +{ + "name": "@opentelemetry/core", + "version": "1.10.0", + "description": "OpenTelemetry Core provides constants and utilities shared by all OpenTelemetry SDK packages.", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/esm/platform/index.js": "./build/esm/platform/browser/index.js", + "./build/esnext/platform/index.js": "./build/esnext/platform/browser/index.js", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "prepublishOnly": "npm run compile", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "test": "nyc ts-mocha -p tsconfig.json test/**/*.test.ts --exclude 'test/platform/browser/**/*.ts'", + "test:browser": "nyc karma start --single-run", + "tdd": "npm run tdd:node", + "tdd:node": "npm run test -- --watch-extensions ts --watch", + "tdd:browser": "karma start", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "version": "node ../../scripts/version-update.js", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies", + "prewatch": "npm run precompile", + "peer-api-check": "node ../../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "browser", + "tracing", + "profiling", + "metrics", + "stats" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0", + "@types/mocha": "10.0.0", + "@types/node": "18.6.5", + "@types/sinon": "10.0.13", + "@types/webpack-env": "1.16.3", + "codecov": "3.8.3", + "istanbul-instrumenter-loader": "3.0.1", + "karma": "6.3.16", + "karma-chrome-launcher": "3.1.0", + "karma-coverage-istanbul-reporter": "3.0.3", + "karma-mocha": "2.0.1", + "karma-spec-reporter": "0.0.32", + "karma-webpack": "4.0.2", + "lerna": "6.0.3", + "mocha": "10.0.0", + "nyc": "15.1.0", + "rimraf": "4.1.2", + "sinon": "15.0.0", + "ts-loader": "8.4.0", + "ts-mocha": "10.0.0", + "typescript": "4.4.4", + "webpack": "4.46.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + }, + "dependencies": { + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-core", + "sideEffects": false, + "gitHead": "56e6b1bb890f844b8963a146780d0b9cfa8abd0d" +} diff --git a/node_modules/@opentelemetry/resources/LICENSE b/node_modules/@opentelemetry/resources/LICENSE new file mode 100644 index 0000000..6b91a29 --- /dev/null +++ b/node_modules/@opentelemetry/resources/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2020] OpenTelemetry Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@opentelemetry/resources/README.md b/node_modules/@opentelemetry/resources/README.md new file mode 100644 index 0000000..8b379ec --- /dev/null +++ b/node_modules/@opentelemetry/resources/README.md @@ -0,0 +1,49 @@ +# OpenTelemetry Resources Util + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +The OpenTelemetry Resource is an immutable representation of the entity producing telemetry. For example, a process producing telemetry that is running in a container on Kubernetes has a Pod name, it is in a namespace and possibly is part of a Deployment which also has a name. All three of these attributes can be included in the `Resource`. + +[This document][resource-semantic_conventions] defines standard attributes for resources which are accessible via [`@opentelemetry/semantic-conventions`](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-semantic-conventions). + +## Installation + +```bash +npm install --save @opentelemetry/resources +``` + +## Usage + +```typescript +import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'; +import { Resource } from '@opentelemetry/resources'; + +const resource = new Resource({ + [SemanticResourceAttributes.SERVICE_NAME]: 'api-service', +}); + +const anotherResource = new Resource({ + 'service.version': '2.0.0', + 'service.group': 'instrumentation-group' +}); +const mergedResource = resource.merge(anotherResource); +``` + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[npm-url]: https://www.npmjs.com/package/@opentelemetry/resources +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fresources.svg + +[resource-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/resource/semantic_conventions diff --git a/node_modules/@opentelemetry/resources/package.json b/node_modules/@opentelemetry/resources/package.json new file mode 100644 index 0000000..85986f4 --- /dev/null +++ b/node_modules/@opentelemetry/resources/package.json @@ -0,0 +1,99 @@ +{ + "name": "@opentelemetry/resources", + "version": "1.10.0", + "description": "OpenTelemetry SDK resources", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/esm/platform/index.js": "./build/esm/platform/browser/index.js", + "./build/esnext/platform/index.js": "./build/esnext/platform/browser/index.js", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "prepublishOnly": "npm run compile", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "codecov:webworker": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "test:browser": "nyc karma start --single-run", + "test:webworker": "nyc karma start karma.worker.js --single-run", + "tdd": "npm run test -- --watch-extensions ts --watch", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "version": "node ../../scripts/version-update.js", + "precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies", + "prewatch": "npm run precompile", + "peer-api-check": "node ../../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "resources", + "stats", + "profiling" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0", + "@opentelemetry/resources_1.9.0": "npm:@opentelemetry/resources@1.9.0", + "@types/mocha": "10.0.0", + "@types/node": "18.6.5", + "@types/sinon": "10.0.13", + "@types/webpack-env": "1.16.3", + "codecov": "3.8.3", + "karma": "6.3.16", + "karma-chrome-launcher": "3.1.0", + "karma-coverage-istanbul-reporter": "3.0.3", + "karma-mocha": "2.0.1", + "karma-mocha-webworker": "1.3.0", + "karma-spec-reporter": "0.0.32", + "karma-webpack": "4.0.2", + "mocha": "10.0.0", + "nock": "13.0.11", + "nyc": "15.1.0", + "rimraf": "4.1.2", + "sinon": "15.0.0", + "ts-mocha": "10.0.0", + "typescript": "4.4.4", + "webpack": "4.46.0", + "webpack-cli": "4.9.1", + "webpack-merge": "5.8.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + }, + "dependencies": { + "@opentelemetry/core": "1.10.0", + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources", + "sideEffects": false, + "gitHead": "56e6b1bb890f844b8963a146780d0b9cfa8abd0d" +} diff --git a/node_modules/@opentelemetry/sdk-trace-base/LICENSE b/node_modules/@opentelemetry/sdk-trace-base/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/@opentelemetry/sdk-trace-base/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@opentelemetry/sdk-trace-base/README.md b/node_modules/@opentelemetry/sdk-trace-base/README.md new file mode 100644 index 0000000..6d7b655 --- /dev/null +++ b/node_modules/@opentelemetry/sdk-trace-base/README.md @@ -0,0 +1,178 @@ +# OpenTelemetry Tracing SDK + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +The `tracing` module contains the foundation for all tracing SDKs of [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js). + +Used standalone, this module provides methods for manual instrumentation of code, offering full control over span creation for client-side JavaScript (browser) and Node.js. + +It does **not** provide automated instrumentation of known libraries, context propagation for asynchronous invocations or distributed-context out-of-the-box. + +For automated instrumentation for Node.js, please see +[@opentelemetry/sdk-trace-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node). + +## Installation + +```bash +npm install --save @opentelemetry/api +npm install --save @opentelemetry/sdk-trace-base +``` + +## Usage + +```js +const opentelemetry = require('@opentelemetry/api'); +const { BasicTracerProvider } = require('@opentelemetry/sdk-trace-base'); + +// To start a trace, you first need to initialize the Tracer provider. +// NOTE: The default OpenTelemetry tracer provider does not record any tracing information. +// Registering a working tracer provider allows the API methods to record traces. +new BasicTracerProvider().register(); + +// To create a span in a trace, we used the global singleton tracer to start a new span. +const span = opentelemetry.trace.getTracer('default').startSpan('foo'); + +// Set a span attribute +span.setAttribute('key', 'value'); + +// We must end the spans so they become available for exporting. +span.end(); +``` + +## Config + +Tracing configuration is a merge of user supplied configuration with both the default +configuration as specified in [config.ts](./src/config.ts) and an +environmentally configurable sampling (via `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`). + +## Built-in Samplers + +Sampler is used to make decisions on `Span` sampling. + +### AlwaysOn Sampler + +Samples every trace regardless of upstream sampling decisions. + +> This is used as a default Sampler + +```js +const { + AlwaysOnSampler, + BasicTracerProvider, +} = require("@opentelemetry/sdk-trace-base"); + +const tracerProvider = new BasicTracerProvider({ + sampler: new AlwaysOnSampler() +}); +``` + +### AlwaysOff Sampler + +Doesn't sample any trace, regardless of upstream sampling decisions. + +```js +const { + AlwaysOffSampler, + BasicTracerProvider, +} = require("@opentelemetry/sdk-trace-base"); + +const tracerProvider = new BasicTracerProvider({ + sampler: new AlwaysOffSampler() +}); +``` + +### TraceIdRatioBased Sampler + +Samples some percentage of traces, calculated deterministically using the trace ID. +Any trace that would be sampled at a given percentage will also be sampled at any higher percentage. + +The `TraceIDRatioSampler` may be used with the `ParentBasedSampler` to respect the sampled flag of an incoming trace. + +```js +const { + BasicTracerProvider, + TraceIdRatioBasedSampler, +} = require("@opentelemetry/sdk-trace-base"); + +const tracerProvider = new BasicTracerProvider({ + // See details of ParentBasedSampler below + sampler: new ParentBasedSampler({ + // Trace ID Ratio Sampler accepts a positional argument + // which represents the percentage of traces which should + // be sampled. + root: new TraceIdRatioBasedSampler(0.5) + }); +}); +``` + +### ParentBased Sampler + +- This is a composite sampler. `ParentBased` helps distinguished between the +following cases: + - No parent (root span). + - Remote parent with `sampled` flag `true` + - Remote parent with `sampled` flag `false` + - Local parent with `sampled` flag `true` + - Local parent with `sampled` flag `false` + +Required parameters: + +- `root(Sampler)` - Sampler called for spans with no parent (root spans) + +Optional parameters: + +- `remoteParentSampled(Sampler)` (default: `AlwaysOn`) +- `remoteParentNotSampled(Sampler)` (default: `AlwaysOff`) +- `localParentSampled(Sampler)` (default: `AlwaysOn`) +- `localParentNotSampled(Sampler)` (default: `AlwaysOff`) + +|Parent| parent.isRemote() | parent.isSampled()| Invoke sampler| +|--|--|--|--| +|absent| n/a | n/a |`root()`| +|present|true|true|`remoteParentSampled()`| +|present|true|false|`remoteParentNotSampled()`| +|present|false|true|`localParentSampled()`| +|present|false|false|`localParentNotSampled()`| + +```js +const { + AlwaysOffSampler, + BasicTracerProvider, + ParentBasedSampler, + TraceIdRatioBasedSampler, +} = require("@opentelemetry/sdk-trace-base"); + +const tracerProvider = new BasicTracerProvider({ + sampler: new ParentBasedSampler({ + // By default, the ParentBasedSampler will respect the parent span's sampling + // decision. This is configurable by providing a different sampler to use + // based on the situation. See configuration details above. + // + // This will delegate the sampling decision of all root traces (no parent) + // to the TraceIdRatioBasedSampler. + // See details of TraceIdRatioBasedSampler above. + root: new TraceIdRatioBasedSampler(0.5) + }) +}); +``` + +## Example + +See [examples/basic-tracer-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/examples/basic-tracer-node) for an end-to-end example, including exporting created spans. + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[npm-url]: https://www.npmjs.com/package/@opentelemetry/sdk-trace-base +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsdk-trace-base.svg diff --git a/node_modules/@opentelemetry/sdk-trace-base/package.json b/node_modules/@opentelemetry/sdk-trace-base/package.json new file mode 100644 index 0000000..5d0012b --- /dev/null +++ b/node_modules/@opentelemetry/sdk-trace-base/package.json @@ -0,0 +1,102 @@ +{ + "name": "@opentelemetry/sdk-trace-base", + "version": "1.10.0", + "description": "OpenTelemetry Tracing", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/esm/platform/index.js": "./build/esm/platform/browser/index.js", + "./build/esnext/platform/index.js": "./build/esnext/platform/browser/index.js", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "prepublishOnly": "npm run compile", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts' --exclude 'test/browser/**/*.ts'", + "test:browser": "nyc karma start --single-run", + "test:webworker": "nyc karma start karma.worker.js --single-run", + "tdd": "npm run tdd:node", + "tdd:node": "npm run test -- --watch-extensions ts --watch", + "tdd:browser": "karma start", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "codecov:webworker": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "version": "node ../../scripts/version-update.js", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies", + "prewatch": "npm run precompile", + "peer-api-check": "node ../../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "tracing", + "profiling", + "metrics", + "stats" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0", + "@opentelemetry/resources_1.9.0": "npm:@opentelemetry/resources@1.9.0", + "@types/mocha": "10.0.0", + "@types/node": "18.6.5", + "@types/sinon": "10.0.13", + "@types/webpack-env": "1.16.3", + "codecov": "3.8.3", + "istanbul-instrumenter-loader": "3.0.1", + "karma": "6.3.16", + "karma-chrome-launcher": "3.1.0", + "karma-coverage-istanbul-reporter": "3.0.3", + "karma-mocha": "2.0.1", + "karma-mocha-webworker": "1.3.0", + "karma-spec-reporter": "0.0.32", + "karma-webpack": "4.0.2", + "mocha": "10.0.0", + "nyc": "15.1.0", + "rimraf": "4.1.2", + "sinon": "15.0.0", + "ts-loader": "8.4.0", + "ts-mocha": "10.0.0", + "typescript": "4.4.4", + "webpack": "4.46.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.5.0" + }, + "dependencies": { + "@opentelemetry/core": "1.10.0", + "@opentelemetry/resources": "1.10.0", + "@opentelemetry/semantic-conventions": "1.10.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-base", + "sideEffects": false, + "gitHead": "56e6b1bb890f844b8963a146780d0b9cfa8abd0d" +} diff --git a/node_modules/@opentelemetry/semantic-conventions/LICENSE b/node_modules/@opentelemetry/semantic-conventions/LICENSE new file mode 100644 index 0000000..b0e74c7 --- /dev/null +++ b/node_modules/@opentelemetry/semantic-conventions/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2020] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@opentelemetry/semantic-conventions/README.md b/node_modules/@opentelemetry/semantic-conventions/README.md new file mode 100644 index 0000000..9974e91 --- /dev/null +++ b/node_modules/@opentelemetry/semantic-conventions/README.md @@ -0,0 +1,41 @@ +# OpenTelemetry Semantic Conventions + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +Semantic Convention constants for use with the OpenTelemetry SDK/APIs. [This document][trace-semantic_conventions] defines standard attributes for traces. + +## Installation + +```bash +npm install --save @opentelemetry/semantic-conventions +``` + +## Usage + +```ts +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; + +const span = tracer.startSpan().startSpan(spanName, spanOptions) + .setAttributes({ + [SemanticAttributes.NET_PEER_NAME]: 'localhost', + }); +``` + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[npm-url]: https://www.npmjs.com/package/@opentelemetry/semantic-conventions +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsemantic-conventions.svg + +[trace-semantic_conventions]: https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/trace/semantic_conventions diff --git a/node_modules/@opentelemetry/semantic-conventions/package.json b/node_modules/@opentelemetry/semantic-conventions/package.json new file mode 100644 index 0000000..1c1cdd4 --- /dev/null +++ b/node_modules/@opentelemetry/semantic-conventions/package.json @@ -0,0 +1,67 @@ +{ + "name": "@opentelemetry/semantic-conventions", + "version": "1.10.0", + "description": "OpenTelemetry semantic conventions", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "prepublishOnly": "npm run compile", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "version": "node ../../scripts/version-update.js", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies", + "prewatch": "npm run precompile", + "peer-api-check": "node ../../scripts/peer-api-check.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "tracing", + "attributes", + "semantic conventions" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "10.0.0", + "@types/node": "18.6.5", + "@types/sinon": "10.0.13", + "codecov": "3.8.3", + "mocha": "10.0.0", + "nock": "13.0.11", + "nyc": "15.1.0", + "rimraf": "4.1.2", + "sinon": "15.0.0", + "ts-mocha": "10.0.0", + "typescript": "4.4.4" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-semantic-conventions", + "sideEffects": false, + "gitHead": "56e6b1bb890f844b8963a146780d0b9cfa8abd0d" +} diff --git a/node_modules/@tootallnate/once/LICENSE b/node_modules/@tootallnate/once/LICENSE new file mode 100644 index 0000000..c4c56a2 --- /dev/null +++ b/node_modules/@tootallnate/once/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Nathan Rajlich + +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. diff --git a/node_modules/@tootallnate/once/README.md b/node_modules/@tootallnate/once/README.md new file mode 100644 index 0000000..bc980fd --- /dev/null +++ b/node_modules/@tootallnate/once/README.md @@ -0,0 +1,93 @@ +# @tootallnate/once + +### Creates a Promise that waits for a single event + +## Installation + +Install with `npm`: + +```bash +$ npm install @tootallnate/once +``` + +## API + +### once(emitter: EventEmitter, name: string, opts?: OnceOptions): Promise<[...Args]> + +Creates a Promise that waits for event `name` to occur on `emitter`, and resolves +the promise with an array of the values provided to the event handler. If an +`error` event occurs before the event specified by `name`, then the Promise is +rejected with the error argument. + +```typescript +import once from '@tootallnate/once'; +import { EventEmitter } from 'events'; + +const emitter = new EventEmitter(); + +setTimeout(() => { + emitter.emit('foo', 'bar'); +}, 100); + +const [result] = await once(emitter, 'foo'); +console.log({ result }); +// { result: 'bar' } +``` + +#### Promise Strong Typing + +The main feature that this module provides over other "once" implementations is that +the Promise that is returned is _**strongly typed**_ based on the type of `emitter` +and the `name` of the event. Some examples are shown below. + +_The process "exit" event contains a single number for exit code:_ + +```typescript +const [code] = await once(process, 'exit'); +// ^ number +``` +_A child process "exit" event contains either an exit code or a signal:_ + +```typescript +const child = spawn('echo', []); +const [code, signal] = await once(child, 'exit'); +// ^ number | null +// ^ string | null +``` + +_A forked child process "message" event is type `any`, so you can cast the Promise directly:_ + +```typescript +const child = fork('file.js'); + +// With `await` +const [message, _]: [WorkerPayload, unknown] = await once(child, 'message'); + +// With Promise +const messagePromise: Promise<[WorkerPayload, unknown]> = once(child, 'message'); + +// Better yet would be to leave it as `any`, and validate the payload +// at runtime with i.e. `ajv` + `json-schema-to-typescript` +``` + +_If the TypeScript definition does not contain an overload for the specified event name, then the Promise will have type `unknown[]` and your code will need to narrow the result manually:_ + +```typescript +interface CustomEmitter extends EventEmitter { + on(name: 'foo', listener: (a: string, b: number) => void): this; +} + +const emitter: CustomEmitter = new EventEmitter(); + +// "foo" event is a defined overload, so it's properly typed +const fooPromise = once(emitter, 'foo'); +// ^ Promise<[a: string, b: number]> + +// "bar" event in not a defined overload, so it gets `unknown[]` +const barPromise = once(emitter, 'bar'); +// ^ Promise +``` + +### OnceOptions + +- `signal` - `AbortSignal` instance to unbind event handlers before the Promise has been fulfilled. diff --git a/node_modules/@tootallnate/once/package.json b/node_modules/@tootallnate/once/package.json new file mode 100644 index 0000000..69ce947 --- /dev/null +++ b/node_modules/@tootallnate/once/package.json @@ -0,0 +1,52 @@ +{ + "name": "@tootallnate/once", + "version": "2.0.0", + "description": "Creates a Promise that waits for a single event", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "test": "jest", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/once.git" + }, + "keywords": [], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/once/issues" + }, + "devDependencies": { + "@types/jest": "^27.0.2", + "@types/node": "^12.12.11", + "abort-controller": "^3.0.0", + "jest": "^27.2.1", + "rimraf": "^3.0.0", + "ts-jest": "^27.0.5", + "typescript": "^4.4.3" + }, + "engines": { + "node": ">= 10" + }, + "jest": { + "preset": "ts-jest", + "globals": { + "ts-jest": { + "diagnostics": false, + "isolatedModules": true + } + }, + "verbose": false, + "testEnvironment": "node", + "testMatch": [ + "/test/**/*.test.ts" + ] + } +} diff --git a/node_modules/@types/yoga-layout/LICENSE b/node_modules/@types/yoga-layout/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/yoga-layout/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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 diff --git a/node_modules/@types/yoga-layout/README.md b/node_modules/@types/yoga-layout/README.md new file mode 100644 index 0000000..571e307 --- /dev/null +++ b/node_modules/@types/yoga-layout/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/yoga-layout` + +# Summary +This package contains type definitions for yoga-layout (https://github.com/facebook/yoga#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yoga-layout. + +### Additional Details + * Last updated: Sun, 17 May 2020 16:19:59 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [tnobody](https://github.com/tnobody). diff --git a/node_modules/@types/yoga-layout/index.d.ts b/node_modules/@types/yoga-layout/index.d.ts new file mode 100644 index 0000000..101b9f4 --- /dev/null +++ b/node_modules/@types/yoga-layout/index.d.ts @@ -0,0 +1,413 @@ +// Type definitions for yoga-layout 1.9 +// Project: https://github.com/facebook/yoga#readme +// Definitions by: tnobody +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare const ALIGN_AUTO: 0; +declare const ALIGN_COUNT: 8; +declare const ALIGN_FLEX_START: 1; +declare const ALIGN_CENTER: 2; +declare const ALIGN_FLEX_END: 3; +declare const ALIGN_STRETCH: 4; +declare const ALIGN_BASELINE: 5; +declare const ALIGN_SPACE_BETWEEN: 6; +declare const ALIGN_SPACE_AROUND: 7; +declare const DIMENSION_COUNT: 2; +declare const DIMENSION_WIDTH: 0; +declare const DIMENSION_HEIGHT: 1; +declare const DIRECTION_COUNT: 3; +declare const DIRECTION_INHERIT: 0; +declare const DIRECTION_LTR: 1; +declare const DIRECTION_RTL: 2; +declare const DISPLAY_COUNT: 2; +declare const DISPLAY_FLEX: 0; +declare const DISPLAY_NONE: 1; +declare const EDGE_COUNT: 9; +declare const EDGE_LEFT: 0; +declare const EDGE_TOP: 1; +declare const EDGE_RIGHT: 2; +declare const EDGE_BOTTOM: 3; +declare const EDGE_START: 4; +declare const EDGE_END: 5; +declare const EDGE_HORIZONTAL: 6; +declare const EDGE_VERTICAL: 7; +declare const EDGE_ALL: 8; +declare const EXPERIMENTAL_FEATURE_COUNT: 1; +declare const EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: 0; +declare const FLEX_DIRECTION_COUNT: 4; +declare const FLEX_DIRECTION_COLUMN: 0; +declare const FLEX_DIRECTION_COLUMN_REVERSE: 1; +declare const FLEX_DIRECTION_ROW: 2; +declare const FLEX_DIRECTION_ROW_REVERSE: 3; +declare const JUSTIFY_COUNT: 6; +declare const JUSTIFY_FLEX_START: 0; +declare const JUSTIFY_CENTER: 1; +declare const JUSTIFY_FLEX_END: 2; +declare const JUSTIFY_SPACE_BETWEEN: 3; +declare const JUSTIFY_SPACE_AROUND: 4; +declare const JUSTIFY_SPACE_EVENLY: 5; +declare const LOG_LEVEL_COUNT: 6; +declare const LOG_LEVEL_ERROR: 0; +declare const LOG_LEVEL_WARN: 1; +declare const LOG_LEVEL_INFO: 2; +declare const LOG_LEVEL_DEBUG: 3; +declare const LOG_LEVEL_VERBOSE: 4; +declare const LOG_LEVEL_FATAL: 5; +declare const MEASURE_MODE_COUNT: 3; +declare const MEASURE_MODE_UNDEFINED: 0; +declare const MEASURE_MODE_EXACTLY: 1; +declare const MEASURE_MODE_AT_MOST: 2; +declare const NODE_TYPE_COUNT: 2; +declare const NODE_TYPE_DEFAULT: 0; +declare const NODE_TYPE_TEXT: 1; +declare const OVERFLOW_COUNT: 3; +declare const OVERFLOW_VISIBLE: 0; +declare const OVERFLOW_HIDDEN: 1; +declare const OVERFLOW_SCROLL: 2; +declare const POSITION_TYPE_COUNT: 2; +declare const POSITION_TYPE_RELATIVE: 0; +declare const POSITION_TYPE_ABSOLUTE: 1; +declare const PRINT_OPTIONS_COUNT: 3; +declare const PRINT_OPTIONS_LAYOUT: 1; +declare const PRINT_OPTIONS_STYLE: 2; +declare const PRINT_OPTIONS_CHILDREN: 4; +declare const UNIT_COUNT: 4; +declare const UNIT_UNDEFINED: 0; +declare const UNIT_POINT: 1; +declare const UNIT_PERCENT: 2; +declare const UNIT_AUTO: 3; +declare const WRAP_COUNT: 3; +declare const WRAP_NO_WRAP: 0; +declare const WRAP_WRAP: 1; +declare const WRAP_WRAP_REVERSE: 2; + +interface ConstantsStatic { + readonly ALIGN_AUTO: typeof ALIGN_AUTO; + readonly ALIGN_COUNT: typeof ALIGN_COUNT; + readonly ALIGN_FLEX_START: typeof ALIGN_FLEX_START; + readonly ALIGN_CENTER: typeof ALIGN_CENTER; + readonly ALIGN_FLEX_END: typeof ALIGN_FLEX_END; + readonly ALIGN_STRETCH: typeof ALIGN_STRETCH; + readonly ALIGN_BASELINE: typeof ALIGN_BASELINE; + readonly ALIGN_SPACE_BETWEEN: typeof ALIGN_SPACE_BETWEEN; + readonly ALIGN_SPACE_AROUND: typeof ALIGN_SPACE_AROUND; + readonly DIMENSION_COUNT: typeof DIMENSION_COUNT; + readonly DIMENSION_WIDTH: typeof DIMENSION_WIDTH; + readonly DIMENSION_HEIGHT: typeof DIMENSION_HEIGHT; + readonly DIRECTION_COUNT: typeof DIRECTION_COUNT; + readonly DIRECTION_INHERIT: typeof DIRECTION_INHERIT; + readonly DIRECTION_LTR: typeof DIRECTION_LTR; + readonly DIRECTION_RTL: typeof DIRECTION_RTL; + readonly DISPLAY_COUNT: typeof DISPLAY_COUNT; + readonly DISPLAY_FLEX: typeof DISPLAY_FLEX; + readonly DISPLAY_NONE: typeof DISPLAY_NONE; + readonly EDGE_COUNT: typeof EDGE_COUNT; + readonly EDGE_LEFT: typeof EDGE_LEFT; + readonly EDGE_TOP: typeof EDGE_TOP; + readonly EDGE_RIGHT: typeof EDGE_RIGHT; + readonly EDGE_BOTTOM: typeof EDGE_BOTTOM; + readonly EDGE_START: typeof EDGE_START; + readonly EDGE_END: typeof EDGE_END; + readonly EDGE_HORIZONTAL: typeof EDGE_HORIZONTAL; + readonly EDGE_VERTICAL: typeof EDGE_VERTICAL; + readonly EDGE_ALL: typeof EDGE_ALL; + readonly EXPERIMENTAL_FEATURE_COUNT: typeof EXPERIMENTAL_FEATURE_COUNT; + readonly EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: typeof EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS; + readonly FLEX_DIRECTION_COUNT: typeof FLEX_DIRECTION_COUNT; + readonly FLEX_DIRECTION_COLUMN: typeof FLEX_DIRECTION_COLUMN; + readonly FLEX_DIRECTION_COLUMN_REVERSE: typeof FLEX_DIRECTION_COLUMN_REVERSE; + readonly FLEX_DIRECTION_ROW: typeof FLEX_DIRECTION_ROW; + readonly FLEX_DIRECTION_ROW_REVERSE: typeof FLEX_DIRECTION_ROW_REVERSE; + readonly JUSTIFY_COUNT: typeof JUSTIFY_COUNT; + readonly JUSTIFY_FLEX_START: typeof JUSTIFY_FLEX_START; + readonly JUSTIFY_CENTER: typeof JUSTIFY_CENTER; + readonly JUSTIFY_FLEX_END: typeof JUSTIFY_FLEX_END; + readonly JUSTIFY_SPACE_BETWEEN: typeof JUSTIFY_SPACE_BETWEEN; + readonly JUSTIFY_SPACE_AROUND: typeof JUSTIFY_SPACE_AROUND; + readonly JUSTIFY_SPACE_EVENLY: typeof JUSTIFY_SPACE_EVENLY; + readonly LOG_LEVEL_COUNT: typeof LOG_LEVEL_COUNT; + readonly LOG_LEVEL_ERROR: typeof LOG_LEVEL_ERROR; + readonly LOG_LEVEL_WARN: typeof LOG_LEVEL_WARN; + readonly LOG_LEVEL_INFO: typeof LOG_LEVEL_INFO; + readonly LOG_LEVEL_DEBUG: typeof LOG_LEVEL_DEBUG; + readonly LOG_LEVEL_VERBOSE: typeof LOG_LEVEL_VERBOSE; + readonly LOG_LEVEL_FATAL: typeof LOG_LEVEL_FATAL; + readonly MEASURE_MODE_COUNT: typeof MEASURE_MODE_COUNT; + readonly MEASURE_MODE_UNDEFINED: typeof MEASURE_MODE_UNDEFINED; + readonly MEASURE_MODE_EXACTLY: typeof MEASURE_MODE_EXACTLY; + readonly MEASURE_MODE_AT_MOST: typeof MEASURE_MODE_AT_MOST; + readonly NODE_TYPE_COUNT: typeof NODE_TYPE_COUNT; + readonly NODE_TYPE_DEFAULT: typeof NODE_TYPE_DEFAULT; + readonly NODE_TYPE_TEXT: typeof NODE_TYPE_TEXT; + readonly OVERFLOW_COUNT: typeof OVERFLOW_COUNT; + readonly OVERFLOW_VISIBLE: typeof OVERFLOW_VISIBLE; + readonly OVERFLOW_HIDDEN: typeof OVERFLOW_HIDDEN; + readonly OVERFLOW_SCROLL: typeof OVERFLOW_SCROLL; + readonly POSITION_TYPE_COUNT: typeof POSITION_TYPE_COUNT; + readonly POSITION_TYPE_RELATIVE: typeof POSITION_TYPE_RELATIVE; + readonly POSITION_TYPE_ABSOLUTE: typeof POSITION_TYPE_ABSOLUTE; + readonly PRINT_OPTIONS_COUNT: typeof PRINT_OPTIONS_COUNT; + readonly PRINT_OPTIONS_LAYOUT: typeof PRINT_OPTIONS_LAYOUT; + readonly PRINT_OPTIONS_STYLE: typeof PRINT_OPTIONS_STYLE; + readonly PRINT_OPTIONS_CHILDREN: typeof PRINT_OPTIONS_CHILDREN; + readonly UNIT_COUNT: typeof UNIT_COUNT; + readonly UNIT_UNDEFINED: typeof UNIT_UNDEFINED; + readonly UNIT_POINT: typeof UNIT_POINT; + readonly UNIT_PERCENT: typeof UNIT_PERCENT; + readonly UNIT_AUTO: typeof UNIT_AUTO; + readonly WRAP_COUNT: typeof WRAP_COUNT; + readonly WRAP_NO_WRAP: typeof WRAP_NO_WRAP; + readonly WRAP_WRAP: typeof WRAP_WRAP; + readonly WRAP_WRAP_REVERSE: typeof WRAP_WRAP_REVERSE; +} + +declare namespace Yoga { + type YogaJustifyContent = + | typeof JUSTIFY_CENTER + | typeof JUSTIFY_FLEX_END + | typeof JUSTIFY_FLEX_START + | typeof JUSTIFY_SPACE_AROUND + | typeof JUSTIFY_SPACE_BETWEEN + | typeof JUSTIFY_SPACE_EVENLY; + + type YogaAlign = + | typeof ALIGN_AUTO + | typeof ALIGN_BASELINE + | typeof ALIGN_CENTER + | typeof ALIGN_FLEX_END + | typeof ALIGN_FLEX_START + | typeof ALIGN_SPACE_AROUND + | typeof ALIGN_SPACE_BETWEEN + | typeof ALIGN_STRETCH; + + type YogaFlexDirection = + | typeof FLEX_DIRECTION_COLUMN + | typeof FLEX_DIRECTION_COLUMN_REVERSE + | typeof FLEX_DIRECTION_COUNT + | typeof FLEX_DIRECTION_ROW + | typeof FLEX_DIRECTION_ROW_REVERSE; + + type YogaDirection = + | typeof DIRECTION_INHERIT + | typeof DIRECTION_LTR + | typeof DIRECTION_RTL; + + type YogaFlexWrap = + | typeof WRAP_NO_WRAP + | typeof WRAP_WRAP + | typeof WRAP_WRAP_REVERSE; + + type YogaEdge = + | typeof EDGE_LEFT + | typeof EDGE_TOP + | typeof EDGE_RIGHT + | typeof EDGE_BOTTOM + | typeof EDGE_START + | typeof EDGE_END + | typeof EDGE_HORIZONTAL + | typeof EDGE_VERTICAL + | typeof EDGE_ALL; + + type YogaDisplay = + | typeof DISPLAY_FLEX + | typeof DISPLAY_NONE; + + type YogaUnit = + | typeof UNIT_AUTO + | typeof UNIT_PERCENT + | typeof UNIT_POINT + | typeof UNIT_UNDEFINED; + + type YogaOverflow = + | typeof OVERFLOW_HIDDEN + | typeof OVERFLOW_SCROLL + | typeof OVERFLOW_VISIBLE; + + type YogaPositionType = + | typeof POSITION_TYPE_ABSOLUTE + | typeof POSITION_TYPE_RELATIVE; + + type YogaExperimentalFeature = typeof EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS; + + type YogaMeasureMode = + | typeof MEASURE_MODE_COUNT + | typeof MEASURE_MODE_UNDEFINED + | typeof MEASURE_MODE_EXACTLY + | typeof MEASURE_MODE_AT_MOST; + + interface YogaNode { + calculateLayout( + width?: number, + height?: number, + direction?: YogaDirection, + ): void; + copyStyle(node: YogaNode): void; + free(): void; + freeRecursive(): void; + getAlignContent(): YogaAlign; + getAlignItems(): YogaAlign; + getAlignSelf(): YogaAlign; + getAspectRatio(): number; + getBorder(edge: YogaEdge): number; + getChild(index: number): YogaNode; + getChildCount(): number; + getComputedBorder(edge: YogaEdge): number; + getComputedBottom(): number; + getComputedHeight(): number; + getComputedLayout(): Layout; + getComputedLeft(): number; + getComputedMargin(edge: YogaEdge): number; + getComputedPadding(edge: YogaEdge): number; + getComputedRight(): number; + getComputedTop(): number; + getComputedWidth(): number; + getDisplay(): YogaDisplay; + getFlexBasis(): number; + getFlexDirection(): YogaFlexDirection; + getFlexGrow(): number; + getFlexShrink(): number; + getFlexWrap(): YogaFlexWrap; + getHeight(): Value; + getJustifyContent(): YogaJustifyContent; + getMargin(edge: YogaEdge): Value; + getMaxHeight(): Value; + getMaxWidth(): Value; + getMinHeight(): Value; + getMinWidth(): Value; + getOverflow(): YogaOverflow; + getPadding(edge: YogaEdge): Value; + getParent(): YogaNode | null; + getPosition(edge: YogaEdge): Value; + getPositionType(): YogaPositionType; + getWidth(): Value; + insertChild(child: YogaNode, index: number): void; + isDirty(): boolean; + markDirty(): void; + removeChild(child: YogaNode): void; + reset(): void; + setAlignContent(alignContent: YogaAlign): void; + setAlignItems(alignItems: YogaAlign): void; + setAlignSelf(alignSelf: YogaAlign): void; + setAspectRatio(aspectRatio: number): void; + setBorder(edge: YogaEdge, borderWidth: number): void; + setDisplay(display: YogaDisplay): void; + setFlex(flex: number): void; + setFlexBasis(flexBasis: number | string): void; + setFlexBasisPercent(flexBasis: number): void; + setFlexDirection(flexDirection: YogaFlexDirection): void; + setFlexGrow(flexGrow: number): void; + setFlexShrink(flexShrink: number): void; + setFlexWrap(flexWrap: YogaFlexWrap): void; + setHeight(height: number | string): void; + setHeightAuto(): void; + setHeightPercent(height: number): void; + setJustifyContent(justifyContent: YogaJustifyContent): void; + setMargin(edge: YogaEdge, margin: number): void; + setMarginAuto(edge: YogaEdge): void; + setMarginPercent(edge: YogaEdge, margin: number): void; + setMaxHeight(maxHeight: number | string): void; + setMaxHeightPercent(maxHeight: number): void; + setMaxWidth(maxWidth: number | string): void; + setMaxWidthPercent(maxWidth: number): void; + setMeasureFunc(measureFunc: (width: number, widthMeasureMode: YogaMeasureMode, height: number, heightMeasureMode: YogaMeasureMode) => { width?: number; height?: number } | null): void; + setMinHeight(minHeight: number | string): void; + setMinHeightPercent(minHeight: number): void; + setMinWidth(minWidth: number | string): void; + setMinWidthPercent(minWidth: number): void; + setOverflow(overflow: YogaOverflow): void; + setPadding(edge: YogaEdge, padding: number | string): void; + setPaddingPercent(edge: YogaEdge, padding: number): void; + setPosition(edge: YogaEdge, position: number | string): void; + setPositionPercent(edge: YogaEdge, position: number): void; + setPositionType(positionType: YogaPositionType): void; + setWidth(width: number | string): void; + setWidthAuto(): void; + setWidthPercent(width: number): void; + unsetMeasureFunc(): void; + } + + interface YogaConfig { + isExperimentalFeatureEnabled(feature: YogaExperimentalFeature): boolean; + setExperimentalFeatureEnabled( + feature: YogaExperimentalFeature, + enabled: boolean, + ): void; + setPointScaleFactor(factor: number): void; + } +} + +declare class Layout { + readonly left: number; + readonly right: number; + readonly top: number; + readonly bottom: number; + readonly width: number; + readonly height: number; + constructor( + left: number, + right: number, + top: number, + bottom: number, + width: number, + height: number, + ); + + fromJs(expose: ( + left: number, + right: number, + top: number, + bottom: number, + width: number, + height: number, + ) => any): void; + + toString(): string; +} + +declare class Size { + static fromJS(dim: { width: number, height: number }): Size; + + readonly width: number; + readonly height: number; + + constructor(width: number, height: number); + + fromJS(expose: (width: number, height: number) => any): void; + + toString(): string; +} + +declare class Value { + readonly unit: Yoga.YogaUnit | number; + readonly value: number; + + constructor(unit: Yoga.YogaUnit | number, value: number); + + fromJS(expose: (unit: Yoga.YogaUnit | number, value: number) => any): void; + + toString(): string; + valueOf(): number; +} + +interface NodeStatic { + create(): Yoga.YogaNode; + createDefault(): Yoga.YogaNode; + createWithConfig(config: Yoga.YogaConfig): Yoga.YogaNode; + destroy(node: Yoga.YogaNode): any; +} + +interface ConfigStatic { + create(): Yoga.YogaConfig; + destroy(config: Yoga.YogaConfig): any; +} + +interface YogaStatic extends ConstantsStatic { + Node: NodeStatic; + Config: ConfigStatic; + getInstanceCount(): number; +} + +declare const Yoga: YogaStatic; + +export = Yoga; diff --git a/node_modules/@types/yoga-layout/package.json b/node_modules/@types/yoga-layout/package.json new file mode 100644 index 0000000..8b289a4 --- /dev/null +++ b/node_modules/@types/yoga-layout/package.json @@ -0,0 +1,24 @@ +{ + "name": "@types/yoga-layout", + "version": "1.9.2", + "description": "TypeScript definitions for yoga-layout", + "license": "MIT", + "contributors": [ + { + "name": "tnobody", + "url": "https://github.com/tnobody", + "githubUsername": "tnobody" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/yoga-layout" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "1586c0ef103d4675788030a0a69368315d04e2bfdba0e91ed047dbff74d189ba", + "typeScriptVersion": "3.0" +} \ No newline at end of file diff --git a/node_modules/agent-base/README.md b/node_modules/agent-base/README.md new file mode 100644 index 0000000..256f1f3 --- /dev/null +++ b/node_modules/agent-base/README.md @@ -0,0 +1,145 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance +[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) + +This module provides an `http.Agent` generator. That is, you pass it an async +callback function, and it returns a new `http.Agent` instance that will invoke the +given callback function when sending outbound HTTP requests. + +#### Some subclasses: + +Here's some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install agent-base +``` + + +Example +------- + +Here's a minimal example that creates a new `net.Socket` connection to the server +for every HTTP request (i.e. the equivalent of `agent: false` option): + +```js +var net = require('net'); +var tls = require('tls'); +var url = require('url'); +var http = require('http'); +var agent = require('agent-base'); + +var endpoint = 'http://nodejs.org/api/'; +var parsed = url.parse(endpoint); + +// This is the important part! +parsed.agent = agent(function (req, opts) { + var socket; + // `secureEndpoint` is true when using the https module + if (opts.secureEndpoint) { + socket = tls.connect(opts); + } else { + socket = net.connect(opts); + } + return socket; +}); + +// Everything else works just like normal... +http.get(parsed, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +Returning a Promise or using an `async` function is also supported: + +```js +agent(async function (req, opts) { + await sleep(1000); + // etc… +}); +``` + +Return another `http.Agent` instance to "pass through" the responsibility +for that HTTP request to that agent: + +```js +agent(function (req, opts) { + return opts.secureEndpoint ? https.globalAgent : http.globalAgent; +}); +``` + + +API +--- + +## Agent(Function callback[, Object options]) → [http.Agent][] + +Creates a base `http.Agent` that will execute the callback function `callback` +for every HTTP request that it is used as the `agent` for. The callback function +is responsible for creating a `stream.Duplex` instance of some kind that will be +used as the underlying socket in the HTTP request. + +The `options` object accepts the following properties: + + * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). + +The callback function should have the following signature: + +### callback(http.ClientRequest req, Object options, Function cb) → undefined + +The ClientRequest `req` can be accessed to read request headers and +and the path, etc. The `options` object contains the options passed +to the `http.request()`/`https.request()` function call, and is formatted +to be directly passed to `net.connect()`/`tls.connect()`, or however +else you want a Socket to be created. Pass the created socket to +the callback function `cb` once created, and the HTTP request will +continue to proceed. + +If the `https` module is used to invoke the HTTP request, then the +`secureEndpoint` property on `options` _will be set to `true`_. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/agent-base/package.json b/node_modules/agent-base/package.json new file mode 100644 index 0000000..fadce3a --- /dev/null +++ b/node_modules/agent-base/package.json @@ -0,0 +1,64 @@ +{ + "name": "agent-base", + "version": "6.0.2", + "description": "Turn a function into an `http.Agent` instance", + "main": "dist/src/index", + "typings": "dist/src/index", + "files": [ + "dist/src", + "src" + ], + "scripts": { + "prebuild": "rimraf dist", + "build": "tsc", + "postbuild": "cpy --parents src test '!**/*.ts' dist", + "test": "mocha --reporter spec dist/test/*.js", + "test-lint": "eslint src --ext .js,.ts", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-agent-base.git" + }, + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/node-agent-base/issues" + }, + "dependencies": { + "debug": "4" + }, + "devDependencies": { + "@types/debug": "4", + "@types/mocha": "^5.2.7", + "@types/node": "^14.0.20", + "@types/semver": "^7.1.0", + "@types/ws": "^6.0.3", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "async-listen": "^1.2.0", + "cpy-cli": "^2.0.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.0", + "rimraf": "^3.0.0", + "semver": "^7.1.2", + "typescript": "^3.5.3", + "ws": "^3.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } +} diff --git a/node_modules/agent-base/src/index.ts b/node_modules/agent-base/src/index.ts new file mode 100644 index 0000000..a47ccd4 --- /dev/null +++ b/node_modules/agent-base/src/index.ts @@ -0,0 +1,345 @@ +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +import createDebug from 'debug'; +import promisify from './promisify'; + +const debug = createDebug('agent-base'); + +function isAgent(v: any): v is createAgent.AgentLike { + return Boolean(v) && typeof v.addRequest === 'function'; +} + +function isSecureEndpoint(): boolean { + const { stack } = new Error(); + if (typeof stack !== 'string') return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} + +function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +function createAgent( + callback: createAgent.AgentCallback, + opts?: createAgent.AgentOptions +): createAgent.Agent; +function createAgent( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + opts?: createAgent.AgentOptions +) { + return new createAgent.Agent(callback, opts); +} + +namespace createAgent { + export interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + + export interface AgentRequestOptions { + host?: string; + path?: string; + // `port` on `http.RequestOptions` can be a string or undefined, + // but `net.TcpNetConnectOpts` expects only a number + port: number; + } + + export interface HttpRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: false; + } + + export interface HttpsRequestOptions + extends AgentRequestOptions, + Omit { + secureEndpoint: true; + } + + export type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + + export type AgentLike = Pick | http.Agent; + + export type AgentCallbackReturn = Duplex | AgentLike; + + export type AgentCallbackCallback = ( + err?: Error | null, + socket?: createAgent.AgentCallbackReturn + ) => void; + + export type AgentCallbackPromise = ( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ) => + | createAgent.AgentCallbackReturn + | Promise; + + export type AgentCallback = typeof Agent.prototype.callback; + + export type AgentOptions = { + timeout?: number; + }; + + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + export class Agent extends EventEmitter { + public timeout: number | null; + public maxFreeSockets: number; + public maxTotalSockets: number; + public maxSockets: number; + public sockets: { + [key: string]: net.Socket[]; + }; + public freeSockets: { + [key: string]: net.Socket[]; + }; + public requests: { + [key: string]: http.IncomingMessage[]; + }; + public options: https.AgentOptions; + private promisifiedCallback?: createAgent.AgentCallbackPromise; + private explicitDefaultPort?: number; + private explicitProtocol?: string; + + constructor( + callback?: createAgent.AgentCallback | createAgent.AgentOptions, + _opts?: createAgent.AgentOptions + ) { + super(); + + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } else if (callback) { + opts = callback; + } + + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + + get defaultPort(): number { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + + set defaultPort(v: number) { + this.explicitDefaultPort = v; + } + + get protocol(): string { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + + set protocol(v: string) { + this.explicitProtocol = v; + } + + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions, + fn: createAgent.AgentCallbackCallback + ): void; + callback( + req: createAgent.ClientRequest, + opts: createAgent.RequestOptions + ): + | createAgent.AgentCallbackReturn + | Promise; + callback( + req: createAgent.ClientRequest, + opts: createAgent.AgentOptions, + fn?: createAgent.AgentCallbackCallback + ): + | createAgent.AgentCallbackReturn + | Promise + | void { + throw new Error( + '"agent-base" has no default implementation, you must subclass and override `callback()`' + ); + } + + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void { + const opts: RequestOptions = { ..._opts }; + + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + + if (opts.host == null) { + opts.host = 'localhost'; + } + + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + + let timedOut = false; + let timeoutId: ReturnType | null = null; + const timeoutMs = opts.timeout || this.timeout; + + const onerror = (err: NodeJS.ErrnoException) => { + if (req._hadError) return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err: NodeJS.ErrnoException = new Error( + `A "socket" was not created for HTTP request before ${timeoutMs}ms` + ); + err.code = 'ETIMEOUT'; + onerror(err); + }; + + const callbackError = (err: NodeJS.ErrnoException) => { + if (timedOut) return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + + const onsocket = (socket: AgentCallbackReturn) => { + if (timedOut) return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug( + 'Callback returned another Agent instance %o', + socket.constructor.name + ); + (socket as createAgent.Agent).addRequest(req, opts); + return; + } + + if (socket) { + socket.once('free', () => { + this.freeSocket(socket as net.Socket, opts); + }); + req.onSocket(socket as net.Socket); + return; + } + + const err = new Error( + `no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\`` + ); + onerror(err); + }; + + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify(this.callback); + } else { + this.promisifiedCallback = this.callback; + } + } + + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + + try { + debug( + 'Resolving socket for %o request: %o', + opts.protocol, + `${req.method} ${req.path}` + ); + Promise.resolve(this.promisifiedCallback(req, opts)).then( + onsocket, + callbackError + ); + } catch (err) { + Promise.reject(err).catch(callbackError); + } + } + + freeSocket(socket: net.Socket, opts: AgentOptions) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +} + +export = createAgent; diff --git a/node_modules/agent-base/src/promisify.ts b/node_modules/agent-base/src/promisify.ts new file mode 100644 index 0000000..60cc662 --- /dev/null +++ b/node_modules/agent-base/src/promisify.ts @@ -0,0 +1,33 @@ +import { + Agent, + ClientRequest, + RequestOptions, + AgentCallbackCallback, + AgentCallbackPromise, + AgentCallbackReturn +} from './index'; + +type LegacyCallback = ( + req: ClientRequest, + opts: RequestOptions, + fn: AgentCallbackCallback +) => void; + +export default function promisify(fn: LegacyCallback): AgentCallbackPromise { + return function(this: Agent, req: ClientRequest, opts: RequestOptions) { + return new Promise((resolve, reject) => { + fn.call( + this, + req, + opts, + (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { + if (err) { + reject(err); + } else { + resolve(rtn); + } + } + ); + }); + }; +} diff --git a/node_modules/ansi-escapes/index.d.ts b/node_modules/ansi-escapes/index.d.ts new file mode 100644 index 0000000..5201942 --- /dev/null +++ b/node_modules/ansi-escapes/index.d.ts @@ -0,0 +1,248 @@ +/// +import {LiteralUnion} from 'type-fest'; + +declare namespace ansiEscapes { + interface ImageOptions { + /** + The width is given as a number followed by a unit, or the word `'auto'`. + + - `N`: N character cells. + - `Npx`: N pixels. + - `N%`: N percent of the session's width or height. + - `auto`: The image's inherent size will be used to determine an appropriate dimension. + */ + readonly width?: LiteralUnion<'auto', number | string>; + + /** + The height is given as a number followed by a unit, or the word `'auto'`. + + - `N`: N character cells. + - `Npx`: N pixels. + - `N%`: N percent of the session's width or height. + - `auto`: The image's inherent size will be used to determine an appropriate dimension. + */ + readonly height?: LiteralUnion<'auto', number | string>; + + readonly preserveAspectRatio?: boolean; + } + + interface AnnotationOptions { + /** + Nonzero number of columns to annotate. + + Default: The remainder of the line. + */ + readonly length?: number; + + /** + Starting X coordinate. + + Must be used with `y` and `length`. + + Default: The cursor position + */ + readonly x?: number; + + /** + Starting Y coordinate. + + Must be used with `x` and `length`. + + Default: Cursor position. + */ + readonly y?: number; + + /** + Create a "hidden" annotation. + + Annotations created this way can be shown using the "Show Annotations" iTerm command. + */ + readonly isHidden?: boolean; + } +} + +declare const ansiEscapes: { + /** + Set the absolute position of the cursor. `x0` `y0` is the top left of the screen. + */ + cursorTo(x: number, y?: number): string; + + /** + Set the position of the cursor relative to its current position. + */ + cursorMove(x: number, y?: number): string; + + /** + Move cursor up a specific amount of rows. + + @param count - Count of rows to move up. Default is `1`. + */ + cursorUp(count?: number): string; + + /** + Move cursor down a specific amount of rows. + + @param count - Count of rows to move down. Default is `1`. + */ + cursorDown(count?: number): string; + + /** + Move cursor forward a specific amount of rows. + + @param count - Count of rows to move forward. Default is `1`. + */ + cursorForward(count?: number): string; + + /** + Move cursor backward a specific amount of rows. + + @param count - Count of rows to move backward. Default is `1`. + */ + cursorBackward(count?: number): string; + + /** + Move cursor to the left side. + */ + cursorLeft: string; + + /** + Save cursor position. + */ + cursorSavePosition: string; + + /** + Restore saved cursor position. + */ + cursorRestorePosition: string; + + /** + Get cursor position. + */ + cursorGetPosition: string; + + /** + Move cursor to the next line. + */ + cursorNextLine: string; + + /** + Move cursor to the previous line. + */ + cursorPrevLine: string; + + /** + Hide cursor. + */ + cursorHide: string; + + /** + Show cursor. + */ + cursorShow: string; + + /** + Erase from the current cursor position up the specified amount of rows. + + @param count - Count of rows to erase. + */ + eraseLines(count: number): string; + + /** + Erase from the current cursor position to the end of the current line. + */ + eraseEndLine: string; + + /** + Erase from the current cursor position to the start of the current line. + */ + eraseStartLine: string; + + /** + Erase the entire current line. + */ + eraseLine: string; + + /** + Erase the screen from the current line down to the bottom of the screen. + */ + eraseDown: string; + + /** + Erase the screen from the current line up to the top of the screen. + */ + eraseUp: string; + + /** + Erase the screen and move the cursor the top left position. + */ + eraseScreen: string; + + /** + Scroll display up one line. + */ + scrollUp: string; + + /** + Scroll display down one line. + */ + scrollDown: string; + + /** + Clear the terminal screen. (Viewport) + */ + clearScreen: string; + + /** + Clear the whole terminal, including scrollback buffer. (Not just the visible part of it) + */ + clearTerminal: string; + + /** + Output a beeping sound. + */ + beep: string; + + /** + Create a clickable link. + + [Supported terminals.](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) Use [`supports-hyperlinks`](https://github.com/jamestalmage/supports-hyperlinks) to detect link support. + */ + link(text: string, url: string): string; + + /** + Display an image. + + _Currently only supported on iTerm2 >=3_ + + See [term-img](https://github.com/sindresorhus/term-img) for a higher-level module. + + @param buffer - Buffer of an image. Usually read in with `fs.readFile()`. + */ + image(buffer: Buffer, options?: ansiEscapes.ImageOptions): string; + + iTerm: { + /** + [Inform iTerm2](https://www.iterm2.com/documentation-escape-codes.html) of the current directory to help semantic history and enable [Cmd-clicking relative paths](https://coderwall.com/p/b7e82q/quickly-open-files-in-iterm-with-cmd-click). + + @param cwd - Current directory. Default: `process.cwd()`. + */ + setCwd(cwd?: string): string; + + /** + An annotation looks like this when shown: + + ![screenshot of iTerm annotation](https://user-images.githubusercontent.com/924465/64382136-b60ac700-cfe9-11e9-8a35-9682e8dc4b72.png) + + See the [iTerm Proprietary Escape Codes documentation](https://iterm2.com/documentation-escape-codes.html) for more information. + + @param message - The message to display within the annotation. The `|` character is disallowed and will be stripped. + @returns An escape code which will create an annotation when printed in iTerm2. + */ + annotation(message: string, options?: ansiEscapes.AnnotationOptions): string; + }; + + // TODO: remove this in the next major version + default: typeof ansiEscapes; +}; + +export = ansiEscapes; diff --git a/node_modules/ansi-escapes/index.js b/node_modules/ansi-escapes/index.js new file mode 100644 index 0000000..2833318 --- /dev/null +++ b/node_modules/ansi-escapes/index.js @@ -0,0 +1,157 @@ +'use strict'; +const ansiEscapes = module.exports; +// TODO: remove this in the next major version +module.exports.default = ansiEscapes; + +const ESC = '\u001B['; +const OSC = '\u001B]'; +const BEL = '\u0007'; +const SEP = ';'; +const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; + +ansiEscapes.cursorTo = (x, y) => { + if (typeof x !== 'number') { + throw new TypeError('The `x` argument is required'); + } + + if (typeof y !== 'number') { + return ESC + (x + 1) + 'G'; + } + + return ESC + (y + 1) + ';' + (x + 1) + 'H'; +}; + +ansiEscapes.cursorMove = (x, y) => { + if (typeof x !== 'number') { + throw new TypeError('The `x` argument is required'); + } + + let ret = ''; + + if (x < 0) { + ret += ESC + (-x) + 'D'; + } else if (x > 0) { + ret += ESC + x + 'C'; + } + + if (y < 0) { + ret += ESC + (-y) + 'A'; + } else if (y > 0) { + ret += ESC + y + 'B'; + } + + return ret; +}; + +ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A'; +ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B'; +ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C'; +ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D'; + +ansiEscapes.cursorLeft = ESC + 'G'; +ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's'; +ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u'; +ansiEscapes.cursorGetPosition = ESC + '6n'; +ansiEscapes.cursorNextLine = ESC + 'E'; +ansiEscapes.cursorPrevLine = ESC + 'F'; +ansiEscapes.cursorHide = ESC + '?25l'; +ansiEscapes.cursorShow = ESC + '?25h'; + +ansiEscapes.eraseLines = count => { + let clear = ''; + + for (let i = 0; i < count; i++) { + clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : ''); + } + + if (count) { + clear += ansiEscapes.cursorLeft; + } + + return clear; +}; + +ansiEscapes.eraseEndLine = ESC + 'K'; +ansiEscapes.eraseStartLine = ESC + '1K'; +ansiEscapes.eraseLine = ESC + '2K'; +ansiEscapes.eraseDown = ESC + 'J'; +ansiEscapes.eraseUp = ESC + '1J'; +ansiEscapes.eraseScreen = ESC + '2J'; +ansiEscapes.scrollUp = ESC + 'S'; +ansiEscapes.scrollDown = ESC + 'T'; + +ansiEscapes.clearScreen = '\u001Bc'; + +ansiEscapes.clearTerminal = process.platform === 'win32' ? + `${ansiEscapes.eraseScreen}${ESC}0f` : + // 1. Erases the screen (Only done in case `2` is not supported) + // 2. Erases the whole screen including scrollback buffer + // 3. Moves cursor to the top-left position + // More info: https://www.real-world-systems.com/docs/ANSIcode.html + `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`; + +ansiEscapes.beep = BEL; + +ansiEscapes.link = (text, url) => { + return [ + OSC, + '8', + SEP, + SEP, + url, + BEL, + text, + OSC, + '8', + SEP, + SEP, + BEL + ].join(''); +}; + +ansiEscapes.image = (buffer, options = {}) => { + let ret = `${OSC}1337;File=inline=1`; + + if (options.width) { + ret += `;width=${options.width}`; + } + + if (options.height) { + ret += `;height=${options.height}`; + } + + if (options.preserveAspectRatio === false) { + ret += ';preserveAspectRatio=0'; + } + + return ret + ':' + buffer.toString('base64') + BEL; +}; + +ansiEscapes.iTerm = { + setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, + + annotation: (message, options = {}) => { + let ret = `${OSC}1337;`; + + const hasX = typeof options.x !== 'undefined'; + const hasY = typeof options.y !== 'undefined'; + if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) { + throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined'); + } + + message = message.replace(/\|/g, ''); + + ret += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation='; + + if (options.length > 0) { + ret += + (hasX ? + [message, options.length, options.x, options.y] : + [options.length, message]).join('|'); + } else { + ret += message; + } + + return ret + BEL; + } +}; diff --git a/node_modules/ansi-escapes/license b/node_modules/ansi-escapes/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/ansi-escapes/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-escapes/node_modules/type-fest/base.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/base.d.ts new file mode 100644 index 0000000..625a05d --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/base.d.ts @@ -0,0 +1,39 @@ +// Types that are compatible with all supported TypeScript versions. +// It's shared between all TypeScript version-specific definitions. + +// Basic +export * from './source/basic'; +export * from './source/typed-array'; + +// Utilities +export {Except} from './source/except'; +export {Mutable} from './source/mutable'; +export {Merge} from './source/merge'; +export {MergeExclusive} from './source/merge-exclusive'; +export {RequireAtLeastOne} from './source/require-at-least-one'; +export {RequireExactlyOne} from './source/require-exactly-one'; +export {PartialDeep} from './source/partial-deep'; +export {ReadonlyDeep} from './source/readonly-deep'; +export {LiteralUnion} from './source/literal-union'; +export {Promisable} from './source/promisable'; +export {Opaque} from './source/opaque'; +export {SetOptional} from './source/set-optional'; +export {SetRequired} from './source/set-required'; +export {ValueOf} from './source/value-of'; +export {PromiseValue} from './source/promise-value'; +export {AsyncReturnType} from './source/async-return-type'; +export {ConditionalExcept} from './source/conditional-except'; +export {ConditionalKeys} from './source/conditional-keys'; +export {ConditionalPick} from './source/conditional-pick'; +export {UnionToIntersection} from './source/union-to-intersection'; +export {Stringified} from './source/stringified'; +export {FixedLengthArray} from './source/fixed-length-array'; +export {IterableElement} from './source/iterable-element'; +export {Entry} from './source/entry'; +export {Entries} from './source/entries'; +export {SetReturnType} from './source/set-return-type'; +export {Asyncify} from './source/asyncify'; + +// Miscellaneous +export {PackageJson} from './source/package-json'; +export {TsConfigJson} from './source/tsconfig-json'; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/index.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/index.d.ts new file mode 100644 index 0000000..206261c --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/index.d.ts @@ -0,0 +1,2 @@ +// These are all the basic types that's compatible with all supported TypeScript versions. +export * from './base'; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/license b/node_modules/ansi-escapes/node_modules/type-fest/license new file mode 100644 index 0000000..3e4c85a --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https:/sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-escapes/node_modules/type-fest/package.json b/node_modules/ansi-escapes/node_modules/type-fest/package.json new file mode 100644 index 0000000..a0a3718 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/package.json @@ -0,0 +1,58 @@ +{ + "name": "type-fest", + "version": "0.21.3", + "description": "A collection of essential TypeScript types", + "license": "(MIT OR CC0-1.0)", + "repository": "sindresorhus/type-fest", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && tsd && tsc" + }, + "files": [ + "index.d.ts", + "base.d.ts", + "source", + "ts41" + ], + "keywords": [ + "typescript", + "ts", + "types", + "utility", + "util", + "utilities", + "omit", + "merge", + "json" + ], + "devDependencies": { + "@sindresorhus/tsconfig": "~0.7.0", + "expect-type": "^0.11.0", + "tsd": "^0.14.0", + "typescript": "^4.1.3", + "xo": "^0.36.1" + }, + "types": "./index.d.ts", + "typesVersions": { + ">=4.1": { + "*": [ + "ts41/*" + ] + } + }, + "xo": { + "rules": { + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/indent": "off", + "node/no-unsupported-features/es-builtins": "off" + } + } +} diff --git a/node_modules/ansi-escapes/node_modules/type-fest/readme.md b/node_modules/ansi-escapes/node_modules/type-fest/readme.md new file mode 100644 index 0000000..4fae2d3 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/readme.md @@ -0,0 +1,760 @@ +
+
+
+ type-fest +
+
+ A collection of essential TypeScript types +
+
+
+
+
+

+

+ + Sindre Sorhus' open source work is supported by the community + +

+ Special thanks to: +
+
+ + + +

+
+
+
+
+
+
+ +[![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i) +[![npm dependents](https://badgen.net/npm/dependents/type-fest)](https://www.npmjs.com/package/type-fest?activeTab=dependents) [![npm downloads](https://badgen.net/npm/dt/type-fest)](https://www.npmjs.com/package/type-fest) + +Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +Either add this package as a dependency or copy-paste the needed types. No credit required. 👌 + +PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first. + +## Install + +``` +$ npm install type-fest +``` + +*Requires TypeScript >=3.4* + +## Usage + +```ts +import {Except} from 'type-fest'; + +type Foo = { + unicorn: string; + rainbow: boolean; +}; + +type FooWithoutRainbow = Except; +//=> {unicorn: string} +``` + +## API + +Click the type names for complete docs. + +### Basic + +- [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +- [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +- [`TypedArray`](source/typed-array.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +- [`JsonObject`](source/basic.d.ts) - Matches a JSON object. +- [`JsonArray`](source/basic.d.ts) - Matches a JSON array. +- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value. +- [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). + +### Utilities + +- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). +- [`Mutable`](source/mutable.d.ts) - Create a type that strips `readonly` from all or some of an object's keys. The inverse of `Readonly`. +- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type. +- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys. +- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys. +- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more. +- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) if you only need one level deep. +- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) if you only need one level deep. +- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). +- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`. +- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/). +- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional. +- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required. +- [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from. +- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise`. +- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`. +- [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type. +- [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type. +- [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type. +- [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type. +- [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type. +- [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length. +- [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator. +- [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection. +- [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection. +- [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type. +- [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type. + +### Template literal types + +*Note:* These require [TypeScript 4.1 or newer](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#template-literal-types). + +- [`CamelCase`](ts41/camel-case.d.ts) – Convert a string literal to camel-case (`fooBar`). +- [`KebabCase`](ts41/kebab-case.d.ts) – Convert a string literal to kebab-case (`foo-bar`). +- [`PascalCase`](ts41/pascal-case.d.ts) – Converts a string literal to pascal-case (`FooBar`) +- [`SnakeCase`](ts41/snake-case.d.ts) – Convert a string literal to snake-case (`foo_bar`). +- [`DelimiterCase`](ts41/delimiter-case.d.ts) – Convert a string literal to a custom string delimiter casing. +- [`Get`](ts41/get.d.ts) - Get a deeply-nested property from an object using a key path, like [Lodash's `.get()`](https://lodash.com/docs/latest#get) function. + +### Miscellaneous + +- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). +- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7). + +## Declined types + +*If we decline a type addition, we will make sure to document the better solution here.* + +- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The PR author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider. +- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary` vs `Record`) from [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now. +- [`SubType`](https://github.com/sindresorhus/type-fest/issues/22) - The type is powerful, but lacks good use-cases and is prone to misuse. +- [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies. + +## Tips + +### Built-in types + +There are many advanced types most users don't know about. + +- [`Partial`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional. +
+ + Example + + + [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) + + ```ts + interface NodeConfig { + appName: string; + port: number; + } + + class NodeAppBuilder { + private configuration: NodeConfig = { + appName: 'NodeApp', + port: 3000 + }; + + private updateConfig(key: Key, value: NodeConfig[Key]) { + this.configuration[key] = value; + } + + config(config: Partial) { + type NodeConfigKey = keyof NodeConfig; + + for (const key of Object.keys(config) as NodeConfigKey[]) { + const updateValue = config[key]; + + if (updateValue === undefined) { + continue; + } + + this.updateConfig(key, updateValue); + } + + return this; + } + } + + // `Partial`` allows us to provide only a part of the + // NodeConfig interface. + new NodeAppBuilder().config({appName: 'ToDoApp'}); + ``` +
+ +- [`Required`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA) + + ```ts + interface ContactForm { + email?: string; + message?: string; + } + + function submitContactForm(formData: Required) { + // Send the form data to the server. + } + + submitContactForm({ + email: 'ex@mple.com', + message: 'Hi! Could you tell me more about…', + }); + + // TypeScript error: missing property 'message' + submitContactForm({ + email: 'ex@mple.com', + }); + ``` +
+ +- [`Readonly`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA) + + ```ts + enum LogLevel { + Off, + Debug, + Error, + Fatal + }; + + interface LoggerConfig { + name: string; + level: LogLevel; + } + + class Logger { + config: Readonly; + + constructor({name, level}: LoggerConfig) { + this.config = {name, level}; + Object.freeze(this.config); + } + } + + const config: LoggerConfig = { + name: 'MyApp', + level: LogLevel.Debug + }; + + const logger = new Logger(config); + + // TypeScript Error: cannot assign to read-only property. + logger.config.level = LogLevel.Error; + + // We are able to edit config variable as we please. + config.level = LogLevel.Error; + ``` +
+ +- [`Pick`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1422-L1427) - From `T`, pick a set of properties whose keys are in the union `K`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA) + + ```ts + interface Article { + title: string; + thumbnail: string; + content: string; + } + + // Creates new type out of the `Article` interface composed + // from the Articles' two properties: `title` and `thumbnail`. + // `ArticlePreview = {title: string; thumbnail: string}` + type ArticlePreview = Pick; + + // Render a list of articles using only title and description. + function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement { + const articles = document.createElement('div'); + + for (const preview of previews) { + // Append preview to the articles. + } + + return articles; + } + + const articles = renderArticlePreviews([ + { + title: 'TypeScript tutorial!', + thumbnail: '/assets/ts.jpg' + } + ]); + ``` +
+ +- [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434) - Construct a type with a set of properties `K` of type `T`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA) + + ```ts + // Positions of employees in our company. + type MemberPosition = 'intern' | 'developer' | 'tech-lead'; + + // Interface describing properties of a single employee. + interface Employee { + firstName: string; + lastName: string; + yearsOfExperience: number; + } + + // Create an object that has all possible `MemberPosition` values set as keys. + // Those keys will store a collection of Employees of the same position. + const team: Record = { + intern: [], + developer: [], + 'tech-lead': [], + }; + + // Our team has decided to help John with his dream of becoming Software Developer. + team.intern.push({ + firstName: 'John', + lastName: 'Doe', + yearsOfExperience: 0 + }); + + // `Record` forces you to initialize all of the property keys. + // TypeScript Error: "tech-lead" property is missing + const teamEmpty: Record = { + intern: null, + developer: null, + }; + ``` +
+ +- [`Exclude`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1436-L1439) - Exclude from `T` those types that are assignable to `U`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) + + ```ts + interface ServerConfig { + port: null | string | number; + } + + type RequestHandler = (request: Request, response: Response) => void; + + // Exclude `null` type from `null | string | number`. + // In case the port is equal to `null`, we will use default value. + function getPortValue(port: Exclude): number { + if (typeof port === 'string') { + return parseInt(port, 10); + } + + return port; + } + + function startServer(handler: RequestHandler, config: ServerConfig): void { + const server = require('http').createServer(handler); + + const port = config.port === null ? 3000 : getPortValue(config.port); + server.listen(port); + } + ``` +
+ +- [`Extract`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1441-L1444) - Extract from `T` those types that are assignable to `U`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA) + + ```ts + declare function uniqueId(): number; + + const ID = Symbol('ID'); + + interface Person { + [ID]: number; + name: string; + age: number; + } + + // Allows changing the person data as long as the property key is of string type. + function changePersonData< + Obj extends Person, + Key extends Extract, + Value extends Obj[Key] + > (obj: Obj, key: Key, value: Value): void { + obj[key] = value; + } + + // Tiny Andrew was born. + const andrew = { + [ID]: uniqueId(), + name: 'Andrew', + age: 0, + }; + + // Cool, we're fine with that. + changePersonData(andrew, 'name', 'Pony'); + + // Goverment didn't like the fact that you wanted to change your identity. + changePersonData(andrew, ID, uniqueId()); + ``` +
+ +- [`NonNullable`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`. +
+ + Example + + Works with strictNullChecks set to true. (Read more here) + + [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) + + ```ts + type PortNumber = string | number | null; + + /** Part of a class definition that is used to build a server */ + class ServerBuilder { + portNumber!: NonNullable; + + port(this: ServerBuilder, port: PortNumber): ServerBuilder { + if (port == null) { + this.portNumber = 8000; + } else { + this.portNumber = port; + } + + return this; + } + } + + const serverBuilder = new ServerBuilder(); + + serverBuilder + .port('8000') // portNumber = '8000' + .port(null) // portNumber = 8000 + .port(3000); // portNumber = 3000 + + // TypeScript error + serverBuilder.portNumber = null; + ``` +
+ +- [`Parameters`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1451-L1454) - Obtain the parameters of a function type in a tuple. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA) + + ```ts + function shuffle(input: any[]): void { + // Mutate array randomly changing its' elements indexes. + } + + function callNTimes any> (func: Fn, callCount: number) { + // Type that represents the type of the received function parameters. + type FunctionParameters = Parameters; + + return function (...args: FunctionParameters) { + for (let i = 0; i < callCount; i++) { + func(...args); + } + } + } + + const shuffleTwice = callNTimes(shuffle, 2); + ``` +
+ +- [`ConstructorParameters`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1456-L1459) - Obtain the parameters of a constructor function type in a tuple. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA) + + ```ts + class ArticleModel { + title: string; + content?: string; + + constructor(title: string) { + this.title = title; + } + } + + class InstanceCache any)> { + private ClassConstructor: T; + private cache: Map> = new Map(); + + constructor (ctr: T) { + this.ClassConstructor = ctr; + } + + getInstance (...args: ConstructorParameters): InstanceType { + const hash = this.calculateArgumentsHash(...args); + + const existingInstance = this.cache.get(hash); + if (existingInstance !== undefined) { + return existingInstance; + } + + return new this.ClassConstructor(...args); + } + + private calculateArgumentsHash(...args: any[]): string { + // Calculate hash. + return 'hash'; + } + } + + const articleCache = new InstanceCache(ArticleModel); + const amazonArticle = articleCache.getInstance('Amazon forests burining!'); + ``` +
+ +- [`ReturnType`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) – Obtain the return type of a function type. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + + ```ts + /** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */ + function mapIter< + Elem, + Func extends (elem: Elem) => any, + Ret extends ReturnType + >(iter: Iterable, callback: Func): Ret[] { + const mapped: Ret[] = []; + + for (const elem of iter) { + mapped.push(callback(elem)); + } + + return mapped; + } + + const setObject: Set = new Set(); + const mapObject: Map = new Map(); + + mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[] + + mapIter(mapObject, ([key, value]: [number, string]) => { + return key % 2 === 0 ? value : 'Odd'; + }); // string[] + ``` +
+ +- [`InstanceType`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1466-L1469) – Obtain the instance type of a constructor function type. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + + ```ts + class IdleService { + doNothing (): void {} + } + + class News { + title: string; + content: string; + + constructor(title: string, content: string) { + this.title = title; + this.content = content; + } + } + + const instanceCounter: Map = new Map(); + + interface Constructor { + new(...args: any[]): any; + } + + // Keep track how many instances of `Constr` constructor have been created. + function getInstance< + Constr extends Constructor, + Args extends ConstructorParameters + >(constructor: Constr, ...args: Args): InstanceType { + let count = instanceCounter.get(constructor) || 0; + + const instance = new constructor(...args); + + instanceCounter.set(constructor, count + 1); + + console.log(`Created ${count + 1} instances of ${Constr.name} class`); + + return instance; + } + + + const idleService = getInstance(IdleService); + // Will log: `Created 1 instances of IdleService class` + const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...'); + // Will log: `Created 1 instances of News class` + ``` +
+ +- [`Omit`](https://github.com/microsoft/TypeScript/blob/71af02f7459dc812e85ac31365bfe23daf14b4e4/src/lib/es5.d.ts#L1446) – Constructs a type by picking all properties from T and then removing K. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA) + + ```ts + interface Animal { + imageUrl: string; + species: string; + images: string[]; + paragraphs: string[]; + } + + // Creates new type with all properties of the `Animal` interface + // except 'images' and 'paragraphs' properties. We can use this + // type to render small hover tooltip for a wiki entry list. + type AnimalShortInfo = Omit; + + function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement { + const container = document.createElement('div'); + // Internal implementation. + return container; + } + ``` +
+ +- [`Uppercase`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types) - Transforms every character in a string into uppercase. +
+ + Example + + + ```ts + type T = Uppercase<'hello'>; // 'HELLO' + + type T2 = Uppercase<'foo' | 'bar'>; // 'FOO' | 'BAR' + + type T3 = Uppercase<`aB${S}`>; + type T4 = T30<'xYz'>; // 'ABXYZ' + + type T5 = Uppercase; // string + type T6 = Uppercase; // any + type T7 = Uppercase; // never + type T8 = Uppercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
+ +- [`Lowercase`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types) - Transforms every character in a string into lowercase. +
+ + Example + + + ```ts + type T = Lowercase<'HELLO'>; // 'hello' + + type T2 = Lowercase<'FOO' | 'BAR'>; // 'foo' | 'bar' + + type T3 = Lowercase<`aB${S}`>; + type T4 = T32<'xYz'>; // 'abxyz' + + type T5 = Lowercase; // string + type T6 = Lowercase; // any + type T7 = Lowercase; // never + type T8 = Lowercase<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
+ +- [`Capitalize`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types) - Transforms the first character in a string into uppercase. +
+ + Example + + + ```ts + type T = Capitalize<'hello'>; // 'Hello' + + type T2 = Capitalize<'foo' | 'bar'>; // 'Foo' | 'Bar' + + type T3 = Capitalize<`aB${S}`>; + type T4 = T32<'xYz'>; // 'ABxYz' + + type T5 = Capitalize; // string + type T6 = Capitalize; // any + type T7 = Capitalize; // never + type T8 = Capitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
+ +- [`Uncapitalize`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#template-literal-types) - Transforms the first character in a string into lowercase. +
+ + Example + + + ```ts + type T = Uncapitalize<'Hello'>; // 'hello' + + type T2 = Uncapitalize<'Foo' | 'Bar'>; // 'foo' | 'bar' + + type T3 = Uncapitalize<`AB${S}`>; + type T4 = T30<'xYz'>; // 'aBxYz' + + type T5 = Uncapitalize; // string + type T6 = Uncapitalize; // any + type T7 = Uncapitalize; // never + type T8 = Uncapitalize<42>; // Error, type 'number' does not satisfy the constraint 'string' + ``` +
+ +You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types). + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Jarek Radosz](https://github.com/CvX) +- [Dimitri Benin](https://github.com/BendingBender) +- [Pelle Wessman](https://github.com/voxpelli) + +## License + +(MIT OR CC0-1.0) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/async-return-type.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/async-return-type.d.ts new file mode 100644 index 0000000..79ec1e9 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/async-return-type.d.ts @@ -0,0 +1,23 @@ +import {PromiseValue} from './promise-value'; + +type AsyncFunction = (...args: any[]) => Promise; + +/** +Unwrap the return type of a function that returns a `Promise`. + +There has been [discussion](https://github.com/microsoft/TypeScript/pull/35998) about implementing this type in TypeScript. + +@example +```ts +import {AsyncReturnType} from 'type-fest'; +import {asyncFunction} from 'api'; + +// This type resolves to the unwrapped return type of `asyncFunction`. +type Value = AsyncReturnType; + +async function doSomething(value: Value) {} + +asyncFunction().then(value => doSomething(value)); +``` +*/ +export type AsyncReturnType = PromiseValue>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/asyncify.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/asyncify.d.ts new file mode 100644 index 0000000..455f2eb --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/asyncify.d.ts @@ -0,0 +1,31 @@ +import {PromiseValue} from './promise-value'; +import {SetReturnType} from './set-return-type'; + +/** +Create an async version of the given function type, by boxing the return type in `Promise` while keeping the same parameter types. + +Use-case: You have two functions, one synchronous and one asynchronous that do the same thing. Instead of having to duplicate the type definition, you can use `Asyncify` to reuse the synchronous type. + +@example +``` +import {Asyncify} from 'type-fest'; + +// Synchronous function. +function getFooSync(someArg: SomeType): Foo { + // … +} + +type AsyncifiedFooGetter = Asyncify; +//=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise; + +// Same as `getFooSync` but asynchronous. +const getFooAsync: AsyncifiedFooGetter = (someArg) => { + // TypeScript now knows that `someArg` is `SomeType` automatically. + // It also knows that this function must return `Promise`. + // If you have `@typescript-eslint/promise-function-async` linter rule enabled, it will even report that "Functions that return promises must be async.". + + // … +} +``` +*/ +export type Asyncify any> = SetReturnType>>>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/basic.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/basic.d.ts new file mode 100644 index 0000000..f6fba38 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/basic.d.ts @@ -0,0 +1,51 @@ +/// + +// TODO: This can just be `export type Primitive = not object` when the `not` keyword is out. +/** +Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +*/ +export type Primitive = + | null + | undefined + | string + | number + | boolean + | symbol + | bigint; + +// TODO: Remove the `= unknown` sometime in the future when most users are on TS 3.5 as it's now the default +/** +Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +*/ +export type Class = new(...arguments_: Arguments) => T; + +/** +Matches a JSON object. + +This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. +*/ +export type JsonObject = {[Key in string]?: JsonValue}; + +/** +Matches a JSON array. +*/ +export interface JsonArray extends Array {} + +/** +Matches any valid JSON value. +*/ +export type JsonValue = string | number | boolean | null | JsonObject | JsonArray; + +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} + +/** +Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). +*/ +export interface ObservableLike { + subscribe(observer: (value: unknown) => void): void; + [Symbol.observable](): ObservableLike; +} diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-except.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-except.d.ts new file mode 100644 index 0000000..ac506cc --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-except.d.ts @@ -0,0 +1,43 @@ +import {Except} from './except'; +import {ConditionalKeys} from './conditional-keys'; + +/** +Exclude keys from a shape that matches the given `Condition`. + +This is useful when you want to create a new type with a specific set of keys from a shape. For example, you might want to exclude all the primitive properties from a class and form a new shape containing everything but the primitive properties. + +@example +``` +import {Primitive, ConditionalExcept} from 'type-fest'; + +class Awesome { + name: string; + successes: number; + failures: bigint; + + run() {} +} + +type ExceptPrimitivesFromAwesome = ConditionalExcept; +//=> {run: () => void} +``` + +@example +``` +import {ConditionalExcept} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c: () => void; + d: {}; +} + +type NonStringKeysOnly = ConditionalExcept; +//=> {b: string | number; c: () => void; d: {}} +``` +*/ +export type ConditionalExcept = Except< + Base, + ConditionalKeys +>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-keys.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-keys.d.ts new file mode 100644 index 0000000..eb074dc --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-keys.d.ts @@ -0,0 +1,43 @@ +/** +Extract the keys from a type where the value type of the key extends the given `Condition`. + +Internally this is used for the `ConditionalPick` and `ConditionalExcept` types. + +@example +``` +import {ConditionalKeys} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c?: string; + d: {}; +} + +type StringKeysOnly = ConditionalKeys; +//=> 'a' +``` + +To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below. + +@example +``` +type StringKeysAndUndefined = ConditionalKeys; +//=> 'a' | 'c' +``` +*/ +export type ConditionalKeys = NonNullable< + // Wrap in `NonNullable` to strip away the `undefined` type from the produced union. + { + // Map through all the keys of the given base type. + [Key in keyof Base]: + // Pick only keys with types extending the given `Condition` type. + Base[Key] extends Condition + // Retain this key since the condition passes. + ? Key + // Discard this key since the condition fails. + : never; + + // Convert the produced object into a union type of the keys which passed the conditional test. + }[keyof Base] +>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-pick.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-pick.d.ts new file mode 100644 index 0000000..cecc3df --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/conditional-pick.d.ts @@ -0,0 +1,42 @@ +import {ConditionalKeys} from './conditional-keys'; + +/** +Pick keys from the shape that matches the given `Condition`. + +This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type. + +@example +``` +import {Primitive, ConditionalPick} from 'type-fest'; + +class Awesome { + name: string; + successes: number; + failures: bigint; + + run() {} +} + +type PickPrimitivesFromAwesome = ConditionalPick; +//=> {name: string; successes: number; failures: bigint} +``` + +@example +``` +import {ConditionalPick} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c: () => void; + d: {}; +} + +type StringKeysOnly = ConditionalPick; +//=> {a: string} +``` +*/ +export type ConditionalPick = Pick< + Base, + ConditionalKeys +>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/entries.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/entries.d.ts new file mode 100644 index 0000000..e02237a --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/entries.d.ts @@ -0,0 +1,57 @@ +import {ArrayEntry, MapEntry, ObjectEntry, SetEntry} from './entry'; + +type ArrayEntries = Array>; +type MapEntries = Array>; +type ObjectEntries = Array>; +type SetEntries> = Array>; + +/** +Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries. + +For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. + +@see `Entry` if you want to just access the type of a single entry. + +@example +``` +import {Entries} from 'type-fest'; + +interface Example { + someKey: number; +} + +const manipulatesEntries = (examples: Entries) => examples.map(example => [ + // Does some arbitrary processing on the key (with type information available) + example[0].toUpperCase(), + + // Does some arbitrary processing on the value (with type information available) + example[1].toFixed() +]); + +const example: Example = {someKey: 1}; +const entries = Object.entries(example) as Entries; +const output = manipulatesEntries(entries); + +// Objects +const objectExample = {a: 1}; +const objectEntries: Entries = [['a', 1]]; + +// Arrays +const arrayExample = ['a', 1]; +const arrayEntries: Entries = [[0, 'a'], [1, 1]]; + +// Maps +const mapExample = new Map([['a', 1]]); +const mapEntries: Entries = [['a', 1]]; + +// Sets +const setExample = new Set(['a', 1]); +const setEntries: Entries = [['a', 'a'], [1, 1]]; +``` +*/ +export type Entries = + BaseType extends Map ? MapEntries + : BaseType extends Set ? SetEntries + : BaseType extends unknown[] ? ArrayEntries + : BaseType extends object ? ObjectEntries + : never; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/entry.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/entry.d.ts new file mode 100644 index 0000000..db71821 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/entry.d.ts @@ -0,0 +1,60 @@ +type MapKey = BaseType extends Map ? KeyType : never; +type MapValue = BaseType extends Map ? ValueType : never; + +export type ArrayEntry = [number, BaseType[number]]; +export type MapEntry = [MapKey, MapValue]; +export type ObjectEntry = [keyof BaseType, BaseType[keyof BaseType]]; +export type SetEntry = BaseType extends Set ? [ItemType, ItemType] : never; + +/** +Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entry` type will return the type of that collection's entry. + +For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. + +@see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method). + +@example +``` +import {Entry} from 'type-fest'; + +interface Example { + someKey: number; +} + +const manipulatesEntry = (example: Entry) => [ + // Does some arbitrary processing on the key (with type information available) + example[0].toUpperCase(), + + // Does some arbitrary processing on the value (with type information available) + example[1].toFixed(), +]; + +const example: Example = {someKey: 1}; +const entry = Object.entries(example)[0] as Entry; +const output = manipulatesEntry(entry); + +// Objects +const objectExample = {a: 1}; +const objectEntry: Entry = ['a', 1]; + +// Arrays +const arrayExample = ['a', 1]; +const arrayEntryString: Entry = [0, 'a']; +const arrayEntryNumber: Entry = [1, 1]; + +// Maps +const mapExample = new Map([['a', 1]]); +const mapEntry: Entry = ['a', 1]; + +// Sets +const setExample = new Set(['a', 1]); +const setEntryString: Entry = ['a', 'a']; +const setEntryNumber: Entry = [1, 1]; +``` +*/ +export type Entry = + BaseType extends Map ? MapEntry + : BaseType extends Set ? SetEntry + : BaseType extends unknown[] ? ArrayEntry + : BaseType extends object ? ObjectEntry + : never; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/except.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/except.d.ts new file mode 100644 index 0000000..7dedbaa --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/except.d.ts @@ -0,0 +1,22 @@ +/** +Create a type from an object type without certain keys. + +This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/30825) if you want to have the stricter version as a built-in in TypeScript. + +@example +``` +import {Except} from 'type-fest'; + +type Foo = { + a: number; + b: string; + c: boolean; +}; + +type FooWithoutA = Except; +//=> {b: string}; +``` +*/ +export type Except = Pick>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/fixed-length-array.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/fixed-length-array.d.ts new file mode 100644 index 0000000..e3bc0f4 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/fixed-length-array.d.ts @@ -0,0 +1,38 @@ +/** +Methods to exclude. +*/ +type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'; + +/** +Create a type that represents an array of the given type and length. The array's length and the `Array` prototype methods that manipulate its length are excluded in the resulting type. + +Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similiar type built into TypeScript. + +Use-cases: +- Declaring fixed-length tuples or arrays with a large number of items. +- Creating a range union (for example, `0 | 1 | 2 | 3 | 4` from the keys of such a type) without having to resort to recursive types. +- Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector. + +@example +``` +import {FixedLengthArray} from 'type-fest'; + +type FencingTeam = FixedLengthArray; + +const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert']; + +const homeFencingTeam: FencingTeam = ['George', 'John']; +//=> error TS2322: Type string[] is not assignable to type 'FencingTeam' + +guestFencingTeam.push('Sam'); +//=> error TS2339: Property 'push' does not exist on type 'FencingTeam' +``` +*/ +export type FixedLengthArray = Pick< + ArrayPrototype, + Exclude +> & { + [index: number]: Element; + [Symbol.iterator]: () => IterableIterator; + readonly length: Length; +}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/iterable-element.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/iterable-element.d.ts new file mode 100644 index 0000000..174cfbf --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/iterable-element.d.ts @@ -0,0 +1,46 @@ +/** +Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator. + +This can be useful, for example, if you want to get the type that is yielded in a generator function. Often the return type of those functions are not specified. + +This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators. + +Here is an example of `IterableElement` in action with a generator function: + +@example +``` +function * iAmGenerator() { + yield 1; + yield 2; +} + +type MeNumber = IterableElement> +``` + +And here is an example with an async generator: + +@example +``` +async function * iAmGeneratorAsync() { + yield 'hi'; + yield true; +} + +type MeStringOrBoolean = IterableElement> +``` + +Many types in JavaScript/TypeScript are iterables. This type works on all types that implement those interfaces. For example, `Array`, `Set`, `Map`, `stream.Readable`, etc. + +An example with an array of strings: + +@example +``` +type MeString = IterableElement +``` +*/ +export type IterableElement = + TargetIterable extends Iterable ? + ElementType : + TargetIterable extends AsyncIterable ? + ElementType : + never; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/literal-union.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/literal-union.d.ts new file mode 100644 index 0000000..8debd93 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/literal-union.d.ts @@ -0,0 +1,33 @@ +import {Primitive} from './basic'; + +/** +Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. + +Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. + +This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. + +@example +``` +import {LiteralUnion} from 'type-fest'; + +// Before + +type Pet = 'dog' | 'cat' | string; + +const pet: Pet = ''; +// Start typing in your TypeScript-enabled IDE. +// You **will not** get auto-completion for `dog` and `cat` literals. + +// After + +type Pet2 = LiteralUnion<'dog' | 'cat', string>; + +const pet: Pet2 = ''; +// You **will** get auto-completion for `dog` and `cat` literals. +``` + */ +export type LiteralUnion< + LiteralType, + BaseType extends Primitive +> = LiteralType | (BaseType & {_?: never}); diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/merge-exclusive.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/merge-exclusive.d.ts new file mode 100644 index 0000000..059bd2c --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/merge-exclusive.d.ts @@ -0,0 +1,39 @@ +// Helper type. Not useful on its own. +type Without = {[KeyType in Exclude]?: never}; + +/** +Create a type that has mutually exclusive keys. + +This type was inspired by [this comment](https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-373782604). + +This type works with a helper type, called `Without`. `Without` produces a type that has only keys from `FirstType` which are not present on `SecondType` and sets the value type for these keys to `never`. This helper type is then used in `MergeExclusive` to remove keys from either `FirstType` or `SecondType`. + +@example +``` +import {MergeExclusive} from 'type-fest'; + +interface ExclusiveVariation1 { + exclusive1: boolean; +} + +interface ExclusiveVariation2 { + exclusive2: string; +} + +type ExclusiveOptions = MergeExclusive; + +let exclusiveOptions: ExclusiveOptions; + +exclusiveOptions = {exclusive1: true}; +//=> Works +exclusiveOptions = {exclusive2: 'hi'}; +//=> Works +exclusiveOptions = {exclusive1: true, exclusive2: 'hi'}; +//=> Error +``` +*/ +export type MergeExclusive = + (FirstType | SecondType) extends object ? + (Without & SecondType) | (Without & FirstType) : + FirstType | SecondType; + diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/merge.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/merge.d.ts new file mode 100644 index 0000000..695cb95 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/merge.d.ts @@ -0,0 +1,25 @@ +import {Except} from './except'; +import {Simplify} from './simplify'; + +type Merge_ = Except> & SecondType; + +/** +Merge two types into a new type. Keys of the second type overrides keys of the first type. + +@example +``` +import {Merge} from 'type-fest'; + +type Foo = { + a: number; + b: string; +}; + +type Bar = { + b: number; +}; + +const ab: Merge = {a: 1, b: 2}; +``` +*/ +export type Merge = Simplify>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/mutable.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/mutable.d.ts new file mode 100644 index 0000000..a465d41 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/mutable.d.ts @@ -0,0 +1,38 @@ +import {Except} from './except'; +import {Simplify} from './simplify'; + +/** +Create a type that strips `readonly` from all or some of an object's keys. Inverse of `Readonly`. + +This can be used to [store and mutate options within a class](https://github.com/sindresorhus/pageres/blob/4a5d05fca19a5fbd2f53842cbf3eb7b1b63bddd2/source/index.ts#L72), [edit `readonly` objects within tests](https://stackoverflow.com/questions/50703834), [construct a `readonly` object within a function](https://github.com/Microsoft/TypeScript/issues/24509), or to define a single model where the only thing that changes is whether or not some of the keys are mutable. + +@example +``` +import {Mutable} from 'type-fest'; + +type Foo = { + readonly a: number; + readonly b: readonly string[]; // To show that only the mutability status of the properties, not their values, are affected. + readonly c: boolean; +}; + +const mutableFoo: Mutable = {a: 1, b: ['2']}; +mutableFoo.a = 3; +mutableFoo.b[0] = 'new value'; // Will still fail as the value of property "b" is still a readonly type. +mutableFoo.b = ['something']; // Will work as the "b" property itself is no longer readonly. + +type SomeMutable = Mutable; +// type SomeMutable = { +// readonly a: number; +// b: readonly string[]; // It's now mutable. The type of the property remains unaffected. +// c: boolean; // It's now mutable. +// } +``` +*/ +export type Mutable = + Simplify< + // Pick just the keys that are not mutable from the base type. + Except & + // Pick the keys that should be mutable from the base type and make them mutable by removing the `readonly` modifier from the key. + {-readonly [KeyType in keyof Pick]: Pick[KeyType]} + >; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/opaque.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/opaque.d.ts new file mode 100644 index 0000000..20ab964 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/opaque.d.ts @@ -0,0 +1,65 @@ +/** +Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly. + +The generic type parameter can be anything. It doesn't have to be an object. + +[Read more about opaque types.](https://codemix.com/opaque-types-in-javascript/) + +There have been several discussions about adding this feature to TypeScript via the `opaque type` operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward: + - [Microsoft/TypeScript#15408](https://github.com/Microsoft/TypeScript/issues/15408) + - [Microsoft/TypeScript#15807](https://github.com/Microsoft/TypeScript/issues/15807) + +@example +``` +import {Opaque} from 'type-fest'; + +type AccountNumber = Opaque; +type AccountBalance = Opaque; + +// The Token parameter allows the compiler to differentiate between types, whereas "unknown" will not. For example, consider the following structures: +type ThingOne = Opaque; +type ThingTwo = Opaque; + +// To the compiler, these types are allowed to be cast to each other as they have the same underlying type. They are both `string & { __opaque__: unknown }`. +// To avoid this behaviour, you would instead pass the "Token" parameter, like so. +type NewThingOne = Opaque; +type NewThingTwo = Opaque; + +// Now they're completely separate types, so the following will fail to compile. +function createNewThingOne (): NewThingOne { + // As you can see, casting from a string is still allowed. However, you may not cast NewThingOne to NewThingTwo, and vice versa. + return 'new thing one' as NewThingOne; +} + +// This will fail to compile, as they are fundamentally different types. +const thingTwo = createNewThingOne() as NewThingTwo; + +// Here's another example of opaque typing. +function createAccountNumber(): AccountNumber { + return 2 as AccountNumber; +} + +function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance { + return 4 as AccountBalance; +} + +// This will compile successfully. +getMoneyForAccount(createAccountNumber()); + +// But this won't, because it has to be explicitly passed as an `AccountNumber` type. +getMoneyForAccount(2); + +// You can use opaque values like they aren't opaque too. +const accountNumber = createAccountNumber(); + +// This will not compile successfully. +const newAccountNumber = accountNumber + 2; + +// As a side note, you can (and should) use recursive types for your opaque types to make them stronger and hopefully easier to type. +type Person = { + id: Opaque; + name: string; +}; +``` +*/ +export type Opaque = Type & {readonly __opaque__: Token}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/package-json.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/package-json.d.ts new file mode 100644 index 0000000..cf355d0 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/package-json.d.ts @@ -0,0 +1,611 @@ +import {LiteralUnion} from './literal-union'; + +declare namespace PackageJson { + /** + A person who has been involved in creating or maintaining the package. + */ + export type Person = + | string + | { + name: string; + url?: string; + email?: string; + }; + + export type BugsLocation = + | string + | { + /** + The URL to the package's issue tracker. + */ + url?: string; + + /** + The email address to which issues should be reported. + */ + email?: string; + }; + + export interface DirectoryLocations { + [directoryType: string]: unknown; + + /** + Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. + */ + bin?: string; + + /** + Location for Markdown files. + */ + doc?: string; + + /** + Location for example scripts. + */ + example?: string; + + /** + Location for the bulk of the library. + */ + lib?: string; + + /** + Location for man pages. Sugar to generate a `man` array by walking the folder. + */ + man?: string; + + /** + Location for test files. + */ + test?: string; + } + + export type Scripts = { + /** + Run **before** the package is published (Also run on local `npm install` without any arguments). + */ + prepublish?: string; + + /** + Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. + */ + prepare?: string; + + /** + Run **before** the package is prepared and packed, **only** on `npm publish`. + */ + prepublishOnly?: string; + + /** + Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). + */ + prepack?: string; + + /** + Run **after** the tarball has been generated and moved to its final destination. + */ + postpack?: string; + + /** + Run **after** the package is published. + */ + publish?: string; + + /** + Run **after** the package is published. + */ + postpublish?: string; + + /** + Run **before** the package is installed. + */ + preinstall?: string; + + /** + Run **after** the package is installed. + */ + install?: string; + + /** + Run **after** the package is installed and after `install`. + */ + postinstall?: string; + + /** + Run **before** the package is uninstalled and before `uninstall`. + */ + preuninstall?: string; + + /** + Run **before** the package is uninstalled. + */ + uninstall?: string; + + /** + Run **after** the package is uninstalled. + */ + postuninstall?: string; + + /** + Run **before** bump the package version and before `version`. + */ + preversion?: string; + + /** + Run **before** bump the package version. + */ + version?: string; + + /** + Run **after** bump the package version. + */ + postversion?: string; + + /** + Run with the `npm test` command, before `test`. + */ + pretest?: string; + + /** + Run with the `npm test` command. + */ + test?: string; + + /** + Run with the `npm test` command, after `test`. + */ + posttest?: string; + + /** + Run with the `npm stop` command, before `stop`. + */ + prestop?: string; + + /** + Run with the `npm stop` command. + */ + stop?: string; + + /** + Run with the `npm stop` command, after `stop`. + */ + poststop?: string; + + /** + Run with the `npm start` command, before `start`. + */ + prestart?: string; + + /** + Run with the `npm start` command. + */ + start?: string; + + /** + Run with the `npm start` command, after `start`. + */ + poststart?: string; + + /** + Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + prerestart?: string; + + /** + Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + restart?: string; + + /** + Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + postrestart?: string; + } & Record; + + /** + Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. + */ + export type Dependency = Record; + + /** + Conditions which provide a way to resolve a package entry point based on the environment. + */ + export type ExportCondition = LiteralUnion< + | 'import' + | 'require' + | 'node' + | 'deno' + | 'browser' + | 'electron' + | 'react-native' + | 'default', + string + >; + + /** + Entry points of a module, optionally with conditions and subpath exports. + */ + export type Exports = + | string + | {[key in ExportCondition]: Exports} + | {[key: string]: Exports}; // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + + export interface NonStandardEntryPoints { + /** + An ECMAScript module ID that is the primary entry point to the program. + */ + module?: string; + + /** + A module ID with untranspiled code that is the primary entry point to the program. + */ + esnext?: + | string + | { + [moduleName: string]: string | undefined; + main?: string; + browser?: string; + }; + + /** + A hint to JavaScript bundlers or component tools when packaging modules for client side use. + */ + browser?: + | string + | Record; + + /** + Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. + + [Read more.](https://webpack.js.org/guides/tree-shaking/) + */ + sideEffects?: boolean | string[]; + } + + export interface TypeScriptConfiguration { + /** + Location of the bundled TypeScript declaration file. + */ + types?: string; + + /** + Location of the bundled TypeScript declaration file. Alias of `types`. + */ + typings?: string; + } + + /** + An alternative configuration for Yarn workspaces. + */ + export interface WorkspaceConfig { + /** + An array of workspace pattern strings which contain the workspace packages. + */ + packages?: WorkspacePattern[]; + + /** + Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. + + [Read more](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) + */ + nohoist?: WorkspacePattern[]; + } + + /** + A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. + + The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). + + @example + `docs` → Include the docs directory and install its dependencies. + `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. + */ + type WorkspacePattern = string; + + export interface YarnConfiguration { + /** + Used to configure [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). + + Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run `yarn install` once to install all of them in a single pass. + + Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. + */ + workspaces?: WorkspacePattern[] | WorkspaceConfig; + + /** + If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. + + Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. + */ + flat?: boolean; + + /** + Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. + */ + resolutions?: Dependency; + } + + export interface JSPMConfiguration { + /** + JSPM configuration. + */ + jspm?: PackageJson; + } + + /** + Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. + */ + export interface PackageJsonStandard { + /** + The name of the package. + */ + name?: string; + + /** + Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). + */ + version?: string; + + /** + Package description, listed in `npm search`. + */ + description?: string; + + /** + Keywords associated with package, listed in `npm search`. + */ + keywords?: string[]; + + /** + The URL to the package's homepage. + */ + homepage?: LiteralUnion<'.', string>; + + /** + The URL to the package's issue tracker and/or the email address to which issues should be reported. + */ + bugs?: BugsLocation; + + /** + The license for the package. + */ + license?: string; + + /** + The licenses for the package. + */ + licenses?: Array<{ + type?: string; + url?: string; + }>; + + author?: Person; + + /** + A list of people who contributed to the package. + */ + contributors?: Person[]; + + /** + A list of people who maintain the package. + */ + maintainers?: Person[]; + + /** + The files included in the package. + */ + files?: string[]; + + /** + Resolution algorithm for importing ".js" files from the package's scope. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) + */ + type?: 'module' | 'commonjs'; + + /** + The module ID that is the primary entry point to the program. + */ + main?: string; + + /** + Standard entry points of the package, with enhanced support for ECMAScript Modules. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_entry_points) + */ + exports?: Exports; + + /** + The executable files that should be installed into the `PATH`. + */ + bin?: + | string + | Record; + + /** + Filenames to put in place for the `man` program to find. + */ + man?: string | string[]; + + /** + Indicates the structure of the package. + */ + directories?: DirectoryLocations; + + /** + Location for the code repository. + */ + repository?: + | string + | { + type: string; + url: string; + + /** + Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). + + [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) + */ + directory?: string; + }; + + /** + Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. + */ + scripts?: Scripts; + + /** + Is used to set configuration parameters used in package scripts that persist across upgrades. + */ + config?: Record; + + /** + The dependencies of the package. + */ + dependencies?: Dependency; + + /** + Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. + */ + devDependencies?: Dependency; + + /** + Dependencies that are skipped if they fail to install. + */ + optionalDependencies?: Dependency; + + /** + Dependencies that will usually be required by the package user directly or via another dependency. + */ + peerDependencies?: Dependency; + + /** + Indicate peer dependencies that are optional. + */ + peerDependenciesMeta?: Record; + + /** + Package names that are bundled when the package is published. + */ + bundledDependencies?: string[]; + + /** + Alias of `bundledDependencies`. + */ + bundleDependencies?: string[]; + + /** + Engines that this package runs on. + */ + engines?: { + [EngineName in 'npm' | 'node' | string]: string; + }; + + /** + @deprecated + */ + engineStrict?: boolean; + + /** + Operating systems the module runs on. + */ + os?: Array>; + + /** + CPU architectures the module runs on. + */ + cpu?: Array>; + + /** + If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. + + @deprecated + */ + preferGlobal?: boolean; + + /** + If set to `true`, then npm will refuse to publish it. + */ + private?: boolean; + + /** + A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. + */ + publishConfig?: Record; + + /** + Describes and notifies consumers of a package's monetary support information. + + [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) + */ + funding?: string | { + /** + The type of funding. + */ + type?: LiteralUnion< + | 'github' + | 'opencollective' + | 'patreon' + | 'individual' + | 'foundation' + | 'corporation', + string + >; + + /** + The URL to the funding page. + */ + url: string; + }; + } +} + +/** +Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. +*/ +export type PackageJson = +PackageJson.PackageJsonStandard & +PackageJson.NonStandardEntryPoints & +PackageJson.TypeScriptConfiguration & +PackageJson.YarnConfiguration & +PackageJson.JSPMConfiguration; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/partial-deep.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/partial-deep.d.ts new file mode 100644 index 0000000..b962b84 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/partial-deep.d.ts @@ -0,0 +1,72 @@ +import {Primitive} from './basic'; + +/** +Create a type from another type with all keys and nested keys set to optional. + +Use-cases: +- Merging a default settings/config object with another object, the second object would be a deep partial of the default object. +- Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test. + +@example +``` +import {PartialDeep} from 'type-fest'; + +const settings: Settings = { + textEditor: { + fontSize: 14; + fontColor: '#000000'; + fontWeight: 400; + } + autocomplete: false; + autosave: true; +}; + +const applySavedSettings = (savedSettings: PartialDeep) => { + return {...settings, ...savedSettings}; +} + +settings = applySavedSettings({textEditor: {fontWeight: 500}}); +``` +*/ +export type PartialDeep = T extends Primitive + ? Partial + : T extends Map + ? PartialMapDeep + : T extends Set + ? PartialSetDeep + : T extends ReadonlyMap + ? PartialReadonlyMapDeep + : T extends ReadonlySet + ? PartialReadonlySetDeep + : T extends ((...arguments: any[]) => unknown) + ? T | undefined + : T extends object + ? PartialObjectDeep + : unknown; + +/** +Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialMapDeep extends Map, PartialDeep> {} + +/** +Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialSetDeep extends Set> {} + +/** +Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialReadonlyMapDeep extends ReadonlyMap, PartialDeep> {} + +/** +Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialReadonlySetDeep extends ReadonlySet> {} + +/** +Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`. +*/ +type PartialObjectDeep = { + [KeyType in keyof ObjectType]?: PartialDeep +}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/promisable.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/promisable.d.ts new file mode 100644 index 0000000..71242a5 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/promisable.d.ts @@ -0,0 +1,23 @@ +/** +Create a type that represents either the value or the value wrapped in `PromiseLike`. + +Use-cases: +- A function accepts a callback that may either return a value synchronously or may return a promised value. +- This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript. + +@example +``` +import {Promisable} from 'type-fest'; + +async function logger(getLogEntry: () => Promisable): Promise { + const entry = await getLogEntry(); + console.log(entry); +} + +logger(() => 'foo'); +logger(() => Promise.resolve('bar')); +``` +*/ +export type Promisable = T | PromiseLike; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/promise-value.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/promise-value.d.ts new file mode 100644 index 0000000..642ddeb --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/promise-value.d.ts @@ -0,0 +1,27 @@ +/** +Returns the type that is wrapped inside a `Promise` type. +If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained. +If the type is not a `Promise`, the type itself is returned. + +@example +``` +import {PromiseValue} from 'type-fest'; + +type AsyncData = Promise; +let asyncData: PromiseValue = Promise.resolve('ABC'); + +type Data = PromiseValue; +let data: Data = await asyncData; + +// Here's an example that shows how this type reacts to non-Promise types. +type SyncData = PromiseValue; +let syncData: SyncData = getSyncData(); + +// Here's an example that shows how this type reacts to recursive Promise types. +type RecursiveAsyncData = Promise >; +let recursiveAsyncData: PromiseValue = Promise.resolve(Promise.resolve('ABC')); +``` +*/ +export type PromiseValue = PromiseType extends Promise + ? { 0: PromiseValue; 1: Value }[PromiseType extends Promise ? 0 : 1] + : Otherwise; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/readonly-deep.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/readonly-deep.d.ts new file mode 100644 index 0000000..b8c04de --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/readonly-deep.d.ts @@ -0,0 +1,59 @@ +import {Primitive} from './basic'; + +/** +Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively. + +This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript. + +@example +``` +// data.json +{ + "foo": ["bar"] +} + +// main.ts +import {ReadonlyDeep} from 'type-fest'; +import dataJson = require('./data.json'); + +const data: ReadonlyDeep = dataJson; + +export default data; + +// test.ts +import data from './main'; + +data.foo.push('bar'); +//=> error TS2339: Property 'push' does not exist on type 'readonly string[]' +``` +*/ +export type ReadonlyDeep = T extends Primitive | ((...arguments: any[]) => unknown) + ? T + : T extends ReadonlyMap + ? ReadonlyMapDeep + : T extends ReadonlySet + ? ReadonlySetDeep + : T extends object + ? ReadonlyObjectDeep + : unknown; + +/** +Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +interface ReadonlyMapDeep + extends ReadonlyMap, ReadonlyDeep> {} + +/** +Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +interface ReadonlySetDeep + extends ReadonlySet> {} + +/** +Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +type ReadonlyObjectDeep = { + readonly [KeyType in keyof ObjectType]: ReadonlyDeep +}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/require-at-least-one.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/require-at-least-one.d.ts new file mode 100644 index 0000000..b3b8719 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/require-at-least-one.d.ts @@ -0,0 +1,33 @@ +import {Except} from './except'; + +/** +Create a type that requires at least one of the given keys. The remaining keys are kept as is. + +@example +``` +import {RequireAtLeastOne} from 'type-fest'; + +type Responder = { + text?: () => string; + json?: () => string; + + secure?: boolean; +}; + +const responder: RequireAtLeastOne = { + json: () => '{"message": "ok"}', + secure: true +}; +``` +*/ +export type RequireAtLeastOne< + ObjectType, + KeysType extends keyof ObjectType = keyof ObjectType +> = { + // For each `Key` in `KeysType` make a mapped type: + [Key in KeysType]-?: Required> & // 1. Make `Key`'s type required + // 2. Make all other keys in `KeysType` optional + Partial>>; +}[KeysType] & + // 3. Add the remaining keys not in `KeysType` + Except; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/require-exactly-one.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/require-exactly-one.d.ts new file mode 100644 index 0000000..c3e7e7e --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/require-exactly-one.d.ts @@ -0,0 +1,35 @@ +// TODO: Remove this when we target TypeScript >=3.5. +type _Omit = Pick>; + +/** +Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is. + +Use-cases: +- Creating interfaces for components that only need one of the keys to display properly. +- Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`. + +The caveat with `RequireExactlyOne` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireExactlyOne` can't do anything to prevent extra keys it doesn't know about. + +@example +``` +import {RequireExactlyOne} from 'type-fest'; + +type Responder = { + text: () => string; + json: () => string; + secure: boolean; +}; + +const responder: RequireExactlyOne = { + // Adding a `text` key here would cause a compile error. + + json: () => '{"message": "ok"}', + secure: true +}; +``` +*/ +export type RequireExactlyOne = + {[Key in KeysType]: ( + Required> & + Partial, never>> + )}[KeysType] & _Omit; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/set-optional.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/set-optional.d.ts new file mode 100644 index 0000000..ebaf098 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/set-optional.d.ts @@ -0,0 +1,33 @@ +import {Except} from './except'; +import {Simplify} from './simplify'; + +/** +Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type. + +Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional. + +@example +``` +import {SetOptional} from 'type-fest'; + +type Foo = { + a: number; + b?: string; + c: boolean; +} + +type SomeOptional = SetOptional; +// type SomeOptional = { +// a: number; +// b?: string; // Was already optional and still is. +// c?: boolean; // Is now optional. +// } +``` +*/ +export type SetOptional = + Simplify< + // Pick just the keys that are readonly from the base type. + Except & + // Pick the keys that should be mutable from the base type and make them mutable. + Partial> + >; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/set-required.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/set-required.d.ts new file mode 100644 index 0000000..ab8593e --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/set-required.d.ts @@ -0,0 +1,33 @@ +import {Except} from './except'; +import {Simplify} from './simplify'; + +/** +Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type. + +Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required. + +@example +``` +import {SetRequired} from 'type-fest'; + +type Foo = { + a?: number; + b: string; + c?: boolean; +} + +type SomeRequired = SetRequired; +// type SomeRequired = { +// a?: number; +// b: string; // Was already required and still is. +// c: boolean; // Is now required. +// } +``` +*/ +export type SetRequired = + Simplify< + // Pick just the keys that are optional from the base type. + Except & + // Pick the keys that should be required from the base type and make them required. + Required> + >; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/set-return-type.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/set-return-type.d.ts new file mode 100644 index 0000000..98766b1 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/set-return-type.d.ts @@ -0,0 +1,29 @@ +type IsAny = 0 extends (1 & T) ? true : false; // https://stackoverflow.com/a/49928360/3406963 +type IsNever = [T] extends [never] ? true : false; +type IsUnknown = IsNever extends false ? T extends unknown ? unknown extends T ? IsAny extends false ? true : false : false : false : false; + +/** +Create a function type with a return type of your choice and the same parameters as the given function type. + +Use-case: You want to define a wrapped function that returns something different while receiving the same parameters. For example, you might want to wrap a function that can throw an error into one that will return `undefined` instead. + +@example +``` +import {SetReturnType} from 'type-fest'; + +type MyFunctionThatCanThrow = (foo: SomeType, bar: unknown) => SomeOtherType; + +type MyWrappedFunction = SetReturnType; +//=> type MyWrappedFunction = (foo: SomeType, bar: unknown) => SomeOtherType | undefined; +``` +*/ +export type SetReturnType any, TypeToReturn> = + // Just using `Parameters` isn't ideal because it doesn't handle the `this` fake parameter. + Fn extends (this: infer ThisArg, ...args: infer Arguments) => any ? ( + // If a function did not specify the `this` fake parameter, it will be inferred to `unknown`. + // We want to detect this situation just to display a friendlier type upon hovering on an IntelliSense-powered IDE. + IsUnknown extends true ? (...args: Arguments) => TypeToReturn : (this: ThisArg, ...args: Arguments) => TypeToReturn + ) : ( + // This part should be unreachable, but we make it meaningful just in case… + (...args: Parameters) => TypeToReturn + ); diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/simplify.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/simplify.d.ts new file mode 100644 index 0000000..5e067c2 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/simplify.d.ts @@ -0,0 +1,4 @@ +/** +Flatten the type output to improve type hints shown in editors. +*/ +export type Simplify = {[KeyType in keyof T]: T[KeyType]}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/stringified.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/stringified.d.ts new file mode 100644 index 0000000..9688b67 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/stringified.d.ts @@ -0,0 +1,21 @@ +/** +Create a type with the keys of the given type changed to `string` type. + +Use-case: Changing interface values to strings in order to use them in a form model. + +@example +``` +import {Stringified} from 'type-fest'; + +type Car { + model: string; + speed: number; +} + +const carForm: Stringified = { + model: 'Foo', + speed: '101' +}; +``` +*/ +export type Stringified = {[KeyType in keyof ObjectType]: string}; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/tsconfig-json.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/tsconfig-json.d.ts new file mode 100644 index 0000000..89f6e9d --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/tsconfig-json.d.ts @@ -0,0 +1,870 @@ +declare namespace TsConfigJson { + namespace CompilerOptions { + export type JSX = + | 'preserve' + | 'react' + | 'react-native'; + + export type Module = + | 'CommonJS' + | 'AMD' + | 'System' + | 'UMD' + | 'ES6' + | 'ES2015' + | 'ESNext' + | 'None' + // Lowercase alternatives + | 'commonjs' + | 'amd' + | 'system' + | 'umd' + | 'es6' + | 'es2015' + | 'esnext' + | 'none'; + + export type NewLine = + | 'CRLF' + | 'LF' + // Lowercase alternatives + | 'crlf' + | 'lf'; + + export type Target = + | 'ES3' + | 'ES5' + | 'ES6' + | 'ES2015' + | 'ES2016' + | 'ES2017' + | 'ES2018' + | 'ES2019' + | 'ES2020' + | 'ESNext' + // Lowercase alternatives + | 'es3' + | 'es5' + | 'es6' + | 'es2015' + | 'es2016' + | 'es2017' + | 'es2018' + | 'es2019' + | 'es2020' + | 'esnext'; + + export type Lib = + | 'ES5' + | 'ES6' + | 'ES7' + | 'ES2015' + | 'ES2015.Collection' + | 'ES2015.Core' + | 'ES2015.Generator' + | 'ES2015.Iterable' + | 'ES2015.Promise' + | 'ES2015.Proxy' + | 'ES2015.Reflect' + | 'ES2015.Symbol.WellKnown' + | 'ES2015.Symbol' + | 'ES2016' + | 'ES2016.Array.Include' + | 'ES2017' + | 'ES2017.Intl' + | 'ES2017.Object' + | 'ES2017.SharedMemory' + | 'ES2017.String' + | 'ES2017.TypedArrays' + | 'ES2018' + | 'ES2018.AsyncIterable' + | 'ES2018.Intl' + | 'ES2018.Promise' + | 'ES2018.Regexp' + | 'ES2019' + | 'ES2019.Array' + | 'ES2019.Object' + | 'ES2019.String' + | 'ES2019.Symbol' + | 'ES2020' + | 'ES2020.String' + | 'ES2020.Symbol.WellKnown' + | 'ESNext' + | 'ESNext.Array' + | 'ESNext.AsyncIterable' + | 'ESNext.BigInt' + | 'ESNext.Intl' + | 'ESNext.Symbol' + | 'DOM' + | 'DOM.Iterable' + | 'ScriptHost' + | 'WebWorker' + | 'WebWorker.ImportScripts' + // Lowercase alternatives + | 'es5' + | 'es6' + | 'es7' + | 'es2015' + | 'es2015.collection' + | 'es2015.core' + | 'es2015.generator' + | 'es2015.iterable' + | 'es2015.promise' + | 'es2015.proxy' + | 'es2015.reflect' + | 'es2015.symbol.wellknown' + | 'es2015.symbol' + | 'es2016' + | 'es2016.array.include' + | 'es2017' + | 'es2017.intl' + | 'es2017.object' + | 'es2017.sharedmemory' + | 'es2017.string' + | 'es2017.typedarrays' + | 'es2018' + | 'es2018.asynciterable' + | 'es2018.intl' + | 'es2018.promise' + | 'es2018.regexp' + | 'es2019' + | 'es2019.array' + | 'es2019.object' + | 'es2019.string' + | 'es2019.symbol' + | 'es2020' + | 'es2020.string' + | 'es2020.symbol.wellknown' + | 'esnext' + | 'esnext.array' + | 'esnext.asynciterable' + | 'esnext.bigint' + | 'esnext.intl' + | 'esnext.symbol' + | 'dom' + | 'dom.iterable' + | 'scripthost' + | 'webworker' + | 'webworker.importscripts'; + + export interface Plugin { + [key: string]: unknown; + /** + Plugin name. + */ + name?: string; + } + } + + export interface CompilerOptions { + /** + The character set of the input files. + + @default 'utf8' + */ + charset?: string; + + /** + Enables building for project references. + + @default true + */ + composite?: boolean; + + /** + Generates corresponding d.ts files. + + @default false + */ + declaration?: boolean; + + /** + Specify output directory for generated declaration files. + + Requires TypeScript version 2.0 or later. + */ + declarationDir?: string; + + /** + Show diagnostic information. + + @default false + */ + diagnostics?: boolean; + + /** + Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. + + @default false + */ + emitBOM?: boolean; + + /** + Only emit `.d.ts` declaration files. + + @default false + */ + emitDeclarationOnly?: boolean; + + /** + Enable incremental compilation. + + @default `composite` + */ + incremental?: boolean; + + /** + Specify file to store incremental compilation information. + + @default '.tsbuildinfo' + */ + tsBuildInfoFile?: string; + + /** + Emit a single file with source maps instead of having a separate file. + + @default false + */ + inlineSourceMap?: boolean; + + /** + Emit the source alongside the sourcemaps within a single file. + + Requires `--inlineSourceMap` to be set. + + @default false + */ + inlineSources?: boolean; + + /** + Specify JSX code generation: `'preserve'`, `'react'`, or `'react-native'`. + + @default 'preserve' + */ + jsx?: CompilerOptions.JSX; + + /** + Specifies the object invoked for `createElement` and `__spread` when targeting `'react'` JSX emit. + + @default 'React' + */ + reactNamespace?: string; + + /** + Print names of files part of the compilation. + + @default false + */ + listFiles?: boolean; + + /** + Specifies the location where debugger should locate map files instead of generated locations. + */ + mapRoot?: string; + + /** + Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015' or 'ESNext'. Only 'AMD' and 'System' can be used in conjunction with `--outFile`. 'ES6' and 'ES2015' values may be used when targeting 'ES5' or lower. + + @default ['ES3', 'ES5'].includes(target) ? 'CommonJS' : 'ES6' + */ + module?: CompilerOptions.Module; + + /** + Specifies the end of line sequence to be used when emitting files: 'crlf' (Windows) or 'lf' (Unix). + + Default: Platform specific + */ + newLine?: CompilerOptions.NewLine; + + /** + Do not emit output. + + @default false + */ + noEmit?: boolean; + + /** + Do not generate custom helper functions like `__extends` in compiled output. + + @default false + */ + noEmitHelpers?: boolean; + + /** + Do not emit outputs if any type checking errors were reported. + + @default false + */ + noEmitOnError?: boolean; + + /** + Warn on expressions and declarations with an implied 'any' type. + + @default false + */ + noImplicitAny?: boolean; + + /** + Raise error on 'this' expressions with an implied any type. + + @default false + */ + noImplicitThis?: boolean; + + /** + Report errors on unused locals. + + Requires TypeScript version 2.0 or later. + + @default false + */ + noUnusedLocals?: boolean; + + /** + Report errors on unused parameters. + + Requires TypeScript version 2.0 or later. + + @default false + */ + noUnusedParameters?: boolean; + + /** + Do not include the default library file (lib.d.ts). + + @default false + */ + noLib?: boolean; + + /** + Do not add triple-slash references or module import targets to the list of compiled files. + + @default false + */ + noResolve?: boolean; + + /** + Disable strict checking of generic signatures in function types. + + @default false + */ + noStrictGenericChecks?: boolean; + + /** + @deprecated use `skipLibCheck` instead. + */ + skipDefaultLibCheck?: boolean; + + /** + Skip type checking of declaration files. + + Requires TypeScript version 2.0 or later. + + @default false + */ + skipLibCheck?: boolean; + + /** + Concatenate and emit output to single file. + */ + outFile?: string; + + /** + Redirect output structure to the directory. + */ + outDir?: string; + + /** + Do not erase const enum declarations in generated code. + + @default false + */ + preserveConstEnums?: boolean; + + /** + Do not resolve symlinks to their real path; treat a symlinked file like a real one. + + @default false + */ + preserveSymlinks?: boolean; + + /** + Keep outdated console output in watch mode instead of clearing the screen. + + @default false + */ + preserveWatchOutput?: boolean; + + /** + Stylize errors and messages using color and context (experimental). + + @default true // Unless piping to another program or redirecting output to a file. + */ + pretty?: boolean; + + /** + Do not emit comments to output. + + @default false + */ + removeComments?: boolean; + + /** + Specifies the root directory of input files. + + Use to control the output directory structure with `--outDir`. + */ + rootDir?: string; + + /** + Unconditionally emit imports for unresolved files. + + @default false + */ + isolatedModules?: boolean; + + /** + Generates corresponding '.map' file. + + @default false + */ + sourceMap?: boolean; + + /** + Specifies the location where debugger should locate TypeScript files instead of source locations. + */ + sourceRoot?: string; + + /** + Suppress excess property checks for object literals. + + @default false + */ + suppressExcessPropertyErrors?: boolean; + + /** + Suppress noImplicitAny errors for indexing objects lacking index signatures. + + @default false + */ + suppressImplicitAnyIndexErrors?: boolean; + + /** + Do not emit declarations for code that has an `@internal` annotation. + */ + stripInternal?: boolean; + + /** + Specify ECMAScript target version. + + @default 'es3' + */ + target?: CompilerOptions.Target; + + /** + Watch input files. + + @default false + */ + watch?: boolean; + + /** + Enables experimental support for ES7 decorators. + + @default false + */ + experimentalDecorators?: boolean; + + /** + Emit design-type metadata for decorated declarations in source. + + @default false + */ + emitDecoratorMetadata?: boolean; + + /** + Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6). + + @default ['AMD', 'System', 'ES6'].includes(module) ? 'classic' : 'node' + */ + moduleResolution?: 'classic' | 'node'; + + /** + Do not report errors on unused labels. + + @default false + */ + allowUnusedLabels?: boolean; + + /** + Report error when not all code paths in function return a value. + + @default false + */ + noImplicitReturns?: boolean; + + /** + Report errors for fallthrough cases in switch statement. + + @default false + */ + noFallthroughCasesInSwitch?: boolean; + + /** + Do not report errors on unreachable code. + + @default false + */ + allowUnreachableCode?: boolean; + + /** + Disallow inconsistently-cased references to the same file. + + @default false + */ + forceConsistentCasingInFileNames?: boolean; + + /** + Base directory to resolve non-relative module names. + */ + baseUrl?: string; + + /** + Specify path mapping to be computed relative to baseUrl option. + */ + paths?: Record; + + /** + List of TypeScript language server plugins to load. + + Requires TypeScript version 2.3 or later. + */ + plugins?: CompilerOptions.Plugin[]; + + /** + Specify list of root directories to be used when resolving modules. + */ + rootDirs?: string[]; + + /** + Specify list of directories for type definition files to be included. + + Requires TypeScript version 2.0 or later. + */ + typeRoots?: string[]; + + /** + Type declaration files to be included in compilation. + + Requires TypeScript version 2.0 or later. + */ + types?: string[]; + + /** + Enable tracing of the name resolution process. + + @default false + */ + traceResolution?: boolean; + + /** + Allow javascript files to be compiled. + + @default false + */ + allowJs?: boolean; + + /** + Do not truncate error messages. + + @default false + */ + noErrorTruncation?: boolean; + + /** + Allow default imports from modules with no default export. This does not affect code emit, just typechecking. + + @default module === 'system' || esModuleInterop + */ + allowSyntheticDefaultImports?: boolean; + + /** + Do not emit `'use strict'` directives in module output. + + @default false + */ + noImplicitUseStrict?: boolean; + + /** + Enable to list all emitted files. + + Requires TypeScript version 2.0 or later. + + @default false + */ + listEmittedFiles?: boolean; + + /** + Disable size limit for JavaScript project. + + Requires TypeScript version 2.0 or later. + + @default false + */ + disableSizeLimit?: boolean; + + /** + List of library files to be included in the compilation. + + Requires TypeScript version 2.0 or later. + */ + lib?: CompilerOptions.Lib[]; + + /** + Enable strict null checks. + + Requires TypeScript version 2.0 or later. + + @default false + */ + strictNullChecks?: boolean; + + /** + The maximum dependency depth to search under `node_modules` and load JavaScript files. Only applicable with `--allowJs`. + + @default 0 + */ + maxNodeModuleJsDepth?: number; + + /** + Import emit helpers (e.g. `__extends`, `__rest`, etc..) from tslib. + + Requires TypeScript version 2.1 or later. + + @default false + */ + importHelpers?: boolean; + + /** + Specify the JSX factory function to use when targeting React JSX emit, e.g. `React.createElement` or `h`. + + Requires TypeScript version 2.1 or later. + + @default 'React.createElement' + */ + jsxFactory?: string; + + /** + Parse in strict mode and emit `'use strict'` for each source file. + + Requires TypeScript version 2.1 or later. + + @default false + */ + alwaysStrict?: boolean; + + /** + Enable all strict type checking options. + + Requires TypeScript version 2.3 or later. + + @default false + */ + strict?: boolean; + + /** + Enable stricter checking of of the `bind`, `call`, and `apply` methods on functions. + + @default false + */ + strictBindCallApply?: boolean; + + /** + Provide full support for iterables in `for-of`, spread, and destructuring when targeting `ES5` or `ES3`. + + Requires TypeScript version 2.3 or later. + + @default false + */ + downlevelIteration?: boolean; + + /** + Report errors in `.js` files. + + Requires TypeScript version 2.3 or later. + + @default false + */ + checkJs?: boolean; + + /** + Disable bivariant parameter checking for function types. + + Requires TypeScript version 2.6 or later. + + @default false + */ + strictFunctionTypes?: boolean; + + /** + Ensure non-undefined class properties are initialized in the constructor. + + Requires TypeScript version 2.7 or later. + + @default false + */ + strictPropertyInitialization?: boolean; + + /** + Emit `__importStar` and `__importDefault` helpers for runtime Babel ecosystem compatibility and enable `--allowSyntheticDefaultImports` for typesystem compatibility. + + Requires TypeScript version 2.7 or later. + + @default false + */ + esModuleInterop?: boolean; + + /** + Allow accessing UMD globals from modules. + + @default false + */ + allowUmdGlobalAccess?: boolean; + + /** + Resolve `keyof` to string valued property names only (no numbers or symbols). + + Requires TypeScript version 2.9 or later. + + @default false + */ + keyofStringsOnly?: boolean; + + /** + Emit ECMAScript standard class fields. + + Requires TypeScript version 3.7 or later. + + @default false + */ + useDefineForClassFields?: boolean; + + /** + Generates a sourcemap for each corresponding `.d.ts` file. + + Requires TypeScript version 2.9 or later. + + @default false + */ + declarationMap?: boolean; + + /** + Include modules imported with `.json` extension. + + Requires TypeScript version 2.9 or later. + + @default false + */ + resolveJsonModule?: boolean; + } + + /** + Auto type (.d.ts) acquisition options for this project. + + Requires TypeScript version 2.1 or later. + */ + export interface TypeAcquisition { + /** + Enable auto type acquisition. + */ + enable?: boolean; + + /** + Specifies a list of type declarations to be included in auto type acquisition. For example, `['jquery', 'lodash']`. + */ + include?: string[]; + + /** + Specifies a list of type declarations to be excluded from auto type acquisition. For example, `['jquery', 'lodash']`. + */ + exclude?: string[]; + } + + export interface References { + /** + A normalized path on disk. + */ + path: string; + + /** + The path as the user originally wrote it. + */ + originalPath?: string; + + /** + True if the output of this reference should be prepended to the output of this project. + + Only valid for `--outFile` compilations. + */ + prepend?: boolean; + + /** + True if it is intended that this reference form a circularity. + */ + circular?: boolean; + } +} + +export interface TsConfigJson { + /** + Instructs the TypeScript compiler how to compile `.ts` files. + */ + compilerOptions?: TsConfigJson.CompilerOptions; + + /** + Auto type (.d.ts) acquisition options for this project. + + Requires TypeScript version 2.1 or later. + */ + typeAcquisition?: TsConfigJson.TypeAcquisition; + + /** + Enable Compile-on-Save for this project. + */ + compileOnSave?: boolean; + + /** + Path to base configuration file to inherit from. + + Requires TypeScript version 2.1 or later. + */ + extends?: string; + + /** + If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. When a `files` property is specified, only those files and those specified by `include` are included. + */ + files?: string[]; + + /** + Specifies a list of files to be excluded from compilation. The `exclude` property only affects the files included via the `include` property and not the `files` property. + + Glob patterns require TypeScript version 2.0 or later. + */ + exclude?: string[]; + + /** + Specifies a list of glob patterns that match files to be included in compilation. + + If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. + + Requires TypeScript version 2.0 or later. + */ + include?: string[]; + + /** + Referenced projects. + + Requires TypeScript version 3.0 or later. + */ + references?: TsConfigJson.References[]; +} diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/typed-array.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/typed-array.d.ts new file mode 100644 index 0000000..15e22a3 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/typed-array.d.ts @@ -0,0 +1,15 @@ +/** +Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +*/ +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/union-to-intersection.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/union-to-intersection.d.ts new file mode 100644 index 0000000..5f9837f --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/union-to-intersection.d.ts @@ -0,0 +1,58 @@ +/** +Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). + +Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153). + +@example +``` +import {UnionToIntersection} from 'type-fest'; + +type Union = {the(): void} | {great(arg: string): void} | {escape: boolean}; + +type Intersection = UnionToIntersection; +//=> {the(): void; great(arg: string): void; escape: boolean}; +``` + +A more applicable example which could make its way into your library code follows. + +@example +``` +import {UnionToIntersection} from 'type-fest'; + +class CommandOne { + commands: { + a1: () => undefined, + b1: () => undefined, + } +} + +class CommandTwo { + commands: { + a2: (argA: string) => undefined, + b2: (argB: string) => undefined, + } +} + +const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands); +type Union = typeof union; +//=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void} + +type Intersection = UnionToIntersection; +//=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void} +``` +*/ +export type UnionToIntersection = ( + // `extends unknown` is always going to be the case and is used to convert the + // `Union` into a [distributive conditional + // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). + Union extends unknown + // The union type is used as the only argument to a function since the union + // of function arguments is an intersection. + ? (distributedUnion: Union) => void + // This won't happen. + : never + // Infer the `Intersection` type since TypeScript represents the positional + // arguments of unions of functions as an intersection of the union. + ) extends ((mergedIntersection: infer Intersection) => void) + ? Intersection + : never; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/utilities.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/utilities.d.ts new file mode 100644 index 0000000..8d60ccd --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/utilities.d.ts @@ -0,0 +1,5 @@ +export type UpperCaseCharacters = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'; + +export type WordSeparators = '-' | '_' | ' '; + +export type StringDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/source/value-of.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/source/value-of.d.ts new file mode 100644 index 0000000..1279373 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/source/value-of.d.ts @@ -0,0 +1,40 @@ +/** +Create a union of the given object's values, and optionally specify which keys to get the values from. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. + +@example +``` +// data.json +{ + 'foo': 1, + 'bar': 2, + 'biz': 3 +} + +// main.ts +import {ValueOf} from 'type-fest'; +import data = require('./data.json'); + +export function getData(name: string): ValueOf { + return data[name]; +} + +export function onlyBar(name: string): ValueOf { + return data[name]; +} + +// file.ts +import {getData, onlyBar} from './main'; + +getData('foo'); +//=> 1 + +onlyBar('foo'); +//=> TypeError ... + +onlyBar('bar'); +//=> 2 +``` +*/ +export type ValueOf = ObjectType[ValueType]; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/camel-case.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/camel-case.d.ts new file mode 100644 index 0000000..4f9a67b --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/camel-case.d.ts @@ -0,0 +1,64 @@ +import {WordSeparators} from '../source/utilities'; +import {Split} from './utilities'; + +/** +Step by step takes the first item in an array literal, formats it and adds it to a string literal, and then recursively appends the remainder. + +Only to be used by `CamelCaseStringArray<>`. + +@see CamelCaseStringArray +*/ +type InnerCamelCaseStringArray = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? FirstPart extends undefined + ? '' + : FirstPart extends '' + ? InnerCamelCaseStringArray + : `${PreviousPart extends '' ? FirstPart : Capitalize}${InnerCamelCaseStringArray}` + : ''; + +/** +Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal. + +It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code. + +@see Split +*/ +type CamelCaseStringArray = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray}`> + : never; + +/** +Convert a string literal to camel-case. + +This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result. + +@example +``` +import {CamelCase} from 'type-fest'; + +// Simple + +const someVariable: CamelCase<'foo-bar'> = 'fooBar'; + +// Advanced + +type CamelCasedProps = { + [K in keyof T as CamelCase]: T[K] +}; + +interface RawOptions { + 'dry-run': boolean; + 'full_family_name': string; + foo: number; +} + +const dbResult: CamelCasedProps = { + dryRun: true, + fullFamilyName: 'bar.js', + foo: 123 +}; +``` +*/ +export type CamelCase = K extends string ? CamelCaseStringArray> : K; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/delimiter-case.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/delimiter-case.d.ts new file mode 100644 index 0000000..52f4eb9 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/delimiter-case.d.ts @@ -0,0 +1,85 @@ +import {UpperCaseCharacters, WordSeparators} from '../source/utilities'; + +/** +Unlike a simpler split, this one includes the delimiter splitted on in the resulting array literal. This is to enable splitting on, for example, upper-case characters. +*/ +export type SplitIncludingDelimiters = + Source extends '' ? [] : + Source extends `${infer FirstPart}${Delimiter}${infer SecondPart}` ? + ( + Source extends `${FirstPart}${infer UsedDelimiter}${SecondPart}` + ? UsedDelimiter extends Delimiter + ? Source extends `${infer FirstPart}${UsedDelimiter}${infer SecondPart}` + ? [...SplitIncludingDelimiters, UsedDelimiter, ...SplitIncludingDelimiters] + : never + : never + : never + ) : + [Source]; + +/** +Format a specific part of the splitted string literal that `StringArrayToDelimiterCase<>` fuses together, ensuring desired casing. + +@see StringArrayToDelimiterCase +*/ +type StringPartToDelimiterCase = + StringPart extends UsedWordSeparators ? Delimiter : + StringPart extends UsedUpperCaseCharacters ? `${Delimiter}${Lowercase}` : + StringPart; + +/** +Takes the result of a splitted string literal and recursively concatenates it together into the desired casing. + +It receives `UsedWordSeparators` and `UsedUpperCaseCharacters` as input to ensure it's fully encapsulated. + +@see SplitIncludingDelimiters +*/ +type StringArrayToDelimiterCase = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? `${StringPartToDelimiterCase}${StringArrayToDelimiterCase}` + : ''; + +/** +Convert a string literal to a custom string delimiter casing. + +This can be useful when, for example, converting a camel-cased object property to an oddly cased one. + +@see KebabCase +@see SnakeCase + +@example +``` +import {DelimiterCase} from 'type-fest'; + +// Simple + +const someVariable: DelimiterCase<'fooBar', '#'> = 'foo#bar'; + +// Advanced + +type OddlyCasedProps = { + [K in keyof T as DelimiterCase]: T[K] +}; + +interface SomeOptions { + dryRun: boolean; + includeFile: string; + foo: number; +} + +const rawCliOptions: OddlyCasedProps = { + 'dry#run': true, + 'include#file': 'bar.js', + foo: 123 +}; +``` +*/ + +export type DelimiterCase = Value extends string + ? StringArrayToDelimiterCase< + SplitIncludingDelimiters, + WordSeparators, + UpperCaseCharacters, + Delimiter + > + : Value; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/get.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/get.d.ts new file mode 100644 index 0000000..9103e9a --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/get.d.ts @@ -0,0 +1,131 @@ +import {Split} from './utilities'; +import {StringDigit} from '../source/utilities'; + +/** +Like the `Get` type but receives an array of strings as a path parameter. +*/ +type GetWithPath = + Keys extends [] + ? BaseType + : Keys extends [infer Head, ...infer Tail] + ? GetWithPath>, Extract> + : never; + +/** +Splits a dot-prop style path into a tuple comprised of the properties in the path. Handles square-bracket notation. + +@example +``` +ToPath<'foo.bar.baz'> +//=> ['foo', 'bar', 'baz'] + +ToPath<'foo[0].bar.baz'> +//=> ['foo', '0', 'bar', 'baz'] +``` +*/ +type ToPath = Split, '.'>; + +/** +Replaces square-bracketed dot notation with dots, for example, `foo[0].bar` -> `foo.0.bar`. +*/ +type FixPathSquareBrackets = + Path extends `${infer Head}[${infer Middle}]${infer Tail}` + ? `${Head}.${Middle}${FixPathSquareBrackets}` + : Path; + +/** +Returns true if `LongString` is made up out of `Substring` repeated 0 or more times. + +@example +``` +ConsistsOnlyOf<'aaa', 'a'> //=> true +ConsistsOnlyOf<'ababab', 'ab'> //=> true +ConsistsOnlyOf<'aBa', 'a'> //=> false +ConsistsOnlyOf<'', 'a'> //=> true +``` +*/ +type ConsistsOnlyOf = + LongString extends '' + ? true + : LongString extends `${Substring}${infer Tail}` + ? ConsistsOnlyOf + : false; + +/** +Convert a type which may have number keys to one with string keys, making it possible to index using strings retrieved from template types. + +@example +``` +type WithNumbers = {foo: string; 0: boolean}; +type WithStrings = WithStringKeys; + +type WithNumbersKeys = keyof WithNumbers; +//=> 'foo' | 0 +type WithStringsKeys = keyof WithStrings; +//=> 'foo' | '0' +``` +*/ +type WithStringKeys> = { + [Key in `${Extract}`]: BaseType[Key] +}; + +/** +Get a property of an object or array. Works when indexing arrays using number-literal-strings, for example, `PropertyOf = number`, and when indexing objects with number keys. + +Note: +- Returns `unknown` if `Key` is not a property of `BaseType`, since TypeScript uses structural typing, and it cannot be guaranteed that extra properties unknown to the type system will exist at runtime. +- Returns `undefined` from nullish values, to match the behaviour of most deep-key libraries like `lodash`, `dot-prop`, etc. +*/ +type PropertyOf = + BaseType extends null | undefined + ? undefined + : Key extends keyof BaseType + ? BaseType[Key] + : BaseType extends { + [n: number]: infer Item; + length: number; // Note: This is needed to avoid being too lax with records types using number keys like `{0: string; 1: boolean}`. + } + ? ( + ConsistsOnlyOf extends true + ? Item + : unknown + ) + : Key extends keyof WithStringKeys + ? WithStringKeys[Key] + : unknown; + +// This works by first splitting the path based on `.` and `[...]` characters into a tuple of string keys. Then it recursively uses the head key to get the next property of the current object, until there are no keys left. Number keys extract the item type from arrays, or are converted to strings to extract types from tuples and dictionaries with number keys. +/** +Get a deeply-nested property from an object using a key path, like Lodash's `.get()` function. + +Use-case: Retrieve a property from deep inside an API response or some other complex object. + +@example +``` +import {Get} from 'type-fest'; +import * as lodash from 'lodash'; + +const get = (object: BaseType, path: Path): Get => + lodash.get(object, path); + +interface ApiResponse { + hits: { + hits: Array<{ + _id: string + _source: { + name: Array<{ + given: string[] + family: string + }> + birthDate: string + } + }> + } +} + +const getName = (apiResponse: ApiResponse) => + get(apiResponse, 'hits.hits[0]._source.name'); + //=> Array<{given: string[]; family: string}> +``` +*/ +export type Get = GetWithPath>; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/index.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/index.d.ts new file mode 100644 index 0000000..e49504c --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/index.d.ts @@ -0,0 +1,10 @@ +// These are all the basic types that's compatible with all supported TypeScript versions. +export * from '../base'; + +// These are special types that require at least TypeScript 4.1. +export {CamelCase} from './camel-case'; +export {KebabCase} from './kebab-case'; +export {PascalCase} from './pascal-case'; +export {SnakeCase} from './snake-case'; +export {DelimiterCase} from './delimiter-case'; +export {Get} from './get'; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/kebab-case.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/kebab-case.d.ts new file mode 100644 index 0000000..ba6a99d --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/kebab-case.d.ts @@ -0,0 +1,36 @@ +import {DelimiterCase} from './delimiter-case'; + +/** +Convert a string literal to kebab-case. + +This can be useful when, for example, converting a camel-cased object property to a kebab-cased CSS class name or a command-line flag. + +@example +``` +import {KebabCase} from 'type-fest'; + +// Simple + +const someVariable: KebabCase<'fooBar'> = 'foo-bar'; + +// Advanced + +type KebabCasedProps = { + [K in keyof T as KebabCase]: T[K] +}; + +interface CliOptions { + dryRun: boolean; + includeFile: string; + foo: number; +} + +const rawCliOptions: KebabCasedProps = { + 'dry-run': true, + 'include-file': 'bar.js', + foo: 123 +}; +``` +*/ + +export type KebabCase = DelimiterCase; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/pascal-case.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/pascal-case.d.ts new file mode 100644 index 0000000..bfb2a36 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/pascal-case.d.ts @@ -0,0 +1,36 @@ +import {CamelCase} from './camel-case'; + +/** +Converts a string literal to pascal-case. + +@example +``` +import {PascalCase} from 'type-fest'; + +// Simple + +const someVariable: PascalCase<'foo-bar'> = 'FooBar'; + +// Advanced + +type PascalCaseProps = { + [K in keyof T as PascalCase]: T[K] +}; + +interface RawOptions { + 'dry-run': boolean; + 'full_family_name': string; + foo: number; +} + +const dbResult: CamelCasedProps = { + DryRun: true, + FullFamilyName: 'bar.js', + Foo: 123 +}; +``` +*/ + +export type PascalCase = CamelCase extends string + ? Capitalize> + : CamelCase; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/snake-case.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/snake-case.d.ts new file mode 100644 index 0000000..272b3d3 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/snake-case.d.ts @@ -0,0 +1,35 @@ +import {DelimiterCase} from './delimiter-case'; + +/** +Convert a string literal to snake-case. + +This can be useful when, for example, converting a camel-cased object property to a snake-cased SQL column name. + +@example +``` +import {SnakeCase} from 'type-fest'; + +// Simple + +const someVariable: SnakeCase<'fooBar'> = 'foo_bar'; + +// Advanced + +type SnakeCasedProps = { + [K in keyof T as SnakeCase]: T[K] +}; + +interface ModelProps { + isHappy: boolean; + fullFamilyName: string; + foo: number; +} + +const dbResult: SnakeCasedProps = { + 'is_happy': true, + 'full_family_name': 'Carla Smith', + foo: 123 +}; +``` +*/ +export type SnakeCase = DelimiterCase; diff --git a/node_modules/ansi-escapes/node_modules/type-fest/ts41/utilities.d.ts b/node_modules/ansi-escapes/node_modules/type-fest/ts41/utilities.d.ts new file mode 100644 index 0000000..f82e362 --- /dev/null +++ b/node_modules/ansi-escapes/node_modules/type-fest/ts41/utilities.d.ts @@ -0,0 +1,8 @@ +/** +Recursively split a string literal into two parts on the first occurence of the given string, returning an array literal of all the separate parts. +*/ +export type Split = + string extends S ? string[] : + S extends '' ? [] : + S extends `${infer T}${D}${infer U}` ? [T, ...Split] : + [S]; diff --git a/node_modules/ansi-escapes/package.json b/node_modules/ansi-escapes/package.json new file mode 100644 index 0000000..88a9356 --- /dev/null +++ b/node_modules/ansi-escapes/package.json @@ -0,0 +1,57 @@ +{ + "name": "ansi-escapes", + "version": "4.3.2", + "description": "ANSI escape codes for manipulating the terminal", + "license": "MIT", + "repository": "sindresorhus/ansi-escapes", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "escapes", + "formatting", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text", + "vt100", + "sequence", + "control", + "code", + "codes", + "cursor", + "iterm", + "iterm2" + ], + "dependencies": { + "type-fest": "^0.21.3" + }, + "devDependencies": { + "@types/node": "^13.7.7", + "ava": "^2.1.0", + "tsd": "^0.14.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/ansi-escapes/readme.md b/node_modules/ansi-escapes/readme.md new file mode 100644 index 0000000..9fbfec9 --- /dev/null +++ b/node_modules/ansi-escapes/readme.md @@ -0,0 +1,245 @@ +# ansi-escapes + +> [ANSI escape codes](http://www.termsys.demon.co.uk/vtansi.htm) for manipulating the terminal + +## Install + +``` +$ npm install ansi-escapes +``` + +## Usage + +```js +const ansiEscapes = require('ansi-escapes'); + +// Moves the cursor two rows up and to the left +process.stdout.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft); +//=> '\u001B[2A\u001B[1000D' +``` + +## API + +### cursorTo(x, y?) + +Set the absolute position of the cursor. `x0` `y0` is the top left of the screen. + +### cursorMove(x, y?) + +Set the position of the cursor relative to its current position. + +### cursorUp(count) + +Move cursor up a specific amount of rows. Default is `1`. + +### cursorDown(count) + +Move cursor down a specific amount of rows. Default is `1`. + +### cursorForward(count) + +Move cursor forward a specific amount of columns. Default is `1`. + +### cursorBackward(count) + +Move cursor backward a specific amount of columns. Default is `1`. + +### cursorLeft + +Move cursor to the left side. + +### cursorSavePosition + +Save cursor position. + +### cursorRestorePosition + +Restore saved cursor position. + +### cursorGetPosition + +Get cursor position. + +### cursorNextLine + +Move cursor to the next line. + +### cursorPrevLine + +Move cursor to the previous line. + +### cursorHide + +Hide cursor. + +### cursorShow + +Show cursor. + +### eraseLines(count) + +Erase from the current cursor position up the specified amount of rows. + +### eraseEndLine + +Erase from the current cursor position to the end of the current line. + +### eraseStartLine + +Erase from the current cursor position to the start of the current line. + +### eraseLine + +Erase the entire current line. + +### eraseDown + +Erase the screen from the current line down to the bottom of the screen. + +### eraseUp + +Erase the screen from the current line up to the top of the screen. + +### eraseScreen + +Erase the screen and move the cursor the top left position. + +### scrollUp + +Scroll display up one line. + +### scrollDown + +Scroll display down one line. + +### clearScreen + +Clear the terminal screen. (Viewport) + +### clearTerminal + +Clear the whole terminal, including scrollback buffer. (Not just the visible part of it) + +### beep + +Output a beeping sound. + +### link(text, url) + +Create a clickable link. + +[Supported terminals.](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) Use [`supports-hyperlinks`](https://github.com/jamestalmage/supports-hyperlinks) to detect link support. + +### image(filePath, options?) + +Display an image. + +*Currently only supported on iTerm2 >=3* + +See [term-img](https://github.com/sindresorhus/term-img) for a higher-level module. + +#### input + +Type: `Buffer` + +Buffer of an image. Usually read in with `fs.readFile()`. + +#### options + +Type: `object` + +##### width +##### height + +Type: `string | number` + +The width and height are given as a number followed by a unit, or the word "auto". + +- `N`: N character cells. +- `Npx`: N pixels. +- `N%`: N percent of the session's width or height. +- `auto`: The image's inherent size will be used to determine an appropriate dimension. + +##### preserveAspectRatio + +Type: `boolean`\ +Default: `true` + +### iTerm.setCwd(path?) + +Type: `string`\ +Default: `process.cwd()` + +[Inform iTerm2](https://www.iterm2.com/documentation-escape-codes.html) of the current directory to help semantic history and enable [Cmd-clicking relative paths](https://coderwall.com/p/b7e82q/quickly-open-files-in-iterm-with-cmd-click). + +### iTerm.annotation(message, options?) + +Creates an escape code to display an "annotation" in iTerm2. + +An annotation looks like this when shown: + + + +See the [iTerm Proprietary Escape Codes documentation](https://iterm2.com/documentation-escape-codes.html) for more information. + +#### message + +Type: `string` + +The message to display within the annotation. + +The `|` character is disallowed and will be stripped. + +#### options + +Type: `object` + +##### length + +Type: `number`\ +Default: The remainder of the line + +Nonzero number of columns to annotate. + +##### x + +Type: `number`\ +Default: Cursor position + +Starting X coordinate. + +Must be used with `y` and `length`. + +##### y + +Type: `number`\ +Default: Cursor position + +Starting Y coordinate. + +Must be used with `x` and `length`. + +##### isHidden + +Type: `boolean`\ +Default: `false` + +Create a "hidden" annotation. + +Annotations created this way can be shown using the "Show Annotations" iTerm command. + +## Related + +- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/ansi-regex/index.d.ts b/node_modules/ansi-regex/index.d.ts new file mode 100644 index 0000000..50ef64d --- /dev/null +++ b/node_modules/ansi-regex/index.d.ts @@ -0,0 +1,33 @@ +export interface Options { + /** + Match only the first ANSI escape. + + @default false + */ + readonly onlyFirst: boolean; +} + +/** +Regular expression for matching ANSI escape codes. + +@example +``` +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` +*/ +export default function ansiRegex(options?: Options): RegExp; diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..130a092 --- /dev/null +++ b/node_modules/ansi-regex/index.js @@ -0,0 +1,8 @@ +export default function ansiRegex({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..7bbb563 --- /dev/null +++ b/node_modules/ansi-regex/package.json @@ -0,0 +1,58 @@ +{ + "name": "ansi-regex", + "version": "6.0.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "funding": "https://github.com/chalk/ansi-regex?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..0e17e23 --- /dev/null +++ b/node_modules/ansi-regex/readme.md @@ -0,0 +1,72 @@ +# ansi-regex + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + +## Install + +``` +$ npm install ansi-regex +``` + +## Usage + +```js +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`\ +Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/ansi-styles/index.d.ts b/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000..44a907e --- /dev/null +++ b/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,345 @@ +declare type CSSColor = + | 'aliceblue' + | 'antiquewhite' + | 'aqua' + | 'aquamarine' + | 'azure' + | 'beige' + | 'bisque' + | 'black' + | 'blanchedalmond' + | 'blue' + | 'blueviolet' + | 'brown' + | 'burlywood' + | 'cadetblue' + | 'chartreuse' + | 'chocolate' + | 'coral' + | 'cornflowerblue' + | 'cornsilk' + | 'crimson' + | 'cyan' + | 'darkblue' + | 'darkcyan' + | 'darkgoldenrod' + | 'darkgray' + | 'darkgreen' + | 'darkgrey' + | 'darkkhaki' + | 'darkmagenta' + | 'darkolivegreen' + | 'darkorange' + | 'darkorchid' + | 'darkred' + | 'darksalmon' + | 'darkseagreen' + | 'darkslateblue' + | 'darkslategray' + | 'darkslategrey' + | 'darkturquoise' + | 'darkviolet' + | 'deeppink' + | 'deepskyblue' + | 'dimgray' + | 'dimgrey' + | 'dodgerblue' + | 'firebrick' + | 'floralwhite' + | 'forestgreen' + | 'fuchsia' + | 'gainsboro' + | 'ghostwhite' + | 'gold' + | 'goldenrod' + | 'gray' + | 'green' + | 'greenyellow' + | 'grey' + | 'honeydew' + | 'hotpink' + | 'indianred' + | 'indigo' + | 'ivory' + | 'khaki' + | 'lavender' + | 'lavenderblush' + | 'lawngreen' + | 'lemonchiffon' + | 'lightblue' + | 'lightcoral' + | 'lightcyan' + | 'lightgoldenrodyellow' + | 'lightgray' + | 'lightgreen' + | 'lightgrey' + | 'lightpink' + | 'lightsalmon' + | 'lightseagreen' + | 'lightskyblue' + | 'lightslategray' + | 'lightslategrey' + | 'lightsteelblue' + | 'lightyellow' + | 'lime' + | 'limegreen' + | 'linen' + | 'magenta' + | 'maroon' + | 'mediumaquamarine' + | 'mediumblue' + | 'mediumorchid' + | 'mediumpurple' + | 'mediumseagreen' + | 'mediumslateblue' + | 'mediumspringgreen' + | 'mediumturquoise' + | 'mediumvioletred' + | 'midnightblue' + | 'mintcream' + | 'mistyrose' + | 'moccasin' + | 'navajowhite' + | 'navy' + | 'oldlace' + | 'olive' + | 'olivedrab' + | 'orange' + | 'orangered' + | 'orchid' + | 'palegoldenrod' + | 'palegreen' + | 'paleturquoise' + | 'palevioletred' + | 'papayawhip' + | 'peachpuff' + | 'peru' + | 'pink' + | 'plum' + | 'powderblue' + | 'purple' + | 'rebeccapurple' + | 'red' + | 'rosybrown' + | 'royalblue' + | 'saddlebrown' + | 'salmon' + | 'sandybrown' + | 'seagreen' + | 'seashell' + | 'sienna' + | 'silver' + | 'skyblue' + | 'slateblue' + | 'slategray' + | 'slategrey' + | 'snow' + | 'springgreen' + | 'steelblue' + | 'tan' + | 'teal' + | 'thistle' + | 'tomato' + | 'turquoise' + | 'violet' + | 'wheat' + | 'white' + | 'whitesmoke' + | 'yellow' + | 'yellowgreen'; + +declare namespace ansiStyles { + interface ColorConvert { + /** + The RGB color space. + + @param red - (`0`-`255`) + @param green - (`0`-`255`) + @param blue - (`0`-`255`) + */ + rgb(red: number, green: number, blue: number): string; + + /** + The RGB HEX color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hex(hex: string): string; + + /** + @param keyword - A CSS color name. + */ + keyword(keyword: CSSColor): string; + + /** + The HSL color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param lightness - (`0`-`100`) + */ + hsl(hue: number, saturation: number, lightness: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param value - (`0`-`100`) + */ + hsv(hue: number, saturation: number, value: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param whiteness - (`0`-`100`) + @param blackness - (`0`-`100`) + */ + hwb(hue: number, whiteness: number, blackness: number): string; + + /** + Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. + */ + ansi(ansi: number): string; + + /** + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(ansi: number): string; + } + + interface CSPair { + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; + } + + interface ColorBase { + readonly ansi: ColorConvert; + readonly ansi256: ColorConvert; + readonly ansi16m: ColorConvert; + + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + } + + interface Modifier { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; + } + + interface ForegroundColor { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; + } + + interface BackgroundColor { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; + } +} + +declare const ansiStyles: { + readonly modifier: ansiStyles.Modifier; + readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; + readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; + readonly codes: ReadonlyMap; +} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; + +export = ansiStyles; diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..5d82581 --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,163 @@ +'use strict'; + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = require('color-convert'); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +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], + + // Bright color + blackBright: [90, 39], + 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] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + 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 + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-styles/package.json b/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..7539328 --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,56 @@ +{ + "name": "ansi-styles", + "version": "4.3.0", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "color-convert": "^2.0.1" + }, + "devDependencies": { + "@types/color-convert": "^1.9.0", + "ava": "^2.3.0", + "svg-term-cli": "^2.1.1", + "tsd": "^0.11.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..24883de --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,152 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + +## Install + +``` +$ npm install ansi-styles +``` + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +The following color spaces from `color-convert` are supported: + +- `rgb` +- `hex` +- `keyword` +- `hsl` +- `hsv` +- `hwb` +- `ansi` +- `ansi256` + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/ansicolors/LICENSE b/node_modules/ansicolors/LICENSE new file mode 100644 index 0000000..41702c5 --- /dev/null +++ b/node_modules/ansicolors/LICENSE @@ -0,0 +1,23 @@ +Copyright 2013 Thorsten Lorenz. +All rights reserved. + +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. diff --git a/node_modules/ansicolors/README.md b/node_modules/ansicolors/README.md new file mode 100644 index 0000000..f3e9d07 --- /dev/null +++ b/node_modules/ansicolors/README.md @@ -0,0 +1,62 @@ +# ansicolors [![build status](https://secure.travis-ci.org/thlorenz/ansicolors.png)](http://next.travis-ci.org/thlorenz/ansicolors) + +Functions that surround a string with ansicolor codes so it prints in color. + +In case you need styles, like `bold`, have a look at [ansistyles](https://github.com/thlorenz/ansistyles). + +## Installation + + npm install ansicolors + +## Usage + +```js +var colors = require('ansicolors'); + +// foreground colors +var redHerring = colors.red('herring'); +var blueMoon = colors.blue('moon'); +var brighBlueMoon = colors.brightBlue('moon'); + +console.log(redHerring); // this will print 'herring' in red +console.log(blueMoon); // this 'moon' in blue +console.log(brightBlueMoon); // I think you got the idea + +// background colors +console.log(colors.bgYellow('printed on yellow background')); +console.log(colors.bgBrightBlue('printed on bright blue background')); + +// mixing background and foreground colors +// below two lines have same result (order in which bg and fg are combined doesn't matter) +console.log(colors.bgYellow(colors.blue('printed on yellow background in blue'))); +console.log(colors.blue(colors.bgYellow('printed on yellow background in blue'))); +``` + +## Advanced API + +**ansicolors** allows you to access opening and closing escape sequences separately. + +```js +var colors = require('ansicolors'); + +function inspect(obj, depth) { + return require('util').inspect(obj, false, depth || 5, true); +} + +console.log('open blue', inspect(colors.open.blue)); +console.log('close bgBlack', inspect(colors.close.bgBlack)); + +// => open blue '\u001b[34m' +// close bgBlack '\u001b[49m' +``` + +## Tests + +Look at the [tests](https://github.com/thlorenz/ansicolors/blob/master/test/ansicolors.js) to see more examples and/or run them via: + + npm explore ansicolors && npm test + +## Alternatives + +**ansicolors** tries to meet simple use cases with a very simple API. However, if you need a more powerful ansi formatting tool, +I'd suggest to look at the [features](https://github.com/TooTallNate/ansi.js#features) of the [ansi module](https://github.com/TooTallNate/ansi.js). diff --git a/node_modules/ansicolors/ansicolors.js b/node_modules/ansicolors/ansicolors.js new file mode 100644 index 0000000..16b2586 --- /dev/null +++ b/node_modules/ansicolors/ansicolors.js @@ -0,0 +1,65 @@ +// ColorCodes explained: http://www.termsys.demon.co.uk/vtansi.htm +'use strict'; + +var colorNums = { + white : 37 + , black : 30 + , blue : 34 + , cyan : 36 + , green : 32 + , magenta : 35 + , red : 31 + , yellow : 33 + , brightBlack : 90 + , brightRed : 91 + , brightGreen : 92 + , brightYellow : 93 + , brightBlue : 94 + , brightMagenta : 95 + , brightCyan : 96 + , brightWhite : 97 + } + , backgroundColorNums = { + bgBlack : 40 + , bgRed : 41 + , bgGreen : 42 + , bgYellow : 43 + , bgBlue : 44 + , bgMagenta : 45 + , bgCyan : 46 + , bgWhite : 47 + , bgBrightBlack : 100 + , bgBrightRed : 101 + , bgBrightGreen : 102 + , bgBrightYellow : 103 + , bgBrightBlue : 104 + , bgBrightMagenta : 105 + , bgBrightCyan : 106 + , bgBrightWhite : 107 + } + , open = {} + , close = {} + , colors = {} + ; + +Object.keys(colorNums).forEach(function (k) { + var o = open[k] = '\u001b[' + colorNums[k] + 'm'; + var c = close[k] = '\u001b[39m'; + + colors[k] = function (s) { + return o + s + c; + }; +}); + +Object.keys(backgroundColorNums).forEach(function (k) { + var o = open[k] = '\u001b[' + backgroundColorNums[k] + 'm'; + var c = close[k] = '\u001b[49m'; + + colors[k] = function (s) { + return o + s + c; + }; +}); + +module.exports = colors; +colors.open = open; +colors.close = close; diff --git a/node_modules/ansicolors/package.json b/node_modules/ansicolors/package.json new file mode 100644 index 0000000..cda0c75 --- /dev/null +++ b/node_modules/ansicolors/package.json @@ -0,0 +1,23 @@ +{ + "name": "ansicolors", + "version": "0.3.2", + "description": "Functions that surround a string with ansicolor codes so it prints in color.", + "main": "ansicolors.js", + "scripts": { + "test": "node test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/ansicolors.git" + }, + "keywords": [ + "ansi", + "colors", + "highlight", + "string" + ], + "author": "Thorsten Lorenz (thlorenz.com)", + "license": "MIT", + "readmeFilename": "README.md", + "gitHead": "858847ca28e8b360d9b70eee0592700fa2ab087d" +} diff --git a/node_modules/ansicolors/test/ansicolors.js b/node_modules/ansicolors/test/ansicolors.js new file mode 100644 index 0000000..4945393 --- /dev/null +++ b/node_modules/ansicolors/test/ansicolors.js @@ -0,0 +1,71 @@ +'use strict'; + +var assert = require('assert') + , colors = require('..') + , open = colors.open + , close = colors.close + +console.log('Foreground colors ..'); + +assert.equal(colors.white('printed in white'), '\u001b[37mprinted in white\u001b[39m'); + +assert.equal(colors.black('printed in black'), '\u001b[30mprinted in black\u001b[39m'); +assert.equal(colors.brightBlack('printed in bright black'), '\u001b[90mprinted in bright black\u001b[39m'); + +assert.equal(colors.green('printed in green'), '\u001b[32mprinted in green\u001b[39m'); +assert.equal(colors.brightGreen('printed in bright green'), '\u001b[92mprinted in bright green\u001b[39m'); + +assert.equal(colors.red('printed in red'), '\u001b[31mprinted in red\u001b[39m'); +assert.equal(colors.brightRed('printed in bright red'), '\u001b[91mprinted in bright red\u001b[39m'); + +console.log('OK'); + +console.log('Background colors ..'); + +assert.equal( + colors.bgBlack('printed with black background') + , '\u001b[40mprinted with black background\u001b[49m' +); + +assert.equal( + colors.bgYellow('printed with yellow background') + , '\u001b[43mprinted with yellow background\u001b[49m' +); +assert.equal( + colors.bgBrightYellow('printed with bright yellow background') + , '\u001b[103mprinted with bright yellow background\u001b[49m' +); + +assert.equal( + colors.bgWhite('printed with white background') + , '\u001b[47mprinted with white background\u001b[49m' +); + +console.log('OK'); + +console.log('Mixing background and foreground colors ..'); + +assert.equal( + colors.blue(colors.bgYellow('printed in blue with yellow background')) + , '\u001b[34m\u001b[43mprinted in blue with yellow background\u001b[49m\u001b[39m' +); +assert.equal( + colors.bgYellow(colors.blue('printed in blue with yellow background again')) + , '\u001b[43m\u001b[34mprinted in blue with yellow background again\u001b[39m\u001b[49m' +); + +console.log('OK'); + +console.log('Open ...'); + +assert.equal(open.black, '\u001b[30m'); +assert.equal(open.bgYellow, '\u001b[43m'); + +console.log('OK'); + +console.log('Close ...'); + +assert.equal(close.black, '\u001b[39m'); +assert.equal(close.bgYellow, '\u001b[49m'); + +console.log('OK'); diff --git a/node_modules/any-promise/.jshintrc b/node_modules/any-promise/.jshintrc new file mode 100644 index 0000000..979105e --- /dev/null +++ b/node_modules/any-promise/.jshintrc @@ -0,0 +1,4 @@ +{ + "node":true, + "strict":true +} diff --git a/node_modules/any-promise/.npmignore b/node_modules/any-promise/.npmignore new file mode 100644 index 0000000..1354abc --- /dev/null +++ b/node_modules/any-promise/.npmignore @@ -0,0 +1,7 @@ +.git* +test/ +test-browser/ +build/ +.travis.yml +*.swp +Makefile diff --git a/node_modules/any-promise/LICENSE b/node_modules/any-promise/LICENSE new file mode 100644 index 0000000..9187fe5 --- /dev/null +++ b/node_modules/any-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2014-2016 Kevin Beaty + +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. diff --git a/node_modules/any-promise/README.md b/node_modules/any-promise/README.md new file mode 100644 index 0000000..174bea4 --- /dev/null +++ b/node_modules/any-promise/README.md @@ -0,0 +1,161 @@ +## Any Promise + +[![Build Status](https://secure.travis-ci.org/kevinbeaty/any-promise.svg)](http://travis-ci.org/kevinbeaty/any-promise) + +Let your library support any ES 2015 (ES6) compatible `Promise` and leave the choice to application authors. The application can *optionally* register its preferred `Promise` implementation and it will be exported when requiring `any-promise` from library code. + +If no preference is registered, defaults to the global `Promise` for newer Node.js versions. The browser version defaults to the window `Promise`, so polyfill or register as necessary. + +### Usage with global Promise: + +Assuming the global `Promise` is the desired implementation: + +```bash +# Install any libraries depending on any-promise +$ npm install mz +``` + +The installed libraries will use global Promise by default. + +```js +// in library +var Promise = require('any-promise') // the global Promise + +function promiseReturningFunction(){ + return new Promise(function(resolve, reject){...}) +} +``` + +### Usage with registration: + +Assuming `bluebird` is the desired Promise implementation: + +```bash +# Install preferred promise library +$ npm install bluebird +# Install any-promise to allow registration +$ npm install any-promise +# Install any libraries you would like to use depending on any-promise +$ npm install mz +``` + +Register your preference in the application entry point before any other `require` of packages that load `any-promise`: + +```javascript +// top of application index.js or other entry point +require('any-promise/register/bluebird') + +// -or- Equivalent to above, but allows customization of Promise library +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +Now that the implementation is registered, you can use any package depending on `any-promise`: + + +```javascript +var fsp = require('mz/fs') // mz/fs will use registered bluebird promises +var Promise = require('any-promise') // the registered bluebird promise +``` + +It is safe to call `register` multiple times, but it must always be with the same implementation. + +Again, registration is *optional*. It should only be called by the application user if overriding the global `Promise` implementation is desired. + +### Optional Application Registration + +As an application author, you can *optionally* register a preferred `Promise` implementation on application startup (before any call to `require('any-promise')`: + +You must register your preference before any call to `require('any-promise')` (by you or required packages), and only one implementation can be registered. Typically, this registration would occur at the top of the application entry point. + + +#### Registration shortcuts + +If you are using a known `Promise` implementation, you can register your preference with a shortcut: + + +```js +require('any-promise/register/bluebird') +// -or- +import 'any-promise/register/q'; +``` + +Shortcut registration is the preferred registration method as it works in the browser and Node.js. It is also convenient for using with `import` and many test runners, that offer a `--require` flag: + +``` +$ ava --require=any-promise/register/bluebird test.js +``` + +Current known implementations include `bluebird`, `q`, `when`, `rsvp`, `es6-promise`, `promise`, `native-promise-only`, `pinkie`, `vow` and `lie`. If you are not using a known implementation, you can use another registration method described below. + + +#### Basic Registration + +As an alternative to registration shortcuts, you can call the `register` function with the preferred `Promise` implementation. The benefit of this approach is that a `Promise` library can be required by name without being a known implementation. This approach does NOT work in the browser. To use `any-promise` in the browser use either registration shortcuts or specify the `Promise` constructor using advanced registration (see below). + +```javascript +require('any-promise/register')('when') +// -or- require('any-promise/register')('any other ES6 compatible library (known or otherwise)') +``` + +This registration method will try to detect the `Promise` constructor from requiring the specified implementation. If you would like to specify your own constructor, see advanced registration. + + +#### Advanced Registration + +To use the browser version, you should either install a polyfill or explicitly register the `Promise` constructor: + +```javascript +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +This could also be used for registering a custom `Promise` implementation or subclass. + +Your preference will be registered globally, allowing a single registration even if multiple versions of `any-promise` are installed in the NPM dependency tree or are using multiple bundled JavaScript files in the browser. You can bypass this global registration in options: + + +```javascript +require('../register')('es6-promise', {Promise: require('es6-promise').Promise, global: false}) +``` + +### Library Usage + +To use any `Promise` constructor, simply require it: + +```javascript +var Promise = require('any-promise'); + +return Promise + .all([xf, f, init, coll]) + .then(fn); + + +return new Promise(function(resolve, reject){ + try { + resolve(item); + } catch(e){ + reject(e); + } +}); + +``` + +Except noted below, libraries using `any-promise` should only use [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) functions as there is no guarantee which implementation will be chosen by the application author. Libraries should never call `register`, only the application user should call if desired. + + +#### Advanced Library Usage + +If your library needs to branch code based on the registered implementation, you can retrieve it using `var impl = require('any-promise/implementation')`, where `impl` will be the package name (`"bluebird"`, `"when"`, etc.) if registered, `"global.Promise"` if using the global version on Node.js, or `"window.Promise"` if using the browser version. You should always include a default case, as there is no guarantee what package may be registered. + + +### Support for old Node.js versions + +Node.js versions prior to `v0.12` may have contained buggy versions of the global `Promise`. For this reason, the global `Promise` is not loaded automatically for these old versions. If using `any-promise` in Node.js versions versions `<= v0.12`, the user should register a desired implementation. + +If an implementation is not registered, `any-promise` will attempt to discover an installed `Promise` implementation. If no implementation can be found, an error will be thrown on `require('any-promise')`. While the auto-discovery usually avoids errors, it is non-deterministic. It is recommended that the user always register a preferred implementation for older Node.js versions. + +This auto-discovery is only available for Node.jS versions prior to `v0.12`. Any newer versions will always default to the global `Promise` implementation. + +### Related + +- [any-observable](https://github.com/sindresorhus/any-observable) - `any-promise` for Observables. + diff --git a/node_modules/any-promise/implementation.d.ts b/node_modules/any-promise/implementation.d.ts new file mode 100644 index 0000000..c331a56 --- /dev/null +++ b/node_modules/any-promise/implementation.d.ts @@ -0,0 +1,3 @@ +declare var implementation: string; + +export = implementation; diff --git a/node_modules/any-promise/implementation.js b/node_modules/any-promise/implementation.js new file mode 100644 index 0000000..a45ae94 --- /dev/null +++ b/node_modules/any-promise/implementation.js @@ -0,0 +1 @@ +module.exports = require('./register')().implementation diff --git a/node_modules/any-promise/index.d.ts b/node_modules/any-promise/index.d.ts new file mode 100644 index 0000000..9f646c5 --- /dev/null +++ b/node_modules/any-promise/index.d.ts @@ -0,0 +1,73 @@ +declare class Promise implements Promise.Thenable { + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor (callback: (resolve : (value?: R | Promise.Thenable) => void, reject: (error?: any) => void) => void); + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => U | Promise.Thenable): Promise; + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => void): Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch (onRejected?: (error: any) => U | Promise.Thenable): Promise; + + /** + * Make a new promise from the thenable. + * A thenable is promise-like in as far as it has a "then" method. + */ + static resolve (): Promise; + static resolve (value: R | Promise.Thenable): Promise; + + /** + * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error + */ + static reject (error: any): Promise; + + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + */ + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable, T10 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable ]): Promise<[T1, T2, T3, T4]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable]): Promise<[T1, T2, T3]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable]): Promise<[T1, T2]>; + static all (values: [T1 | Promise.Thenable]): Promise<[T1]>; + static all (values: Array>): Promise; + + /** + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + */ + static race (promises: (R | Promise.Thenable)[]): Promise; +} + +declare namespace Promise { + export interface Thenable { + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; + } +} + +export = Promise; diff --git a/node_modules/any-promise/index.js b/node_modules/any-promise/index.js new file mode 100644 index 0000000..74b8548 --- /dev/null +++ b/node_modules/any-promise/index.js @@ -0,0 +1 @@ +module.exports = require('./register')().Promise diff --git a/node_modules/any-promise/loader.js b/node_modules/any-promise/loader.js new file mode 100644 index 0000000..e164914 --- /dev/null +++ b/node_modules/any-promise/loader.js @@ -0,0 +1,78 @@ +"use strict" + // global key for user preferred registration +var REGISTRATION_KEY = '@@any-promise/REGISTRATION', + // Prior registration (preferred or detected) + registered = null + +/** + * Registers the given implementation. An implementation must + * be registered prior to any call to `require("any-promise")`, + * typically on application load. + * + * If called with no arguments, will return registration in + * following priority: + * + * For Node.js: + * + * 1. Previous registration + * 2. global.Promise if node.js version >= 0.12 + * 3. Auto detected promise based on first sucessful require of + * known promise libraries. Note this is a last resort, as the + * loaded library is non-deterministic. node.js >= 0.12 will + * always use global.Promise over this priority list. + * 4. Throws error. + * + * For Browser: + * + * 1. Previous registration + * 2. window.Promise + * 3. Throws error. + * + * Options: + * + * Promise: Desired Promise constructor + * global: Boolean - Should the registration be cached in a global variable to + * allow cross dependency/bundle registration? (default true) + */ +module.exports = function(root, loadImplementation){ + return function register(implementation, opts){ + implementation = implementation || null + opts = opts || {} + // global registration unless explicitly {global: false} in options (default true) + var registerGlobal = opts.global !== false; + + // load any previous global registration + if(registered === null && registerGlobal){ + registered = root[REGISTRATION_KEY] || null + } + + if(registered !== null + && implementation !== null + && registered.implementation !== implementation){ + // Throw error if attempting to redefine implementation + throw new Error('any-promise already defined as "'+registered.implementation+ + '". You can only register an implementation before the first '+ + ' call to require("any-promise") and an implementation cannot be changed') + } + + if(registered === null){ + // use provided implementation + if(implementation !== null && typeof opts.Promise !== 'undefined'){ + registered = { + Promise: opts.Promise, + implementation: implementation + } + } else { + // require implementation if implementation is specified but not provided + registered = loadImplementation(implementation) + } + + if(registerGlobal){ + // register preference globally in case multiple installations + root[REGISTRATION_KEY] = registered + } + } + + return registered + } +} diff --git a/node_modules/any-promise/optional.js b/node_modules/any-promise/optional.js new file mode 100644 index 0000000..f388942 --- /dev/null +++ b/node_modules/any-promise/optional.js @@ -0,0 +1,6 @@ +"use strict"; +try { + module.exports = require('./register')().Promise || null +} catch(e) { + module.exports = null +} diff --git a/node_modules/any-promise/package.json b/node_modules/any-promise/package.json new file mode 100644 index 0000000..5baf14c --- /dev/null +++ b/node_modules/any-promise/package.json @@ -0,0 +1,45 @@ +{ + "name": "any-promise", + "version": "1.3.0", + "description": "Resolve any installed ES6 compatible promise", + "main": "index.js", + "typings": "index.d.ts", + "browser": { + "./register.js": "./register-shim.js" + }, + "scripts": { + "test": "ava" + }, + "repository": { + "type": "git", + "url": "https://github.com/kevinbeaty/any-promise" + }, + "keywords": [ + "promise", + "es6" + ], + "author": "Kevin Beaty", + "license": "MIT", + "bugs": { + "url": "https://github.com/kevinbeaty/any-promise/issues" + }, + "homepage": "http://github.com/kevinbeaty/any-promise", + "dependencies": {}, + "devDependencies": { + "ava": "^0.14.0", + "bluebird": "^3.0.0", + "es6-promise": "^3.0.0", + "is-promise": "^2.0.0", + "lie": "^3.0.0", + "mocha": "^2.0.0", + "native-promise-only": "^0.8.0", + "phantomjs-prebuilt": "^2.0.0", + "pinkie": "^2.0.0", + "promise": "^7.0.0", + "q": "^1.0.0", + "rsvp": "^3.0.0", + "vow": "^0.4.0", + "when": "^3.0.0", + "zuul": "^3.0.0" + } +} diff --git a/node_modules/any-promise/register-shim.js b/node_modules/any-promise/register-shim.js new file mode 100644 index 0000000..9049405 --- /dev/null +++ b/node_modules/any-promise/register-shim.js @@ -0,0 +1,18 @@ +"use strict"; +module.exports = require('./loader')(window, loadImplementation) + +/** + * Browser specific loadImplementation. Always uses `window.Promise` + * + * To register a custom implementation, must register with `Promise` option. + */ +function loadImplementation(){ + if(typeof window.Promise === 'undefined'){ + throw new Error("any-promise browser requires a polyfill or explicit registration"+ + " e.g: require('any-promise/register/bluebird')") + } + return { + Promise: window.Promise, + implementation: 'window.Promise' + } +} diff --git a/node_modules/any-promise/register.d.ts b/node_modules/any-promise/register.d.ts new file mode 100644 index 0000000..97f2fc0 --- /dev/null +++ b/node_modules/any-promise/register.d.ts @@ -0,0 +1,17 @@ +import Promise = require('./index'); + +declare function register (module?: string, options?: register.Options): register.Register; + +declare namespace register { + export interface Register { + Promise: typeof Promise; + implementation: string; + } + + export interface Options { + Promise?: typeof Promise; + global?: boolean + } +} + +export = register; diff --git a/node_modules/any-promise/register.js b/node_modules/any-promise/register.js new file mode 100644 index 0000000..255c6e2 --- /dev/null +++ b/node_modules/any-promise/register.js @@ -0,0 +1,94 @@ +"use strict" +module.exports = require('./loader')(global, loadImplementation); + +/** + * Node.js version of loadImplementation. + * + * Requires the given implementation and returns the registration + * containing {Promise, implementation} + * + * If implementation is undefined or global.Promise, loads it + * Otherwise uses require + */ +function loadImplementation(implementation){ + var impl = null + + if(shouldPreferGlobalPromise(implementation)){ + // if no implementation or env specified use global.Promise + impl = { + Promise: global.Promise, + implementation: 'global.Promise' + } + } else if(implementation){ + // if implementation specified, require it + var lib = require(implementation) + impl = { + Promise: lib.Promise || lib, + implementation: implementation + } + } else { + // try to auto detect implementation. This is non-deterministic + // and should prefer other branches, but this is our last chance + // to load something without throwing error + impl = tryAutoDetect() + } + + if(impl === null){ + throw new Error('Cannot find any-promise implementation nor'+ + ' global.Promise. You must install polyfill or call'+ + ' require("any-promise/register") with your preferred'+ + ' implementation, e.g. require("any-promise/register/bluebird")'+ + ' on application load prior to any require("any-promise").') + } + + return impl +} + +/** + * Determines if the global.Promise should be preferred if an implementation + * has not been registered. + */ +function shouldPreferGlobalPromise(implementation){ + if(implementation){ + return implementation === 'global.Promise' + } else if(typeof global.Promise !== 'undefined'){ + // Load global promise if implementation not specified + // Versions < 0.11 did not have global Promise + // Do not use for version < 0.12 as version 0.11 contained buggy versions + var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version) + return !(version && +version[1] == 0 && +version[2] < 12) + } + + // do not have global.Promise or another implementation was specified + return false +} + +/** + * Look for common libs as last resort there is no guarantee that + * this will return a desired implementation or even be deterministic. + * The priority is also nearly arbitrary. We are only doing this + * for older versions of Node.js <0.12 that do not have a reasonable + * global.Promise implementation and we the user has not registered + * the preference. This preserves the behavior of any-promise <= 0.1 + * and may be deprecated or removed in the future + */ +function tryAutoDetect(){ + var libs = [ + "es6-promise", + "promise", + "native-promise-only", + "bluebird", + "rsvp", + "when", + "q", + "pinkie", + "lie", + "vow"] + var i = 0, len = libs.length + for(; i < len; i++){ + try { + return loadImplementation(libs[i]) + } catch(e){} + } + return null +} diff --git a/node_modules/any-promise/register/bluebird.d.ts b/node_modules/any-promise/register/bluebird.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/bluebird.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/bluebird.js b/node_modules/any-promise/register/bluebird.js new file mode 100644 index 0000000..de0f87e --- /dev/null +++ b/node_modules/any-promise/register/bluebird.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('bluebird', {Promise: require('bluebird')}) diff --git a/node_modules/any-promise/register/es6-promise.d.ts b/node_modules/any-promise/register/es6-promise.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/es6-promise.js b/node_modules/any-promise/register/es6-promise.js new file mode 100644 index 0000000..59bd55b --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('es6-promise', {Promise: require('es6-promise').Promise}) diff --git a/node_modules/any-promise/register/lie.d.ts b/node_modules/any-promise/register/lie.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/lie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/lie.js b/node_modules/any-promise/register/lie.js new file mode 100644 index 0000000..7d305ca --- /dev/null +++ b/node_modules/any-promise/register/lie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('lie', {Promise: require('lie')}) diff --git a/node_modules/any-promise/register/native-promise-only.d.ts b/node_modules/any-promise/register/native-promise-only.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/native-promise-only.js b/node_modules/any-promise/register/native-promise-only.js new file mode 100644 index 0000000..70a5a5e --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('native-promise-only', {Promise: require('native-promise-only')}) diff --git a/node_modules/any-promise/register/pinkie.d.ts b/node_modules/any-promise/register/pinkie.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/pinkie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/pinkie.js b/node_modules/any-promise/register/pinkie.js new file mode 100644 index 0000000..caaf98a --- /dev/null +++ b/node_modules/any-promise/register/pinkie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('pinkie', {Promise: require('pinkie')}) diff --git a/node_modules/any-promise/register/promise.d.ts b/node_modules/any-promise/register/promise.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/promise.js b/node_modules/any-promise/register/promise.js new file mode 100644 index 0000000..746620d --- /dev/null +++ b/node_modules/any-promise/register/promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('promise', {Promise: require('promise')}) diff --git a/node_modules/any-promise/register/q.d.ts b/node_modules/any-promise/register/q.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/q.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/q.js b/node_modules/any-promise/register/q.js new file mode 100644 index 0000000..0fc633a --- /dev/null +++ b/node_modules/any-promise/register/q.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('q', {Promise: require('q').Promise}) diff --git a/node_modules/any-promise/register/rsvp.d.ts b/node_modules/any-promise/register/rsvp.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/rsvp.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/rsvp.js b/node_modules/any-promise/register/rsvp.js new file mode 100644 index 0000000..02b1318 --- /dev/null +++ b/node_modules/any-promise/register/rsvp.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('rsvp', {Promise: require('rsvp').Promise}) diff --git a/node_modules/any-promise/register/vow.d.ts b/node_modules/any-promise/register/vow.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/vow.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/vow.js b/node_modules/any-promise/register/vow.js new file mode 100644 index 0000000..5b6868c --- /dev/null +++ b/node_modules/any-promise/register/vow.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('vow', {Promise: require('vow').Promise}) diff --git a/node_modules/any-promise/register/when.d.ts b/node_modules/any-promise/register/when.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/when.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/when.js b/node_modules/any-promise/register/when.js new file mode 100644 index 0000000..d91c13d --- /dev/null +++ b/node_modules/any-promise/register/when.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('when', {Promise: require('when').Promise}) diff --git a/node_modules/applicationinsights/.eslintignore b/node_modules/applicationinsights/.eslintignore new file mode 100644 index 0000000..d003253 --- /dev/null +++ b/node_modules/applicationinsights/.eslintignore @@ -0,0 +1,4 @@ +**/*.js +/out +/Tests +/types \ No newline at end of file diff --git a/node_modules/applicationinsights/.eslintrc b/node_modules/applicationinsights/.eslintrc new file mode 100644 index 0000000..5640961 --- /dev/null +++ b/node_modules/applicationinsights/.eslintrc @@ -0,0 +1,41 @@ +{ + "env": { + "browser": true, + "es2021": true + }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:security/recommended" + ], + "plugins": [ + "security" + ], + "rules": { + "quotes": ["warn", "double"], // Enabled for auto fixing + "prefer-const": "off", + "prefer-spread": "off", + "no-var": "off", + "no-extra-boolean-cast": "off", + "prefer-rest-params": "off", + "no-case-declarations": "off", + "no-prototype-builtins": "off", + "no-useless-escape": "off", // Suppressing Error -- need to Review Later + "no-trailing-spaces": [ "warn", { "skipBlankLines": true }],// Enabled for auto fixing + "no-const-assign": "error", + "comma-dangle": [ "error", "never" ], // Enabled for auto fixing + "security/detect-object-injection": "off", // Suppress Warning -- need to Review Later + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/no-unused-vars": [ "warn", { "vars": "all", "args": "none", "argsIgnorePattern": "^_", "ignoreRestSiblings": true } ], + "@typescript-eslint/triple-slash-reference": "off", + "@typescript-eslint/no-inferrable-types": "off", + "@typescript-eslint/no-this-alias": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-extra-semi": "error", // Enabled for auto fixing + "@typescript-eslint/no-non-null-assertion": "error" + } +} diff --git a/node_modules/applicationinsights/CODE_OF_CONDUCT.md b/node_modules/applicationinsights/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3985215 --- /dev/null +++ b/node_modules/applicationinsights/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns \ No newline at end of file diff --git a/node_modules/applicationinsights/CONTRIBUTING.md b/node_modules/applicationinsights/CONTRIBUTING.md new file mode 100644 index 0000000..d7c8c60 --- /dev/null +++ b/node_modules/applicationinsights/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +# How to contribute to the Application Insights Node.js SDK + + +1. Fork this repo +2. Clone your fork locally (`git clone https://github.com//ApplicationInsights-node.js +3. Open a terminal and move into your local copy (`cd ApplicationInsights-node.js`) +4. Install all dependencies with `npm install`. +5. Build project + ```bash + npm run build + ``` +6. Run unit tests + ```bash + npm run test + ``` +7. Run functional and back compatibility tests, start docker then run following commands: + ```bash + npm run functionaltest + ``` + _Note: Functional tests require Docker_ + +8. Run back compatibility tests to ckeck older version of Node.js runtime and Typescript. + ```bash + npm run backcompattest + ``` +--- \ No newline at end of file diff --git a/node_modules/applicationinsights/LICENSE b/node_modules/applicationinsights/LICENSE new file mode 100644 index 0000000..d275a82 --- /dev/null +++ b/node_modules/applicationinsights/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Microsoft Corporation + +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. \ No newline at end of file diff --git a/node_modules/applicationinsights/NOTICE b/node_modules/applicationinsights/NOTICE new file mode 100644 index 0000000..ad4fbe1 --- /dev/null +++ b/node_modules/applicationinsights/NOTICE @@ -0,0 +1,17 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at https://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. \ No newline at end of file diff --git a/node_modules/applicationinsights/PRIVACY b/node_modules/applicationinsights/PRIVACY new file mode 100644 index 0000000..4d6a4ea --- /dev/null +++ b/node_modules/applicationinsights/PRIVACY @@ -0,0 +1,3 @@ +# Data Collection + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. diff --git a/node_modules/applicationinsights/README.md b/node_modules/applicationinsights/README.md new file mode 100644 index 0000000..d1bf200 --- /dev/null +++ b/node_modules/applicationinsights/README.md @@ -0,0 +1,603 @@ +# Application Insights for Node.js + +[![npm version](https://badge.fury.io/js/applicationinsights.svg)](http://badge.fury.io/js/applicationinsights) + + +## `applicationinsights@3.0.0-beta` + +An experimental / beta version of the SDK is also available. It is built on top of [OpenTelemetry](https://opentelemetry.io/), more information about beta version available [here](https://github.com/microsoft/ApplicationInsights-node.js/tree/beta#readme). + +```zsh +npm install applicationinsights@beta +``` + +[Azure Application Insights][] monitors your backend services and components after +you deploy them to help you [discover and rapidly diagnose performance and other +issues][]. Add this SDK to your Node.js services to include deep info about Node.js +processes and their external dependencies such as database and cache services. +You can use this SDK for your Node.js services hosted anywhere: your datacenter, +Azure VMs and Web Apps, and even other public clouds. + +[Azure Application Insights]: https://azure.microsoft.com/documentation/articles/app-insights-overview/ +[discover and rapidly diagnose performance and other issues]: https://docs.microsoft.com/azure/application-insights/app-insights-detect-triage-diagnose + +This library tracks the following out-of-the-box: +- Incoming and outgoing HTTP requests +- Important system metrics such as CPU usage +- Unhandled exceptions +- Events from many popular third-party libraries ([see Automatic third-party instrumentation](#automatic-third-party-instrumentation)) + +You can manually track more aspects of your app and system using the API described in the +[Track custom telemetry](#track-custom-telemetry) section. + + + +## Supported Node.JS versions + +| Platform Version | Supported | +|------------------|-------------------------------------------------| +| Node.JS `v18` | ✅ | +| Node.JS `v17` | ✅ | +| Node.JS `v16` | ✅ | +| Node.JS `v15` | ✅ | +| Node.JS `v14` | ✅ | +| Node.JS `v12` | ✅ | +| Node.JS `v10` | ✅ | +| Node.JS `v8` | ✅ | + + +## Getting Started + +> *Important:* On March 31st, 2025, support for instrumentation key ingestion will end. Instrumentation key ingestion will continue to work, but we’ll no longer provide updates or support for the feature. [Transition to connection strings](https://docs.microsoft.com/en-us/azure/azure-monitor/app/migrate-from-instrumentation-keys-to-connection-strings) to take advantage of [new capabilities](https://docs.microsoft.com/en-us/azure/azure-monitor/app/migrate-from-instrumentation-keys-to-connection-strings#new-capabilities). + +1. Create an Application Insights resource in Azure by following [these instructions][]. +2. Grab the _Connection String_ from the resource you created in + step 1. Later, you'll either add it to your app's environment variables or + use it directly in your scripts. +3. Add the Application Insights Node.js SDK to your app's dependencies and + package.json: + ```bash + npm install --save applicationinsights + ``` + > *Note:* If you're using TypeScript, please install @types/node package to prevent build issues, this npm package contains built-in typings. +4. As early as possible in your app's code, load the Application Insights + package: + ```javascript + let appInsights = require('applicationinsights'); + ``` +5. Configure the local SDK by calling `appInsights.setup('YOUR_CONNECTION_STRING');`, using + the connection string you grabbed in step 2. Or put it in the + `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable and call + `appInsights.setup()` without parameters. + > For more configuration options see below. +6. Finally, start automatically collecting and sending data by calling + `appInsights.start();`. + +[these instructions]: https://docs.microsoft.com/azure/application-insights/app-insights-nodejs + + +## Basic Usage + +> *Important:* `applicationinsights` must be setup *and* started *before* you import anything else. There may be resulting telemetry loss if other libraries are imported first. + +For out-of-the-box collection of HTTP requests, popular third-party library events, +unhandled exceptions, and system metrics: + +```javascript +let appInsights = require("applicationinsights"); +appInsights.setup("YOUR_CONNECTION_STRING").start(); +``` + +* If the connection string is set in the environment variable + APPLICATIONINSIGHTS\_CONNECTION\_STRING, `.setup()` can be called with no + arguments. This makes it easy to use different connection strings for different + environments. + +Load the Application Insights library (i.e. `require("applicationinsights")`) as +early as possible in your scripts, before loading other packages. This is needed +so that the Application Insights library can prepare later packages for tracking. +If you encounter conflicts with other libraries doing similar preparation, try +loading the Application Insights library after those. + +Because of the way JavaScript handles callbacks, additional work is necessary to +track a request across external dependencies and later callbacks. By default +this additional tracking is enabled; disable it by calling +`setAutoDependencyCorrelation(false)` as described in the +Configuration section below. + +## Azure Functions + +Auto correlation in Azure Functions is supported automatically starting in 2.4.0, if using previous version following code should be added to handle the correlation available in Azure Functions environment. + + +```js +... + +// Default export wrapped with Application Insights FaaS context propagation +export default async function contextPropagatingHttpTrigger(context, req) { + // Start an AI Correlation Context using the provided Function context + const correlationContext = appInsights.startOperation(context, req); + + // Wrap the Function runtime with correlationContext + return appInsights.wrapWithCorrelationContext(async () => { + const startTime = Date.now(); // Start trackRequest timer + + // Run the Function + const result = await httpTrigger(context, req); + + // Track Request on completion + appInsights.defaultClient.trackRequest({ + name: context.req.method + " " + context.req.url, + resultCode: context.res.status, + success: true, + url: req.url, + time: new Date(startTime), + duration: Date.now() - startTime, + id: correlationContext.operation.parentId, + }); + appInsights.defaultClient.flush(); + + return result; + }, correlationContext)(); +}; +``` + + +## Configuration + +The appInsights object provides a number of methods to setup SDK behavior. They are +listed in the following snippet with their default values. + +```javascript +let appInsights = require("applicationinsights"); +appInsights.setup("") + .setAutoDependencyCorrelation(true) + .setAutoCollectRequests(true) + .setAutoCollectPerformance(true, true) + .setAutoCollectExceptions(true) + .setAutoCollectDependencies(true) + .setAutoCollectConsole(true, false) + .setUseDiskRetryCaching(true) + .setAutoCollectPreAggregatedMetrics(true) + .setSendLiveMetrics(false) + .setAutoCollectHeartbeat(false) + .setAutoCollectIncomingRequestAzureFunctions(true) + .setInternalLogging(false, true) + .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C) + .enableWebInstrumentation(false) + .start(); +``` + +Please review their descriptions in your IDE's built-in type hinting, or [applicationinsights.ts](https://github.com/microsoft/ApplicationInsights-node.js/tree/develop/applicationinsights.ts) for +detailed information on what these control, and optional secondary arguments. + +Note that by default `setAutoCollectConsole` is configured to *exclude* calls to `console.log` +(and other `console` methods). By default, only calls to supported third-party loggers +(e.g. `winston`, `bunyan`) will be collected. You can change this behavior to *include* calls +to `console` methods by using `setAutoCollectConsole(true, true)`. + +Note that by default `enableWebInstrumentation` will use the connection string for SDK initialization. If you want to use a different one, you can set it as `enableWebInstrumentation(true, "your-connection-string")`. + +The TelemetryClient object contains a `config` property with many optional settings. These can be set as follows: +``` +client.config.PROPERTYNAME = VALUE; +``` +These properties are client specific, so you can configure `appInsights.defaultClient` +separately from clients created with `new appInsights.TelemetryClient()`. + +| Property | Description | +| ------------------------------- |------------------------------------------------------------------------------------------------------------| +| instrumentationKey | Application Insights Instrumentation Key | +| endpointUrl | The ingestion endpoint to send telemetry payloads to | +| proxyHttpUrl | A proxy server for SDK HTTP traffic (Optional, Default pulled from `http_proxy` environment variable) | +| proxyHttpsUrl | A proxy server for SDK HTTPS traffic (Optional, Default pulled from `https_proxy` environment variable) | +| maxBatchSize | The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default `250`) | +| maxBatchIntervalMs | The maximum amount of time to wait to for a payload to reach maxBatchSize (Default `15000`) | +| disableAppInsights | A flag indicating if telemetry transmission is disabled (Default `false`) | +| samplingPercentage | The percentage of telemetry items tracked that should be transmitted (Default `100`) | +| correlationIdRetryIntervalMs | The time to wait before retrying to retrieve the id for cross-component correlation (Default `30000`) | +| correlationHeaderExcludedDomains| A list of domains to exclude from cross-component correlation header injection (Default See [Config.ts][]) | +| ignoreLegacyHeaders | Disable including legacy headers in outgoing requests, x-ms-request-id | +| distributedTracingMode | Sets the distributed tracing modes (Default=AI) | +| enableAutoCollectExternalLoggers| Sets the state of console. If true logger activity will be sent to Application Insights | +| enableAutoCollectConsole | Sets the state of logger tracking (enabled by default for third-party loggers only). If true, logger auto collection will include console.log calls (default false) | +| enableAutoCollectExceptions | Sets the state of exception tracking (enabled by default). If true uncaught exceptions will be sent to Application Insights | +| enableAutoCollectPerformance | Sets the state of performance tracking (enabled by default). If true performance counters will be collected every second and sent to Application Insights | +| enableAutoCollectExtendedMetrics| Sets the state of performance tracking (enabled by default). If true, extended metrics counters will be collected every minute and sent to Application Insights | +| enableAutoCollectPreAggregatedMetrics | Sets the state of pre aggregated metrics tracking (enabled by default). If true pre aggregated metrics will be collected every minute and sent to Application Insights | +| enableAutoCollectHeartbeat | Sets the state of request tracking (enabled by default). If true HeartBeat metric data will be collected every 15 minutes and sent to Application Insights | +| enableAutoCollectRequests | Sets the state of request tracking (enabled by default). If true requests will be sent to Application Insights | +| enableAutoCollectDependencies | Sets the state of dependency tracking (enabled by default). If true dependencies will be sent to Application Insights | +| enableAutoDependencyCorrelation| Sets the state of automatic dependency correlation (enabled by default). If true dependencies will be correlated with requests | +| enableAutoCollectIncomingRequestAzureFunctions| Enable automatic incoming request tracking when running in Azure Functions (disabled by default). | +| enableUseAsyncHooks | Sets the state of automatic dependency correlation (enabled by default). If true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. | +| enableUseDiskRetryCaching | If true events that occurred while client is offline will be cached on disk | +| enableResendInterval | The wait interval for resending cached events. | +| enableMaxBytesOnDisk | The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. | +| enableInternalDebugLogging | Enables debug and warning logging for AppInsights itself. If true, enables debug logging | +| enableInternalWarningLogging | Enables debug and warning logging for AppInsights itself. If true, enables warning logging | +| enableSendLiveMetrics | Enables communication with Application Insights Live Metrics. If true, enables communication with the live metrics service | +| disableAllExtendedMetrics | Disable all environment variables set | +| extendedMetricDisablers | Disable individual environment variables set. `"extendedMetricDisablers": "..."` | +| noDiagnosticChannel | In order to track context across asynchronous calls, some changes are required in third party libraries such as mongodb and redis. By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries. This property is to disable the feature. Note that by setting this flag, events may no longer be correctly associated with the right operation. | +| noPatchModules | Disable individual monkey-patches. Set `noPatchModules` to a comma separated list of packages to disable. e.g. `"noPatchModules": "console,redis"` to avoid patching the console and redis packages. The following modules are available: `azuresdk, bunyan, console, mongodb, mongodb-core, mysql, redis, winston, pg`, and `pg-pool`. Visit the [diagnostic-channel-publishers' README](https://github.com/microsoft/node-diagnostic-channel/blob/master/src/diagnostic-channel-publishers/README.md) for information about exactly which versions of these packages are patched. | +| noHttpAgentKeepAlive | HTTPS without a passed in agent | +| httpAgent | An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) | +| httpsAgent | An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) +| aadTokenCredential| Azure Credential instance to be used to authenticate the App. [AAD Identity Credential Classes](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#credential-classes) +| enableWebInstrumentation(Preview)| Sets the state of automatic web Instrumentation (Optional, disabled by default). If true, web instrumentation will be enabled on valid node server http response with the connection string used for SDK initialization +| webInstrumentationConnectionString(Preview)| Sets connection string used for web Instrumentation (Optional, Default undefined)| +| webInstrumentationSrc(Preview)| Sets web Instrumentation CDN url (Optional). see more details at [ApplicationInsights JavaScript SDK](https://github.com/microsoft/ApplicationInsights-JS)| +| webInstrumentationConfig(Preview)| Sets web Instrumentation config (Optional). see more details at [ApplicationInsights JavaScript SDK](https://github.com/microsoft/ApplicationInsights-JS)| | + +[Config.ts]: https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/Library/Config.ts + +All these properties except httpAgent, httpsAgent and aadTokenCredential could be configured using configuration file `applicationinsights.json` located under root folder of applicationinsights package installation folder, Ex: `node_modules/applicationinsights`. These configuration values will be applied to all TelemetryClients created in the SDK. + + +```javascript +{ + "samplingPercentage": 80, + "enableAutoCollectExternalLoggers": true, + "enableAutoCollectExceptions": true, + "enableAutoCollectHeartbeat": true, + "enableSendLiveMetrics": true, + ... +} + +``` + +Custom JSON file could be provided using `APPLICATIONINSIGHTS_CONFIGURATION_FILE` environment variable. + +```javascript +process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "C:/applicationinsights/config/customConfig.json" + +// Application Insights SDK setup.... +``` + +### Sampling + +By default, the SDK will send all collected data to the Application Insights service. If you collect a lot of data, you might want to enable sampling to reduce the amount of data sent. Set the `samplingPercentage` field on the Config object of a Client to accomplish this. Setting `samplingPercentage` to 100 (the default) means all data will be sent, and 0 means nothing will be sent. + +If you are using automatic correlation, all data associated with a single request will be included or excluded as a unit. + +Add code such as the following to enable sampling: + +```javascript +const appInsights = require("applicationinsights"); +appInsights.setup(""); +appInsights.defaultClient.config.samplingPercentage = 33; // 33% of all telemetry will be sent to Application Insights +appInsights.start(); +``` + +### Multiple roles for multi-component applications + +If your application consists of multiple components that you wish to instrument all with the same Instrumentation Key and still see these components as separate units in the Portal as if they were using separate Instrumentation Keys (for example, as separate nodes on the Application Map) you may need to manually configure the RoleName field to distinguish one component's telemetry from other components sending data to your Application Insights resource. (See [Monitor multi-component applications with Application Insights (preview)](https://docs.microsoft.com/azure/application-insights/app-insights-monitor-multi-role-apps)) + +Use the following to set the RoleName field: + +```javascript +const appInsights = require("applicationinsights"); +appInsights.setup(""); +appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = "MyRoleName"; +appInsights.start(); +``` + +If running in Azure App service or Azure functions the SDK will automatically populate the cloud role when following code is added: +```javascript +const appInsights = require("applicationinsights"); +appInsights.setup(""); +appInsights.defaultClient.setAutoPopulateAzureProperties(true); +appInsights.start(); +``` + +### Automatic web Instrumentation[Preview] + + Automatic web Instrumentation is currently in **Preview**. For node server with configuration `enableWebInstrumentation` set to `true` or environment variable `APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_ENABLED = true`, web Instrumentation will be enabled on node server response when all of the following requirements are met: + +- Response has status code `200`. +- Response method is `GET`. +- Sever response has `Content-Type` html. +- Server response must have both `` and `` Tags. +- If response is compressed, it must have only one `Content-Encoding` type, and encoding type must be one of `gzip`, `br` or `deflate`. +- Response does not contain current /backup web Instrumentation CDN endpoints. (current and backup Web Instrumentation CDN endpoints [here](https://github.com/microsoft/ApplicationInsights-JS#active-public-cdn-endpoints)) + +web Instrumentation CDN endpoint can be changed by setting environment variable `APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE = "web Instrumentation CDN endpoints"`. +web Instrumentation connection string can be changed by setting environment variable `APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_CONNECTION_STRING = "web Instrumentation connection string"` + +**Note:** web Instrumentation may slow down server response time, especially when response size is large or response is compressed. For the case in which some middle layers are applied, it may result in web Instrumentation not working and original response will be returned. + +### Automatic third-party instrumentation + +In order to track context across asynchronous calls, some changes are required in third party libraries such as mongodb and redis. +By default ApplicationInsights will use [`diagnostic-channel-publishers`](https://github.com/microsoft/node-diagnostic-channel/tree/master/src/diagnostic-channel-publishers) +to monkey-patch some of these libraries. +This can be disabled by setting the `APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL` environment variable. Note that by setting that +environment variable, events may no longer be correctly associated with the right operation. Individual monkey-patches can be +disabled by setting the `APPLICATION_INSIGHTS_NO_PATCH_MODULES` environment variable to a comma separated list of packages to +disable, e.g. `APPLICATION_INSIGHTS_NO_PATCH_MODULES=console,redis` to avoid patching the `console` and `redis` packages. + +The following modules are available: `azuresdk`, `bunyan`, `console`, `mongodb`, `mongodb-core`, `mysql`, `redis`, `winston`, +`pg`, and `pg-pool`. Visit the [diagnostic-channel-publishers' README](https://github.com/microsoft/node-diagnostic-channel/blob/master/src/diagnostic-channel-publishers/README.md) +for information about exactly which versions of these packages are patched. + +Automatic instrumentation for several Azure SDKs is also enabled, currently Cognitive Search, Communication Common and Cosmos DB SDKs are not supported. +[Javascript Azure SDKs](https://azure.github.io/azure-sdk/releases/latest/index.html#javascript) + +The `bunyan`, `winston`, and `console` patches will generate Application Insights Trace events based on whether `setAutoCollectConsole` is enabled. +The rest will generate Application Insights Dependency events based on whether `setAutoCollectDependencies` is enabled. Make sure that `applicationinsights` is imported **before** any 3rd-party packages for them to be instrumented successfully. + + +### Live Metrics +To enable sending live metrics of your app to Azure, use `setSendLiveMetrics(true)`. Filtering of live metrics in the Portal is currently not supported. + +### Extended Metrics +>***Note:*** The ability to send extended native metrics was added in version `1.4.0` + +To enable sending extended native metrics of your app to Azure, simply install the separate native metrics package. The SDK will automatically load it when it is installed and start collecting Node.js native metrics. +```zsh +npm install applicationinsights-native-metrics +``` +Currently, the native metrics package performs autocollection of Garbage Collection CPU time, Event Loop ticks, and heap usage: +- **Garbage Collection:** The amount of CPU time spent on each type of garbage collection, and how many occurrences of each type. +- **Event Loop:** How many ticks occurred and how much CPU time was spent in total. +- **Heap vs Non-Heap:** How much of your app's memory usage is in the heap or non-heap. + +### Distributed Tracing Modes +By default, this SDK will send headers understood by other applications/services instrumented with an Application Insights SDK. You can optionally enable sending/receiving of [W3C Trace Context](https://github.com/w3c/trace-context) headers in addition to the existing AI headers, so you will not break correlation with any of your existing legacy services. Enabling W3C headers will allow your app to correlate with other services not instrumented with Application Insights, but do adopt this W3C standard. + +```js +const appInsights = require("applicationinsights"); +appInsights + .setup("") + .setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C) + .start() +``` + +## Track custom telemetry + +You can track any request, event, metric or exception using the Application +Insights client. Examples follow: + +```javascript +let appInsights = require("applicationinsights"); +appInsights.setup().start(); // assuming connection string is in environment variables. start() can be omitted to disable any non-custom data +let client = appInsights.defaultClient; +client.trackEvent({name: "my custom event", properties: {customProperty: "custom property value"}}); +client.trackException({exception: new Error("handled exceptions can be logged with this method")}); +client.trackMetric({name: "custom metric", value: 3}); +client.trackTrace({message: "trace message"}); +client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"}); +client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true}); + +let http = require("http"); +http.createServer( (req, res) => { + client.trackNodeHttpRequest({request: req, response: res}); // Place at the beginning of your request handler +}); +``` + +Note that custom properties are converted to their string representation before being sent, see [Using properties](https://docs.microsoft.com/azure/azure-monitor/app/api-custom-events-metrics#properties) for more information. + +An example utility using `trackMetric` to measure how long event loop scheduling takes: + +```javascript +function startMeasuringEventLoop() { + var startTime = process.hrtime(); + var sampleSum = 0; + var sampleCount = 0; + + // Measure event loop scheduling delay + setInterval(() => { + var elapsed = process.hrtime(startTime); + startTime = process.hrtime(); + sampleSum += elapsed[0] * 1e9 + elapsed[1]; + sampleCount++; + }, 0); + + // Report custom metric every second + setInterval(() => { + var samples = sampleSum; + var count = sampleCount; + sampleSum = 0; + sampleCount = 0; + + if (count > 0) { + var avgNs = samples / count; + var avgMs = Math.round(avgNs / 1e6); + client.trackMetric({name: "Event Loop Delay", value: avgMs}); + } + }, 1000); +} +``` + +## Preprocess data with Telemetry Processors + +```javascript +public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, Error, correlationContext }) => boolean) +``` + +You can process and filter collected data before it is sent for retention using +_Telemetry Processors_. Telemetry processors are called one by one in the +order they were added before the telemetry item is sent to the cloud. + +If a telemetry processor returns false that telemetry item will not be sent. + +All telemetry processors receive the telemetry data and its envelope to inspect and +modify. They also receive a context object. The contents of this object is defined by +the `contextObjects` parameter when calling a track method for manually tracked telemetry. +For automatically collected telemetry, this object is filled with available request information +and the persistent request context as provided by `appInsights.getCorrelationContext()` (if +automatic dependency correlation is enabled). + +The TypeScript type for a telemetry processor is: + +```typescript +telemetryProcessor: (envelope: ContractsModule.Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, Error, correlationContext }) => boolean; +``` + +For example, a processor that removes stack trace data from exceptions might be +written and added as follows: + +```javascript +function removeStackTraces ( envelope, context ) { + if (envelope.data.baseType === "ExceptionData") { + var data = envelope.data.baseData; + if (data.exceptions && data.exceptions.length > 0) { + for (var i = 0; i < data.exceptions.length; i++) { + var exception = data.exceptions[i]; + exception.parsedStack = null; + exception.hasFullStack = false; + } + } + // Add extra properties + var originalError = context["Error"]; + if(originalError && originalError.prop){ + data.properties = data.properties || {}; + data.properties.customProperty = originalError.prop; + } + } + return true; +} + +appInsights.defaultClient.addTelemetryProcessor(removeStackTraces); +``` + +More info on the telemetry API is available in [the docs][]. + +[the docs]: https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/ + +## Use multiple Application Insights resources + +You can create multiple Azure Application Insights resources and send different +data to each by using their respective connection string. For +example: + +```javascript +let appInsights = require("applicationinsights"); + +// configure auto-collection under one Connection String +appInsights.setup("").start(); + +// track some events manually under another connection string +let otherClient = new appInsights.TelemetryClient(""); +otherClient.trackEvent({name: "my custom event"}); +``` + +## Examples + +* Track dependencies + + ```javascript + let appInsights = require("applicationinsights"); + let client = new appInsights.TelemetryClient(); + + var success = false; + let startTime = Date.now(); + // execute dependency call here.... + let duration = Date.now() - startTime; + success = true; + + client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:duration, resultCode:0, success: true, dependencyTypeName: "ZSQL"}); + ``` + +* Assign custom properties to be included with all events + + ```javascript + appInsights.defaultClient.commonProperties = { + environment: process.env.SOME_ENV_VARIABLE + }; + ``` + +* Manually track all HTTP GET requests + + Note that all requests are tracked by default. To disable automatic + collection, call `.setAutoCollectRequests(false)` before calling `start()`. + + ```javascript + appInsights.defaultClient.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true}); + ``` + Alternatively you can track requests using ```trackNodeHttpRequest``` method: + + ```javascript + var server = http.createServer((req, res) => { + if ( req.method === "GET" ) { + appInsights.defaultClient.trackNodeHttpRequest({request:req, response:res}); + } + // other work here.... + res.end(); + }); + ``` + +* Track server startup time + + ```javascript + let start = Date.now(); + server.on("listening", () => { + let duration = Date.now() - start; + appInsights.defaultClient.trackMetric({name: "server startup time", value: duration}); + }); + ``` + +## Self-diagnostics + +"Self-diagnostics" refers to internal logging from Application Insights Node.js SDK. + +This functionality can be helpful for spotting and diagnosing issues with Application Insights itself. + +By default, Application Insights Node.js SDK logs at warning level to console, following code demonstrate how to enable debug logging as well and generate telemetry for internal logs: + +```javascript +let appInsights = require("applicationinsights"); +appInsights.setup("") + .setInternalLogging(true, true) // Enable both debug and warning logging + .setAutoCollectConsole(true, true) // Generate Trace telemetry for winston/bunyan and console logs + .start(); +``` + +Logs could be put into local file using `APPLICATIONINSIGHTS_LOG_DESTINATION` environment variable, supported values are `file` and `file+console`, a file named `applicationinsights.log` will be generated on tmp folder by default, including all logs, `/tmp` for *nix and `USERDIR/AppData/Local/Temp` for Windows. Log directory could be configured using `APPLICATIONINSIGHTS_LOGDIR` environment variable. + +```javascript +process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file"; +process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs" + +// Application Insights SDK setup.... +``` + +## Branches + +- Ongoing development takes place on the [develop][] branch. **Please submit + pull requests to this branch.** +- Releases are merged to the [master][] branch and published to [npm][]. + +[master]: https://github.com/microsoft/ApplicationInsights-node.js/tree/master +[develop]: https://github.com/microsoft/ApplicationInsights-node.js/tree/develop +[npm]: https://www.npmjs.com/package/applicationinsights + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to +agree to a Contributor License Agreement (CLA) declaring that you have the right to, +and actually do, grant us the rights to use your contribution. For details, visit +https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need +to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the +instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Data Collection + +As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement. + +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +## Trademarks + +This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft’s Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies. + +## License + +[MIT](LICENSE) \ No newline at end of file diff --git a/node_modules/applicationinsights/SECURITY.md b/node_modules/applicationinsights/SECURITY.md new file mode 100644 index 0000000..12fbd83 --- /dev/null +++ b/node_modules/applicationinsights/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). + + \ No newline at end of file diff --git a/node_modules/applicationinsights/SUPPORT.md b/node_modules/applicationinsights/SUPPORT.md new file mode 100644 index 0000000..9cf22a3 --- /dev/null +++ b/node_modules/applicationinsights/SUPPORT.md @@ -0,0 +1,14 @@ +# Support + +## How to file issues and get help + +This project uses GitHub Issues to track bugs and feature requests. Please search the existing +issues before filing new issues to avoid duplicates. For new issues, file your bug or +feature request as a new Issue. + +For help and questions about using this project, please create a Support request issue on +https://github.com/microsoft/ApplicationInsights-node.js/issues. + +## Microsoft Support Policy + +Support for this **PROJECT or PRODUCT** is limited to the resources listed above. \ No newline at end of file diff --git a/node_modules/applicationinsights/applicationinsights.json b/node_modules/applicationinsights/applicationinsights.json new file mode 100644 index 0000000..bcdb126 --- /dev/null +++ b/node_modules/applicationinsights/applicationinsights.json @@ -0,0 +1,4 @@ +{ + +} + \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.d.ts b/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.d.ts new file mode 100644 index 0000000..0133c45 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.d.ts @@ -0,0 +1,11 @@ +import { Span } from "@opentelemetry/sdk-trace-base"; +export declare class OpenTelemetryScopeManagerWrapper { + private _activeSymbol; + active(): any; + with(span: Span, fn: () => any): any; + bind(target: T): T; + enable(): this; + disable(): this; + private static _spanToContext; +} +export declare const AsyncScopeManager: OpenTelemetryScopeManagerWrapper; diff --git a/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.js b/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.js new file mode 100644 index 0000000..5dbd537 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/AsyncHooksScopeManager.js @@ -0,0 +1,77 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsyncScopeManager = exports.OpenTelemetryScopeManagerWrapper = void 0; +var CorrelationContextManager_1 = require("./CorrelationContextManager"); +var events_1 = require("events"); +var OpenTelemetryScopeManagerWrapper = /** @class */ (function () { + function OpenTelemetryScopeManagerWrapper() { + } + OpenTelemetryScopeManagerWrapper.prototype.active = function () { + var _this = this; + var context = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + return __assign(__assign({}, context), { getValue: function (key) { + // todo: lazy import activeSymbol from opentelemetry/api + if (!_this._activeSymbol) { + _this._activeSymbol = key; + return context; + } + if (key === _this._activeSymbol) { + return context; + } + return false; + }, setValue: function () { } }); + }; + OpenTelemetryScopeManagerWrapper.prototype.with = function (span, fn) { + var parentSpanId = span.parentSpanId; + var name = span.name; + var correlationContext = OpenTelemetryScopeManagerWrapper._spanToContext(span, parentSpanId, name); + return CorrelationContextManager_1.CorrelationContextManager.runWithContext(correlationContext, fn)(); + }; + OpenTelemetryScopeManagerWrapper.prototype.bind = function (target) { + if (typeof target === "function") { + return CorrelationContextManager_1.CorrelationContextManager.wrapCallback(target); + } + else if (target instanceof events_1.EventEmitter) { + CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(target); + } + return target; + }; + OpenTelemetryScopeManagerWrapper.prototype.enable = function () { + CorrelationContextManager_1.CorrelationContextManager.enable(); + return this; + }; + OpenTelemetryScopeManagerWrapper.prototype.disable = function () { + CorrelationContextManager_1.CorrelationContextManager.disable(); + return this; + }; + OpenTelemetryScopeManagerWrapper._spanToContext = function (span, parentSpanId, name) { + var spanContext = span.spanContext ? span.spanContext() : span.context(); // context is available in OT API {\r\n // todo: lazy import activeSymbol from opentelemetry/api\r\n if (!this._activeSymbol) {\r\n this._activeSymbol = key;\r\n return context;\r\n }\r\n\r\n if (key === this._activeSymbol) {\r\n return context;\r\n }\r\n return false;\r\n },\r\n setValue: () => { }\r\n };\r\n }\r\n\r\n public with(span: Span, fn: () => any) {\r\n const parentSpanId = span.parentSpanId;\r\n const name = span.name;\r\n const correlationContext = OpenTelemetryScopeManagerWrapper._spanToContext(span, parentSpanId, name);\r\n return CorrelationContextManager.runWithContext(correlationContext, fn)();\r\n }\r\n\r\n public bind(target: T): T {\r\n if (typeof target === \"function\") {\r\n return CorrelationContextManager.wrapCallback(target);\r\n } else if (target instanceof EventEmitter) {\r\n CorrelationContextManager.wrapEmitter(target);\r\n }\r\n return target;\r\n }\r\n\r\n public enable(): this {\r\n CorrelationContextManager.enable();\r\n return this;\r\n }\r\n\r\n public disable(): this {\r\n CorrelationContextManager.disable();\r\n return this;\r\n }\r\n\r\n private static _spanToContext(span: Span, parentSpanId?: string, name?: string): CorrelationContext {\r\n const spanContext = span.spanContext ? span.spanContext() : (span).context(); // context is available in OT API 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 }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AzureFunctionsHook = void 0; +var Logging = require("../Library/Logging"); +var CorrelationContextManager_1 = require("./CorrelationContextManager"); +/** Node.js Azure Functions handle incoming HTTP requests before Application Insights SDK is available, + * this code generate incoming request telemetry and generate correlation context to be used + * by outgoing requests and other telemetry, we rely on hooks provided by Azure Functions +*/ +var AzureFunctionsHook = /** @class */ (function () { + function AzureFunctionsHook(client) { + this._client = client; + this._autoGenerateIncomingRequests = false; + try { + this._functionsCoreModule = require("@azure/functions-core"); + // Only v3 of Azure Functions library is supported right now. See matrix of versions here: + // https://github.com/Azure/azure-functions-nodejs-library + var funcProgModel = this._functionsCoreModule.getProgrammingModel(); + if (funcProgModel.name === "@azure/functions" && funcProgModel.version.startsWith("3.")) { + this._addPreInvocationHook(); + this._addPostInvocationHook(); + } + else { + Logging.warn("AzureFunctionsHook does not support model \"" + funcProgModel.name + "\" version \"" + funcProgModel.version + "\""); + } + } + catch (error) { + Logging.info("AzureFunctionsHook failed to load, not running in Azure Functions"); + } + } + AzureFunctionsHook.prototype.enable = function (isEnabled) { + this._autoGenerateIncomingRequests = isEnabled; + }; + AzureFunctionsHook.prototype.dispose = function () { + this.enable(false); + this._removeInvocationHooks(); + this._functionsCoreModule = undefined; + }; + AzureFunctionsHook.prototype._addPreInvocationHook = function () { + var _this = this; + if (!this._preInvocationHook) { + this._preInvocationHook = this._functionsCoreModule.registerHook("preInvocation", function (preInvocationContext) { return __awaiter(_this, void 0, void 0, function () { + var ctx, extractedContext; + return __generator(this, function (_a) { + ctx = preInvocationContext.invocationContext; + try { + extractedContext = CorrelationContextManager_1.CorrelationContextManager.startOperation(ctx); + extractedContext.customProperties.setProperty("InvocationId", ctx.invocationId); + if (ctx.traceContext.attributes) { + extractedContext.customProperties.setProperty("ProcessId", ctx.traceContext.attributes["ProcessId"]); + extractedContext.customProperties.setProperty("LogLevel", ctx.traceContext.attributes["LogLevel"]); + extractedContext.customProperties.setProperty("Category", ctx.traceContext.attributes["Category"]); + extractedContext.customProperties.setProperty("HostInstanceId", ctx.traceContext.attributes["HostInstanceId"]); + extractedContext.customProperties.setProperty("AzFuncLiveLogsSessionId", ctx.traceContext.attributes["#AzFuncLiveLogsSessionId"]); + } + preInvocationContext.functionCallback = CorrelationContextManager_1.CorrelationContextManager.wrapCallback(preInvocationContext.functionCallback, extractedContext); + if (this._isHttpTrigger(ctx) && this._autoGenerateIncomingRequests) { + preInvocationContext.hookData.appInsightsExtractedContext = extractedContext; + preInvocationContext.hookData.appInsightsStartTime = Date.now(); // Start trackRequest timer + } + } + catch (err) { + Logging.warn("Failed to propagate context in Azure Functions", err); + return [2 /*return*/]; + } + return [2 /*return*/]; + }); + }); }); + } + }; + AzureFunctionsHook.prototype._addPostInvocationHook = function () { + var _this = this; + if (!this._postInvocationHook) { + this._postInvocationHook = this._functionsCoreModule.registerHook("postInvocation", function (postInvocationContext) { return __awaiter(_this, void 0, void 0, function () { + var ctx, request_1, startTime_1, response_1, extractedContext_1; + var _this = this; + return __generator(this, function (_a) { + try { + if (this._autoGenerateIncomingRequests) { + ctx = postInvocationContext.invocationContext; + if (this._isHttpTrigger(ctx)) { + request_1 = postInvocationContext.inputs[0]; + if (request_1) { + startTime_1 = postInvocationContext.hookData.appInsightsStartTime || Date.now(); + response_1 = this._getAzureFunctionResponse(postInvocationContext, ctx); + extractedContext_1 = postInvocationContext.hookData.appInsightsExtractedContext; + if (!extractedContext_1) { + this._createIncomingRequestTelemetry(request_1, response_1, startTime_1, null); + } + else { + CorrelationContextManager_1.CorrelationContextManager.runWithContext(extractedContext_1, function () { + _this._createIncomingRequestTelemetry(request_1, response_1, startTime_1, extractedContext_1.operation.parentId); + }); + } + } + } + } + } + catch (err) { + Logging.warn("Error creating automatic incoming request in Azure Functions", err); + } + return [2 /*return*/]; + }); + }); }); + } + }; + AzureFunctionsHook.prototype._createIncomingRequestTelemetry = function (request, response, startTime, parentId) { + var statusCode = 200; //Default + for (var _i = 0, _a = [response.statusCode, response.status]; _i < _a.length; _i++) { + var value = _a[_i]; + if (typeof value === "number" && Number.isInteger(value)) { + statusCode = value; + break; + } + else if (typeof value === "string") { + var parsedVal = parseInt(value); + if (!isNaN(parsedVal)) { + statusCode = parsedVal; + break; + } + } + } + this._client.trackRequest({ + name: request.method + " " + request.url, + resultCode: statusCode, + success: (0 < statusCode) && (statusCode < 400), + url: request.url, + time: new Date(startTime), + duration: Date.now() - startTime, + id: parentId + }); + this._client.flush(); + }; + AzureFunctionsHook.prototype._getAzureFunctionResponse = function (postInvocationContext, ctx) { + var httpOutputBinding = ctx.bindingDefinitions.find(function (b) { return b.direction === "out" && b.type.toLowerCase() === "http"; }); + if ((httpOutputBinding === null || httpOutputBinding === void 0 ? void 0 : httpOutputBinding.name) === "$return") { + return postInvocationContext.result; + } + else if (httpOutputBinding && ctx.bindings && ctx.bindings[httpOutputBinding.name] !== undefined) { + return ctx.bindings[httpOutputBinding.name]; + } + else { + return ctx.res; + } + }; + AzureFunctionsHook.prototype._isHttpTrigger = function (ctx) { + return ctx.bindingDefinitions.find(function (b) { var _a; return ((_a = b.type) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === "httptrigger"; }); + }; + AzureFunctionsHook.prototype._removeInvocationHooks = function () { + if (this._preInvocationHook) { + this._preInvocationHook.dispose(); + this._preInvocationHook = undefined; + } + if (this._postInvocationHook) { + this._postInvocationHook.dispose(); + this._postInvocationHook = undefined; + } + }; + return AzureFunctionsHook; +}()); +exports.AzureFunctionsHook = AzureFunctionsHook; +//# sourceMappingURL=AzureFunctionsHook.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.js.map b/node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.js.map new file mode 100644 index 0000000..d1a9c9a --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/AzureFunctionsHook.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AzureFunctionsHook.js","sourceRoot":"","sources":["../../AutoCollection/AzureFunctionsHook.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,4CAA+C;AAE/C,yEAA4F;AAE5F;;;EAGE;AACF;IAOI,4BAAY,MAAuB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,6BAA6B,GAAG,KAAK,CAAC;QAC3C,IAAI;YACA,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,uBAAuB,CAAC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C,MAAM,CAAC;SACvC;aAAM,IAAI,iBAAiB,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE;YAChG,OAAO,GAAG,CAAC,QAAQ,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;SAC/C;aAAM;YACH,OAAO,GAAG,CAAC,GAAG,CAAC;SAClB;IACL,CAAC;IAEO,2CAAc,GAAtB,UAAuB,GAAY;QAC/B,OAAO,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,UAAA,CAAC,YAAI,OAAA,OAAA,CAAC,CAAC,IAAI,0CAAE,WAAW,QAAO,aAAa,CAAA,EAAA,CAAC,CAAC;IACrF,CAAC;IAEO,mDAAsB,GAA9B;QACI,IAAI,IAAI,CAAC,kBAAkB,EAAE;YACzB,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,CAAC;YAClC,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAC;SACvC;QACD,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC1B,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,CAAC;YACnC,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;SACxC;IACL,CAAC;IACL,yBAAC;AAAD,CAAC,AApJD,IAoJC;AApJY,gDAAkB","sourcesContent":["import { Disposable, PostInvocationContext, PreInvocationContext } from \"@azure/functions-core\";\r\nimport { Context, HttpRequest, HttpResponse } from \"@azure/functions\";\r\nimport Logging = require(\"../Library/Logging\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport { CorrelationContext, CorrelationContextManager } from \"./CorrelationContextManager\";\r\n\r\n/** Node.js Azure Functions handle incoming HTTP requests before Application Insights SDK is available,\r\n * this code generate incoming request telemetry and generate correlation context to be used\r\n * by outgoing requests and other telemetry, we rely on hooks provided by Azure Functions\r\n*/\r\nexport class AzureFunctionsHook {\r\n private _client: TelemetryClient;\r\n private _functionsCoreModule: typeof import(\"@azure/functions-core\");\r\n private _autoGenerateIncomingRequests: boolean;\r\n private _preInvocationHook: Disposable;\r\n private _postInvocationHook: Disposable;\r\n\r\n constructor(client: TelemetryClient) {\r\n this._client = client;\r\n this._autoGenerateIncomingRequests = false;\r\n try {\r\n this._functionsCoreModule = require(\"@azure/functions-core\");\r\n // Only v3 of Azure Functions library is supported right now. See matrix of versions here:\r\n // https://github.com/Azure/azure-functions-nodejs-library\r\n const funcProgModel = this._functionsCoreModule.getProgrammingModel();\r\n if (funcProgModel.name === \"@azure/functions\" && funcProgModel.version.startsWith(\"3.\")) {\r\n this._addPreInvocationHook();\r\n this._addPostInvocationHook();\r\n } else {\r\n Logging.warn(`AzureFunctionsHook does not support model \"${funcProgModel.name}\" version \"${funcProgModel.version}\"`);\r\n }\r\n }\r\n catch (error) {\r\n Logging.info(\"AzureFunctionsHook failed to load, not running in Azure Functions\");\r\n }\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n this._autoGenerateIncomingRequests = isEnabled;\r\n }\r\n\r\n public dispose() {\r\n this.enable(false);\r\n this._removeInvocationHooks();\r\n this._functionsCoreModule = undefined;\r\n }\r\n\r\n private _addPreInvocationHook() {\r\n if (!this._preInvocationHook) {\r\n this._preInvocationHook = this._functionsCoreModule.registerHook(\"preInvocation\", async (preInvocationContext: PreInvocationContext) => {\r\n const ctx: Context = preInvocationContext.invocationContext;\r\n try {\r\n // Start an AI Correlation Context using the provided Function context\r\n let extractedContext = CorrelationContextManager.startOperation(ctx);\r\n extractedContext.customProperties.setProperty(\"InvocationId\", ctx.invocationId);\r\n if (ctx.traceContext.attributes) {\r\n extractedContext.customProperties.setProperty(\"ProcessId\", ctx.traceContext.attributes[\"ProcessId\"]);\r\n extractedContext.customProperties.setProperty(\"LogLevel\", ctx.traceContext.attributes[\"LogLevel\"]);\r\n extractedContext.customProperties.setProperty(\"Category\", ctx.traceContext.attributes[\"Category\"]);\r\n extractedContext.customProperties.setProperty(\"HostInstanceId\", ctx.traceContext.attributes[\"HostInstanceId\"]);\r\n extractedContext.customProperties.setProperty(\"AzFuncLiveLogsSessionId\", ctx.traceContext.attributes[\"#AzFuncLiveLogsSessionId\"]);\r\n }\r\n preInvocationContext.functionCallback = CorrelationContextManager.wrapCallback(preInvocationContext.functionCallback, extractedContext);\r\n if (this._isHttpTrigger(ctx) && this._autoGenerateIncomingRequests) {\r\n preInvocationContext.hookData.appInsightsExtractedContext = extractedContext;\r\n preInvocationContext.hookData.appInsightsStartTime = Date.now(); // Start trackRequest timer\r\n }\r\n }\r\n catch (err) {\r\n Logging.warn(\"Failed to propagate context in Azure Functions\", err);\r\n return;\r\n }\r\n });\r\n }\r\n }\r\n\r\n private _addPostInvocationHook() {\r\n if (!this._postInvocationHook) {\r\n this._postInvocationHook = this._functionsCoreModule.registerHook(\"postInvocation\", async (postInvocationContext: PostInvocationContext) => {\r\n try {\r\n if (this._autoGenerateIncomingRequests) {\r\n const ctx: Context = postInvocationContext.invocationContext;\r\n if (this._isHttpTrigger(ctx)) {\r\n const request: HttpRequest = postInvocationContext.inputs[0];\r\n if (request) {\r\n const startTime: number = postInvocationContext.hookData.appInsightsStartTime || Date.now();\r\n const response = this._getAzureFunctionResponse(postInvocationContext, ctx);\r\n const extractedContext: CorrelationContext | undefined = postInvocationContext.hookData.appInsightsExtractedContext;\r\n if (!extractedContext) {\r\n this._createIncomingRequestTelemetry(request, response, startTime, null);\r\n }\r\n else {\r\n CorrelationContextManager.runWithContext(extractedContext, () => {\r\n this._createIncomingRequestTelemetry(request, response, startTime, extractedContext.operation.parentId);\r\n });\r\n }\r\n }\r\n }\r\n }\r\n }\r\n catch (err) {\r\n Logging.warn(\"Error creating automatic incoming request in Azure Functions\", err);\r\n }\r\n });\r\n }\r\n }\r\n\r\n private _createIncomingRequestTelemetry(request: HttpRequest, response: HttpResponse, startTime: number, parentId: string) {\r\n let statusCode: string | number = 200; //Default\r\n for (const value of [response.statusCode, response.status]) {\r\n if (typeof value === \"number\" && Number.isInteger(value)) {\r\n statusCode = value;\r\n break;\r\n } else if (typeof value === \"string\") {\r\n const parsedVal = parseInt(value);\r\n if (!isNaN(parsedVal)) {\r\n statusCode = parsedVal;\r\n break;\r\n }\r\n }\r\n }\r\n this._client.trackRequest({\r\n name: request.method + \" \" + request.url,\r\n resultCode: statusCode,\r\n success: (0 < statusCode) && (statusCode < 400),\r\n url: request.url,\r\n time: new Date(startTime),\r\n duration: Date.now() - startTime,\r\n id: parentId\r\n });\r\n this._client.flush();\r\n }\r\n\r\n private _getAzureFunctionResponse(postInvocationContext: PostInvocationContext, ctx: Context): HttpResponse {\r\n const httpOutputBinding = ctx.bindingDefinitions.find(b => b.direction === \"out\" && b.type.toLowerCase() === \"http\");\r\n if (httpOutputBinding?.name === \"$return\") {\r\n return postInvocationContext.result;\r\n } else if (httpOutputBinding && ctx.bindings && ctx.bindings[httpOutputBinding.name] !== undefined) {\r\n return ctx.bindings[httpOutputBinding.name];\r\n } else {\r\n return ctx.res;\r\n }\r\n }\r\n\r\n private _isHttpTrigger(ctx: Context) {\r\n return ctx.bindingDefinitions.find(b => b.type?.toLowerCase() === \"httptrigger\");\r\n }\r\n\r\n private _removeInvocationHooks() {\r\n if (this._preInvocationHook) {\r\n this._preInvocationHook.dispose();\r\n this._preInvocationHook = undefined;\r\n }\r\n if (this._postInvocationHook) {\r\n this._postInvocationHook.dispose();\r\n this._postInvocationHook = undefined;\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Console.d.ts b/node_modules/applicationinsights/out/AutoCollection/Console.d.ts new file mode 100644 index 0000000..f4143c3 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Console.d.ts @@ -0,0 +1,15 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +declare class AutoCollectConsole { + static originalMethods: { + [name: string]: (message?: any, ...optionalParams: any[]) => void; + }; + static INSTANCE: AutoCollectConsole; + private static _methodNames; + private _client; + private _isInitialized; + constructor(client: TelemetryClient); + enable(isEnabled: boolean, collectConsoleLog: boolean): void; + isInitialized(): boolean; + dispose(): void; +} +export = AutoCollectConsole; diff --git a/node_modules/applicationinsights/out/AutoCollection/Console.js b/node_modules/applicationinsights/out/AutoCollection/Console.js new file mode 100644 index 0000000..482f780 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Console.js @@ -0,0 +1,29 @@ +"use strict"; +var DiagChannel = require("./diagnostic-channel/initialization"); +var AutoCollectConsole = /** @class */ (function () { + function AutoCollectConsole(client) { + if (!!AutoCollectConsole.INSTANCE) { + throw new Error("Console logging adapter tracking should be configured from the applicationInsights object"); + } + this._client = client; + AutoCollectConsole.INSTANCE = this; + } + AutoCollectConsole.prototype.enable = function (isEnabled, collectConsoleLog) { + if (DiagChannel.IsInitialized) { + require("./diagnostic-channel/console.sub").enable(isEnabled && collectConsoleLog, this._client); + require("./diagnostic-channel/bunyan.sub").enable(isEnabled, this._client); + require("./diagnostic-channel/winston.sub").enable(isEnabled, this._client); + } + }; + AutoCollectConsole.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectConsole.prototype.dispose = function () { + AutoCollectConsole.INSTANCE = null; + this.enable(false, false); + }; + AutoCollectConsole._methodNames = ["debug", "info", "log", "warn", "error"]; + return AutoCollectConsole; +}()); +module.exports = AutoCollectConsole; +//# sourceMappingURL=Console.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Console.js.map b/node_modules/applicationinsights/out/AutoCollection/Console.js.map new file mode 100644 index 0000000..d0f3d88 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Console.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Console.js","sourceRoot":"","sources":["../../AutoCollection/Console.ts"],"names":[],"mappings":";AAEA,iEAAmE;AAEnE;IASI,4BAAY,MAAuB;QAC/B,IAAG,CAAC,CAAC,kBAAkB,CAAC,QAAQ,EAAE;YAC9B,MAAM,IAAI,KAAK,CAAC,2FAA2F,CAAC,CAAC;SAChH;QAED,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,kBAAkB,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvC,CAAC;IAEM,mCAAM,GAAb,UAAc,SAAkB,EAAE,iBAA0B;QACxD,IAAI,WAAW,CAAC,aAAa,EAAE;YAC3B,OAAO,CAAC,kCAAkC,CAAC,CAAC,MAAM,CAAC,SAAS,IAAI,iBAAiB,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACjG,OAAO,CAAC,iCAAiC,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YAC3E,OAAO,CAAC,kCAAkC,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;SAC/E;IACL,CAAC;IAEM,0CAAa,GAApB;QACI,OAAO,IAAI,CAAC,cAAc,CAAC;IAC/B,CAAC;IAEM,oCAAO,GAAd;QACI,kBAAkB,CAAC,QAAQ,GAAG,IAAI,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC9B,CAAC;IA7Bc,+BAAY,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IA8B5E,yBAAC;CAAA,AAlCD,IAkCC;AAED,iBAAS,kBAAkB,CAAC","sourcesContent":["import TelemetryClient = require(\"../Library/TelemetryClient\");\r\n\r\nimport * as DiagChannel from \"./diagnostic-channel/initialization\";\r\n\r\nclass AutoCollectConsole {\r\n public static originalMethods: {[name: string]: (message?: any, ...optionalParams: any[]) => void};\r\n\r\n public static INSTANCE: AutoCollectConsole;\r\n private static _methodNames = [\"debug\", \"info\", \"log\", \"warn\", \"error\"];\r\n\r\n private _client: TelemetryClient;\r\n private _isInitialized: boolean;\r\n\r\n constructor(client: TelemetryClient) {\r\n if(!!AutoCollectConsole.INSTANCE) {\r\n throw new Error(\"Console logging adapter tracking should be configured from the applicationInsights object\");\r\n }\r\n\r\n this._client = client;\r\n AutoCollectConsole.INSTANCE = this;\r\n }\r\n\r\n public enable(isEnabled: boolean, collectConsoleLog: boolean) {\r\n if (DiagChannel.IsInitialized) {\r\n require(\"./diagnostic-channel/console.sub\").enable(isEnabled && collectConsoleLog, this._client);\r\n require(\"./diagnostic-channel/bunyan.sub\").enable(isEnabled, this._client);\r\n require(\"./diagnostic-channel/winston.sub\").enable(isEnabled, this._client);\r\n }\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public dispose() {\r\n AutoCollectConsole.INSTANCE = null;\r\n this.enable(false, false);\r\n }\r\n}\r\n\r\nexport = AutoCollectConsole;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.d.ts b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.d.ts new file mode 100644 index 0000000..78af532 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.d.ts @@ -0,0 +1,105 @@ +/// +import events = require("events"); +import * as azureFunctionsTypes from "../Library/Functions"; +import * as http from "http"; +import Traceparent = require("../Library/Traceparent"); +import Tracestate = require("../Library/Tracestate"); +import { SpanContext } from "@opentelemetry/api"; +import { Span } from "@opentelemetry/sdk-trace-base"; +export interface CustomProperties { + /** + * Get a custom property from the correlation context + */ + getProperty(key: string): string; + /** + * Store a custom property in the correlation context. + * Do not store sensitive information here. + * Properties stored here are exposed via outgoing HTTP headers for correlating data cross-component. + * The characters ',' and '=' are disallowed within keys or values. + */ + setProperty(key: string, value: string): void; +} +export interface PrivateCustomProperties extends CustomProperties { + addHeaderData(header: string): void; + serializeToHeader(): string; +} +export interface CorrelationContext { + operation: { + name: string; + id: string; + parentId: string; + traceparent?: Traceparent; + tracestate?: Tracestate; + }; + /** Do not store sensitive information here. + * Properties here are exposed via outgoing HTTP headers for correlating data cross-component. + */ + customProperties: CustomProperties; +} +export declare class CorrelationContextManager { + private static enabled; + private static hasEverEnabled; + private static forceClsHooked; + private static session; + private static cls; + private static CONTEXT_NAME; + /** + * Provides the current Context. + * The context is the most recent one entered into for the current + * logical chain of execution, including across asynchronous calls. + */ + static getCurrentContext(): CorrelationContext | null; + /** + * A helper to generate objects conforming to the CorrelationContext interface + */ + static generateContextObject(operationId: string, parentId?: string, operationName?: string, correlationContextHeader?: string, traceparent?: Traceparent, tracestate?: Tracestate): CorrelationContext; + static spanToContextObject(spanContext: SpanContext, parentId?: string, name?: string): CorrelationContext; + /** + * Runs a function inside a given Context. + * All logical children of the execution path that entered this Context + * will receive this Context object on calls to GetCurrentContext. + */ + static runWithContext(context: CorrelationContext, fn: () => any): any; + /** + * Wrapper for cls-hooked bindEmitter method + */ + static wrapEmitter(emitter: events.EventEmitter): void; + /** + * Patches a callback to restore the correct Context when getCurrentContext + * is run within it. This is necessary if automatic correlation fails to work + * with user-included libraries. + * + * The supplied callback will be given the same context that was present for + * the call to wrapCallback. */ + static wrapCallback(fn: T, context?: CorrelationContext): T; + /** + * Enables the CorrelationContextManager. + */ + static enable(forceClsHooked?: boolean): void; + /** + * Create new correlation context. + */ + static startOperation(input: azureFunctionsTypes.Context | (http.IncomingMessage | azureFunctionsTypes.HttpRequest) | SpanContext | Span, request?: azureFunctionsTypes.HttpRequest | string): CorrelationContext | null; + /** + * Disables the CorrelationContextManager. + */ + static disable(): void; + /** + * Reset the namespace + */ + static reset(): void; + /** + * Reports if CorrelationContextManager is able to run in this environment + */ + static isNodeVersionCompatible(): boolean; + /** + * We only want to use cls-hooked when it uses async_hooks api (8.2+), else + * use async-listener (plain -cls) + */ + static shouldUseClsHooked(): boolean; + /** + * A TypeError is triggered by cls-hooked for node [8.0, 8.2) + * @internal Used in tests only + */ + static canUseClsHooked(): boolean; +} diff --git a/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js new file mode 100644 index 0000000..4e3bc0c --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js @@ -0,0 +1,296 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CorrelationContextManager = void 0; +var Logging = require("../Library/Logging"); +var DiagChannel = require("./diagnostic-channel/initialization"); +var Traceparent = require("../Library/Traceparent"); +var Tracestate = require("../Library/Tracestate"); +var HttpRequestParser = require("./HttpRequestParser"); +var Util = require("../Library/Util"); +var CorrelationContextManager = /** @class */ (function () { + function CorrelationContextManager() { + } + /** + * Provides the current Context. + * The context is the most recent one entered into for the current + * logical chain of execution, including across asynchronous calls. + */ + CorrelationContextManager.getCurrentContext = function () { + if (!CorrelationContextManager.enabled) { + return null; + } + var context = CorrelationContextManager.session.get(CorrelationContextManager.CONTEXT_NAME); + if (context === undefined) { // cast undefined to null + return null; + } + return context; + }; + /** + * A helper to generate objects conforming to the CorrelationContext interface + */ + CorrelationContextManager.generateContextObject = function (operationId, parentId, operationName, correlationContextHeader, traceparent, tracestate) { + parentId = parentId || operationId; + if (this.enabled) { + return { + operation: { + name: operationName, + id: operationId, + parentId: parentId, + traceparent: traceparent, + tracestate: tracestate + }, + customProperties: new CustomPropertiesImpl(correlationContextHeader) + }; + } + return null; + }; + CorrelationContextManager.spanToContextObject = function (spanContext, parentId, name) { + var traceContext = new Traceparent(); + traceContext.traceId = spanContext.traceId; + traceContext.spanId = spanContext.spanId; + traceContext.traceFlag = Traceparent.formatOpenTelemetryTraceFlags(spanContext.traceFlags) || Traceparent.DEFAULT_TRACE_FLAG; + traceContext.parentId = parentId; + return CorrelationContextManager.generateContextObject(traceContext.traceId, traceContext.parentId, name, null, traceContext); + }; + /** + * Runs a function inside a given Context. + * All logical children of the execution path that entered this Context + * will receive this Context object on calls to GetCurrentContext. + */ + CorrelationContextManager.runWithContext = function (context, fn) { + var _a; + if (CorrelationContextManager.enabled) { + try { + return CorrelationContextManager.session.bind(fn, (_a = {}, _a[CorrelationContextManager.CONTEXT_NAME] = context, _a))(); + } + catch (error) { + Logging.warn("Error binding to session context", Util.dumpObj(error)); + } + } + return fn(); + }; + /** + * Wrapper for cls-hooked bindEmitter method + */ + CorrelationContextManager.wrapEmitter = function (emitter) { + if (CorrelationContextManager.enabled) { + try { + CorrelationContextManager.session.bindEmitter(emitter); + } + catch (error) { + Logging.warn("Error binding to session context", Util.dumpObj(error)); + } + } + }; + /** + * Patches a callback to restore the correct Context when getCurrentContext + * is run within it. This is necessary if automatic correlation fails to work + * with user-included libraries. + * + * The supplied callback will be given the same context that was present for + * the call to wrapCallback. */ + CorrelationContextManager.wrapCallback = function (fn, context) { + var _a; + if (CorrelationContextManager.enabled) { + try { + return CorrelationContextManager.session.bind(fn, context ? (_a = {}, + _a[CorrelationContextManager.CONTEXT_NAME] = context, + _a) : undefined); + } + catch (error) { + Logging.warn("Error binding to session context", Util.dumpObj(error)); + } + } + return fn; + }; + /** + * Enables the CorrelationContextManager. + */ + CorrelationContextManager.enable = function (forceClsHooked) { + if (this.enabled) { + return; + } + if (!this.isNodeVersionCompatible()) { + this.enabled = false; + return; + } + if (!CorrelationContextManager.hasEverEnabled) { + this.forceClsHooked = forceClsHooked; + this.hasEverEnabled = true; + if (typeof this.cls === "undefined") { + if ((CorrelationContextManager.forceClsHooked === true) || (CorrelationContextManager.forceClsHooked === undefined && CorrelationContextManager.shouldUseClsHooked())) { + this.cls = require("cls-hooked"); + } + else { + this.cls = require("continuation-local-storage"); + } + } + CorrelationContextManager.session = this.cls.createNamespace("AI-CLS-Session"); + DiagChannel.registerContextPreservation(function (cb) { + try { + return CorrelationContextManager.session.bind(cb); + } + catch (error) { + Logging.warn("Error binding to session context", Util.dumpObj(error)); + } + }); + } + this.enabled = true; + }; + /** + * Create new correlation context. + */ + CorrelationContextManager.startOperation = function (input, request) { + var traceContext = input && input.traceContext || null; + var span = input && input.spanContext ? input : null; + var spanContext = input && input.traceId ? input : null; + var headers = input && input.headers; + // OpenTelemetry Span + if (span) { + return this.spanToContextObject(span.spanContext(), span.parentSpanId, span.name); + } + // OpenTelemetry SpanContext + if (spanContext) { + return this.spanToContextObject(spanContext, "|" + spanContext.traceId + "." + spanContext.spanId + ".", typeof request === "string" ? request : ""); + } + var operationName = typeof request === "string" ? request : ""; + // AzFunction TraceContext + if (traceContext) { + var traceparent = null; + var tracestate = null; + operationName = traceContext.attributes["OperationName"] || operationName; + if (request) { + var azureFnRequest = request; + if (azureFnRequest.headers) { + if (azureFnRequest.headers.traceparent) { + traceparent = new Traceparent(azureFnRequest.headers.traceparent); + } + else if (azureFnRequest.headers["request-id"]) { + traceparent = new Traceparent(null, azureFnRequest.headers["request-id"]); + } + if (azureFnRequest.headers.tracestate) { + tracestate = new Tracestate(azureFnRequest.headers.tracestate); + } + } + } + if (!traceparent) { + traceparent = new Traceparent(traceContext.traceparent); + } + if (!tracestate) { + tracestate = new Tracestate(traceContext.tracestate); + } + var correlationContextHeader = undefined; + if (typeof request === "object") { + var parser = new HttpRequestParser(request); + correlationContextHeader = parser.getCorrelationContextHeader(); + operationName = parser.getOperationName({}); + } + var correlationContext = CorrelationContextManager.generateContextObject(traceparent.traceId, traceparent.parentId, operationName, correlationContextHeader, traceparent, tracestate); + return correlationContext; + } + // No TraceContext available, parse as http.IncomingMessage + if (headers) { + var traceparent = new Traceparent(headers.traceparent ? headers.traceparent.toString() : null); + var tracestate = new Tracestate(headers.tracestate ? headers.tracestate.toString() : null); + var parser = new HttpRequestParser(input); + var correlationContext = CorrelationContextManager.generateContextObject(traceparent.traceId, traceparent.parentId, parser.getOperationName({}), parser.getCorrelationContextHeader(), traceparent, tracestate); + return correlationContext; + } + Logging.warn("startOperation was called with invalid arguments", arguments); + return null; + }; + /** + * Disables the CorrelationContextManager. + */ + CorrelationContextManager.disable = function () { + this.enabled = false; + }; + /** + * Reset the namespace + */ + CorrelationContextManager.reset = function () { + if (CorrelationContextManager.hasEverEnabled) { + CorrelationContextManager.session = null; + CorrelationContextManager.session = this.cls.createNamespace("AI-CLS-Session"); + } + }; + /** + * Reports if CorrelationContextManager is able to run in this environment + */ + CorrelationContextManager.isNodeVersionCompatible = function () { + var nodeVer = process.versions.node.split("."); + return parseInt(nodeVer[0]) > 3 || (parseInt(nodeVer[0]) > 2 && parseInt(nodeVer[1]) > 2); + }; + /** + * We only want to use cls-hooked when it uses async_hooks api (8.2+), else + * use async-listener (plain -cls) + */ + CorrelationContextManager.shouldUseClsHooked = function () { + var nodeVer = process.versions.node.split("."); + return (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 2); + }; + /** + * A TypeError is triggered by cls-hooked for node [8.0, 8.2) + * @internal Used in tests only + */ + CorrelationContextManager.canUseClsHooked = function () { + var nodeVer = process.versions.node.split("."); + var greater800 = (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 0); + var less820 = (parseInt(nodeVer[0]) < 8) || (parseInt(nodeVer[0]) <= 8 && parseInt(nodeVer[1]) < 2); + var greater470 = parseInt(nodeVer[0]) > 4 || (parseInt(nodeVer[0]) >= 4 && parseInt(nodeVer[1]) >= 7); // cls-hooked requires node 4.7+ + return !(greater800 && less820) && greater470; + }; + CorrelationContextManager.enabled = false; + CorrelationContextManager.hasEverEnabled = false; + CorrelationContextManager.forceClsHooked = undefined; // true: use cls-hooked, false: use cls, undefined: choose based on node version + CorrelationContextManager.CONTEXT_NAME = "ApplicationInsights-Context"; + return CorrelationContextManager; +}()); +exports.CorrelationContextManager = CorrelationContextManager; +var CustomPropertiesImpl = /** @class */ (function () { + function CustomPropertiesImpl(header) { + this.props = []; + this.addHeaderData(header); + } + CustomPropertiesImpl.prototype.addHeaderData = function (header) { + var keyvals = header ? header.split(", ") : []; + this.props = keyvals.map(function (keyval) { + var parts = keyval.split("="); + return { key: parts[0], value: parts[1] }; + }).concat(this.props); + }; + CustomPropertiesImpl.prototype.serializeToHeader = function () { + return this.props.map(function (keyval) { + return keyval.key + "=" + keyval.value; + }).join(", "); + }; + CustomPropertiesImpl.prototype.getProperty = function (prop) { + for (var i = 0; i < this.props.length; ++i) { + var keyval = this.props[i]; + if (keyval.key === prop) { + return keyval.value; + } + } + return; + }; + // TODO: Strictly according to the spec, properties which are recieved from + // an incoming request should be left untouched, while we may add our own new + // properties. The logic here will need to change to track that. + CustomPropertiesImpl.prototype.setProperty = function (prop, val) { + if (CustomPropertiesImpl.bannedCharacters.test(prop) || CustomPropertiesImpl.bannedCharacters.test(val)) { + Logging.warn("Correlation context property keys and values must not contain ',' or '='. setProperty was called with key: " + prop + " and value: " + val); + return; + } + for (var i = 0; i < this.props.length; ++i) { + var keyval = this.props[i]; + if (keyval.key === prop) { + keyval.value = val; + return; + } + } + this.props.push({ key: prop, value: val }); + }; + CustomPropertiesImpl.bannedCharacters = /[,=]/; + return CustomPropertiesImpl; +}()); +//# sourceMappingURL=CorrelationContextManager.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js.map b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js.map new file mode 100644 index 0000000..54daa15 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/CorrelationContextManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CorrelationContextManager.js","sourceRoot":"","sources":["../../AutoCollection/CorrelationContextManager.ts"],"names":[],"mappings":";;;AACA,4CAA+C;AAC/C,iEAAmE;AAMnE,oDAAuD;AACvD,kDAAqD;AACrD,uDAA0D;AAG1D,sCAAyC;AAoCzC;IAAA;IAyRA,CAAC;IAjRG;;;;OAIG;IACW,2CAAiB,GAA/B;QACI,IAAI,CAAC,yBAAyB,CAAC,OAAO,EAAE;YACpC,OAAO,IAAI,CAAC;SACf;QACD,IAAM,OAAO,GAAG,yBAAyB,CAAC,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,YAAY,CAAC,CAAC;QAE9F,IAAI,OAAO,KAAK,SAAS,EAAE,EAAE,yBAAyB;YAClD,OAAO,IAAI,CAAC;SACf;QACD,OAAO,OAAO,CAAC;IACnB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,CAAC;YAC1J,OAAO;SACV;QACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE;YACxC,IAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7B,IAAI,MAAM,CAAC,GAAG,KAAK,IAAI,EAAE;gBACrB,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC;gBACnB,OAAO;aACV;SACJ;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IAC/C,CAAC;IA/Cc,qCAAgB,GAAG,MAAM,CAAC;IAgD7C,2BAAC;CAAA,AAjDD,IAiDC","sourcesContent":["import events = require(\"events\");\r\nimport Logging = require(\"../Library/Logging\");\r\nimport * as DiagChannel from \"./diagnostic-channel/initialization\";\r\nimport * as azureFunctionsTypes from \"../Library/Functions\";\r\n\r\n// Don't reference modules from these directly. Use only for types.\r\nimport * as cls from \"cls-hooked\";\r\nimport * as http from \"http\";\r\nimport Traceparent = require(\"../Library/Traceparent\");\r\nimport Tracestate = require(\"../Library/Tracestate\");\r\nimport HttpRequestParser = require(\"./HttpRequestParser\");\r\nimport { SpanContext } from \"@opentelemetry/api\";\r\nimport { Span } from \"@opentelemetry/sdk-trace-base\";\r\nimport Util = require(\"../Library/Util\");\r\n\r\nexport interface CustomProperties {\r\n /**\r\n * Get a custom property from the correlation context\r\n */\r\n getProperty(key: string): string;\r\n /**\r\n * Store a custom property in the correlation context.\r\n * Do not store sensitive information here.\r\n * Properties stored here are exposed via outgoing HTTP headers for correlating data cross-component.\r\n * The characters ',' and '=' are disallowed within keys or values.\r\n */\r\n setProperty(key: string, value: string): void;\r\n}\r\n\r\nexport interface PrivateCustomProperties extends CustomProperties {\r\n addHeaderData(header: string): void;\r\n serializeToHeader(): string;\r\n}\r\n\r\nexport interface CorrelationContext {\r\n operation: {\r\n name: string;\r\n id: string;\r\n parentId: string; // Always used for dependencies, may be ignored in favor of incoming headers for requests\r\n traceparent?: Traceparent; // w3c context trace\r\n tracestate?: Tracestate; // w3c context state\r\n };\r\n\r\n /** Do not store sensitive information here.\r\n * Properties here are exposed via outgoing HTTP headers for correlating data cross-component.\r\n */\r\n customProperties: CustomProperties\r\n}\r\n\r\nexport class CorrelationContextManager {\r\n private static enabled: boolean = false;\r\n private static hasEverEnabled: boolean = false;\r\n private static forceClsHooked: boolean = undefined; // true: use cls-hooked, false: use cls, undefined: choose based on node version\r\n private static session: cls.Namespace;\r\n private static cls: typeof cls;\r\n private static CONTEXT_NAME = \"ApplicationInsights-Context\";\r\n\r\n /**\r\n * Provides the current Context.\r\n * The context is the most recent one entered into for the current\r\n * logical chain of execution, including across asynchronous calls.\r\n */\r\n public static getCurrentContext(): CorrelationContext | null {\r\n if (!CorrelationContextManager.enabled) {\r\n return null;\r\n }\r\n const context = CorrelationContextManager.session.get(CorrelationContextManager.CONTEXT_NAME);\r\n\r\n if (context === undefined) { // cast undefined to null\r\n return null;\r\n }\r\n return context;\r\n }\r\n\r\n /**\r\n * A helper to generate objects conforming to the CorrelationContext interface\r\n */\r\n public static generateContextObject(operationId: string, parentId?: string, operationName?: string, correlationContextHeader?: string, traceparent?: Traceparent, tracestate?: Tracestate): CorrelationContext {\r\n parentId = parentId || operationId;\r\n\r\n if (this.enabled) {\r\n return {\r\n operation: {\r\n name: operationName,\r\n id: operationId,\r\n parentId: parentId,\r\n traceparent,\r\n tracestate\r\n },\r\n customProperties: new CustomPropertiesImpl(correlationContextHeader)\r\n };\r\n }\r\n\r\n return null;\r\n }\r\n\r\n public static spanToContextObject(spanContext: SpanContext, parentId?: string, name?: string): CorrelationContext {\r\n const traceContext = new Traceparent();\r\n traceContext.traceId = spanContext.traceId;\r\n traceContext.spanId = spanContext.spanId;\r\n traceContext.traceFlag = Traceparent.formatOpenTelemetryTraceFlags(spanContext.traceFlags) || Traceparent.DEFAULT_TRACE_FLAG;\r\n traceContext.parentId = parentId;\r\n return CorrelationContextManager.generateContextObject(traceContext.traceId, traceContext.parentId, name, null, traceContext);\r\n }\r\n\r\n /**\r\n * Runs a function inside a given Context.\r\n * All logical children of the execution path that entered this Context\r\n * will receive this Context object on calls to GetCurrentContext.\r\n */\r\n public static runWithContext(context: CorrelationContext, fn: () => any): any {\r\n if (CorrelationContextManager.enabled) {\r\n try {\r\n return CorrelationContextManager.session.bind(fn, { [CorrelationContextManager.CONTEXT_NAME]: context })();\r\n }\r\n catch (error) {\r\n Logging.warn(\"Error binding to session context\", Util.dumpObj(error));\r\n }\r\n }\r\n return fn();\r\n }\r\n\r\n /**\r\n * Wrapper for cls-hooked bindEmitter method\r\n */\r\n public static wrapEmitter(emitter: events.EventEmitter): void {\r\n if (CorrelationContextManager.enabled) {\r\n try {\r\n CorrelationContextManager.session.bindEmitter(emitter);\r\n }\r\n catch (error) {\r\n Logging.warn(\"Error binding to session context\", Util.dumpObj(error));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Patches a callback to restore the correct Context when getCurrentContext\r\n * is run within it. This is necessary if automatic correlation fails to work\r\n * with user-included libraries.\r\n *\r\n * The supplied callback will be given the same context that was present for\r\n * the call to wrapCallback. */\r\n public static wrapCallback(fn: T, context?: CorrelationContext): T {\r\n if (CorrelationContextManager.enabled) {\r\n try {\r\n return CorrelationContextManager.session.bind(fn, context ? {\r\n [CorrelationContextManager.CONTEXT_NAME]: context\r\n } : undefined);\r\n }\r\n catch (error) {\r\n Logging.warn(\"Error binding to session context\", Util.dumpObj(error));\r\n }\r\n }\r\n return fn;\r\n }\r\n\r\n /**\r\n * Enables the CorrelationContextManager.\r\n */\r\n public static enable(forceClsHooked?: boolean) {\r\n if (this.enabled) {\r\n return;\r\n }\r\n\r\n if (!this.isNodeVersionCompatible()) {\r\n this.enabled = false;\r\n return;\r\n }\r\n if (!CorrelationContextManager.hasEverEnabled) {\r\n this.forceClsHooked = forceClsHooked;\r\n this.hasEverEnabled = true;\r\n\r\n if (typeof this.cls === \"undefined\") {\r\n if ((CorrelationContextManager.forceClsHooked === true) || (CorrelationContextManager.forceClsHooked === undefined && CorrelationContextManager.shouldUseClsHooked())) {\r\n this.cls = require(\"cls-hooked\");\r\n } else {\r\n this.cls = require(\"continuation-local-storage\");\r\n }\r\n }\r\n\r\n CorrelationContextManager.session = this.cls.createNamespace(\"AI-CLS-Session\");\r\n\r\n DiagChannel.registerContextPreservation((cb) => {\r\n try {\r\n return CorrelationContextManager.session.bind(cb);\r\n }\r\n catch (error) {\r\n Logging.warn(\"Error binding to session context\", Util.dumpObj(error));\r\n }\r\n });\r\n }\r\n\r\n this.enabled = true;\r\n }\r\n\r\n /**\r\n * Create new correlation context.\r\n */\r\n public static startOperation(\r\n input: azureFunctionsTypes.Context | (http.IncomingMessage | azureFunctionsTypes.HttpRequest) | SpanContext | Span,\r\n request?: azureFunctionsTypes.HttpRequest | string)\r\n : CorrelationContext | null {\r\n const traceContext = input && (input as azureFunctionsTypes.Context).traceContext || null;\r\n const span = input && (input as Span).spanContext ? input as Span : null;\r\n const spanContext = input && (input as SpanContext).traceId ? input as SpanContext : null;\r\n const headers = input && (input as http.IncomingMessage | azureFunctionsTypes.HttpRequest).headers;\r\n\r\n // OpenTelemetry Span\r\n if (span) {\r\n return this.spanToContextObject(span.spanContext(), span.parentSpanId, span.name);\r\n }\r\n\r\n // OpenTelemetry SpanContext\r\n if (spanContext) {\r\n return this.spanToContextObject(spanContext, `|${spanContext.traceId}.${spanContext.spanId}.`, typeof request === \"string\" ? request : \"\");\r\n }\r\n\r\n let operationName = typeof request === \"string\" ? request : \"\";\r\n\r\n // AzFunction TraceContext\r\n if (traceContext) {\r\n let traceparent = null;\r\n let tracestate = null;\r\n operationName = traceContext.attributes[\"OperationName\"] || operationName;\r\n if (request) {\r\n let azureFnRequest = request as azureFunctionsTypes.HttpRequest;\r\n if (azureFnRequest.headers) {\r\n if (azureFnRequest.headers.traceparent) {\r\n traceparent = new Traceparent(azureFnRequest.headers.traceparent);\r\n } else if (azureFnRequest.headers[\"request-id\"]) {\r\n traceparent = new Traceparent(null, azureFnRequest.headers[\"request-id\"]);\r\n }\r\n if (azureFnRequest.headers.tracestate) {\r\n tracestate = new Tracestate(azureFnRequest.headers.tracestate);\r\n }\r\n }\r\n }\r\n if (!traceparent) {\r\n traceparent = new Traceparent(traceContext.traceparent);\r\n }\r\n if (!tracestate) {\r\n tracestate = new Tracestate(traceContext.tracestate);\r\n }\r\n\r\n let correlationContextHeader = undefined;\r\n if (typeof request === \"object\") {\r\n const parser = new HttpRequestParser(request);\r\n correlationContextHeader = parser.getCorrelationContextHeader();\r\n operationName = parser.getOperationName({});\r\n }\r\n const correlationContext = CorrelationContextManager.generateContextObject(\r\n traceparent.traceId,\r\n traceparent.parentId,\r\n operationName,\r\n correlationContextHeader,\r\n traceparent,\r\n tracestate\r\n );\r\n\r\n return correlationContext;\r\n }\r\n\r\n // No TraceContext available, parse as http.IncomingMessage\r\n if (headers) {\r\n const traceparent = new Traceparent(headers.traceparent ? headers.traceparent.toString() : null);\r\n const tracestate = new Tracestate(headers.tracestate ? headers.tracestate.toString() : null);\r\n const parser = new HttpRequestParser(input as http.IncomingMessage | azureFunctionsTypes.HttpRequest);\r\n const correlationContext = CorrelationContextManager.generateContextObject(\r\n traceparent.traceId,\r\n traceparent.parentId,\r\n parser.getOperationName({}),\r\n parser.getCorrelationContextHeader(),\r\n traceparent,\r\n tracestate\r\n );\r\n\r\n return correlationContext;\r\n }\r\n\r\n Logging.warn(\"startOperation was called with invalid arguments\", arguments);\r\n return null;\r\n }\r\n\r\n /**\r\n * Disables the CorrelationContextManager.\r\n */\r\n public static disable() {\r\n this.enabled = false;\r\n }\r\n\r\n /**\r\n * Reset the namespace\r\n */\r\n public static reset() {\r\n if (CorrelationContextManager.hasEverEnabled) {\r\n CorrelationContextManager.session = null;\r\n CorrelationContextManager.session = this.cls.createNamespace(\"AI-CLS-Session\");\r\n }\r\n }\r\n\r\n /**\r\n * Reports if CorrelationContextManager is able to run in this environment\r\n */\r\n public static isNodeVersionCompatible() {\r\n var nodeVer = process.versions.node.split(\".\");\r\n return parseInt(nodeVer[0]) > 3 || (parseInt(nodeVer[0]) > 2 && parseInt(nodeVer[1]) > 2);\r\n\r\n }\r\n\r\n /**\r\n * We only want to use cls-hooked when it uses async_hooks api (8.2+), else\r\n * use async-listener (plain -cls)\r\n */\r\n public static shouldUseClsHooked() {\r\n var nodeVer = process.versions.node.split(\".\");\r\n return (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 2);\r\n }\r\n\r\n /**\r\n * A TypeError is triggered by cls-hooked for node [8.0, 8.2)\r\n * @internal Used in tests only\r\n */\r\n public static canUseClsHooked() {\r\n var nodeVer = process.versions.node.split(\".\");\r\n var greater800 = (parseInt(nodeVer[0]) > 8) || (parseInt(nodeVer[0]) >= 8 && parseInt(nodeVer[1]) >= 0);\r\n var less820 = (parseInt(nodeVer[0]) < 8) || (parseInt(nodeVer[0]) <= 8 && parseInt(nodeVer[1]) < 2)\r\n var greater470 = parseInt(nodeVer[0]) > 4 || (parseInt(nodeVer[0]) >= 4 && parseInt(nodeVer[1]) >= 7) // cls-hooked requires node 4.7+\r\n return !(greater800 && less820) && greater470;\r\n }\r\n}\r\n\r\nclass CustomPropertiesImpl implements PrivateCustomProperties {\r\n private static bannedCharacters = /[,=]/;\r\n private props: { key: string, value: string }[] = [];\r\n\r\n public constructor(header: string) {\r\n this.addHeaderData(header);\r\n }\r\n\r\n public addHeaderData(header?: string) {\r\n const keyvals = header ? header.split(\", \") : [];\r\n this.props = keyvals.map((keyval) => {\r\n const parts = keyval.split(\"=\");\r\n return { key: parts[0], value: parts[1] };\r\n }).concat(this.props);\r\n }\r\n\r\n public serializeToHeader() {\r\n return this.props.map((keyval) => {\r\n return `${keyval.key}=${keyval.value}`\r\n }).join(\", \");\r\n }\r\n\r\n public getProperty(prop: string) {\r\n for (let i = 0; i < this.props.length; ++i) {\r\n const keyval = this.props[i]\r\n if (keyval.key === prop) {\r\n return keyval.value;\r\n }\r\n }\r\n return;\r\n }\r\n\r\n // TODO: Strictly according to the spec, properties which are recieved from\r\n // an incoming request should be left untouched, while we may add our own new\r\n // properties. The logic here will need to change to track that.\r\n public setProperty(prop: string, val: string) {\r\n if (CustomPropertiesImpl.bannedCharacters.test(prop) || CustomPropertiesImpl.bannedCharacters.test(val)) {\r\n Logging.warn(\"Correlation context property keys and values must not contain ',' or '='. setProperty was called with key: \" + prop + \" and value: \" + val);\r\n return;\r\n }\r\n for (let i = 0; i < this.props.length; ++i) {\r\n const keyval = this.props[i];\r\n if (keyval.key === prop) {\r\n keyval.value = val;\r\n return;\r\n }\r\n }\r\n this.props.push({ key: prop, value: val });\r\n }\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Exceptions.d.ts b/node_modules/applicationinsights/out/AutoCollection/Exceptions.d.ts new file mode 100644 index 0000000..4028077 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Exceptions.d.ts @@ -0,0 +1,19 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +declare class AutoCollectExceptions { + static INSTANCE: AutoCollectExceptions; + static UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME: string; + static UNCAUGHT_EXCEPTION_HANDLER_NAME: string; + static UNHANDLED_REJECTION_HANDLER_NAME: string; + private static _RETHROW_EXIT_MESSAGE; + private static _FALLBACK_ERROR_MESSAGE; + private static _canUseUncaughtExceptionMonitor; + private _exceptionListenerHandle; + private _rejectionListenerHandle; + private _client; + private _isInitialized; + constructor(client: TelemetryClient); + isInitialized(): boolean; + enable(isEnabled: boolean): void; + dispose(): void; +} +export = AutoCollectExceptions; diff --git a/node_modules/applicationinsights/out/AutoCollection/Exceptions.js b/node_modules/applicationinsights/out/AutoCollection/Exceptions.js new file mode 100644 index 0000000..52b99ee --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Exceptions.js @@ -0,0 +1,81 @@ +"use strict"; +var AutoCollectExceptions = /** @class */ (function () { + function AutoCollectExceptions(client) { + if (!!AutoCollectExceptions.INSTANCE) { + throw new Error("Exception tracking should be configured from the applicationInsights object"); + } + AutoCollectExceptions.INSTANCE = this; + this._client = client; + // Only use for 13.7.0+ + var nodeVer = process.versions.node.split("."); + AutoCollectExceptions._canUseUncaughtExceptionMonitor = parseInt(nodeVer[0]) > 13 || (parseInt(nodeVer[0]) === 13 && parseInt(nodeVer[1]) >= 7); + } + AutoCollectExceptions.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectExceptions.prototype.enable = function (isEnabled) { + var _this = this; + if (isEnabled) { + this._isInitialized = true; + if (!this._exceptionListenerHandle) { + // For scenarios like Promise.reject(), an error won't be passed to the handle. Create a placeholder + // error for these scenarios. + var handle = function (reThrow, name, error) { + if (error === void 0) { error = new Error(AutoCollectExceptions._FALLBACK_ERROR_MESSAGE); } + var exceptionTelemetry = { exception: error }; + // Add full error in context so it could used in telemetryProcessors + exceptionTelemetry.contextObjects = {}; + exceptionTelemetry.contextObjects["Error"] = error; + _this._client.trackException(exceptionTelemetry); + _this._client.flush({ isAppCrashing: true }); + // only rethrow when we are the only listener + if (reThrow && name && process.listeners(name).length === 1) { + console.error(error); + process.exit(1); + } + }; + if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) { + // Node.js >= 13.7.0, use uncaughtExceptionMonitor. It handles both promises and exceptions + this._exceptionListenerHandle = handle.bind(this, false, undefined); // never rethrows + process.on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle); + } + else { + this._exceptionListenerHandle = handle.bind(this, true, AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME); + this._rejectionListenerHandle = handle.bind(this, false, undefined); // never rethrows + process.on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle); + process.on(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle); + } + } + } + else { + if (this._exceptionListenerHandle) { + if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) { + process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle); + } + else { + process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle); + process.removeListener(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle); + } + this._exceptionListenerHandle = undefined; + this._rejectionListenerHandle = undefined; + delete this._exceptionListenerHandle; + delete this._rejectionListenerHandle; + } + } + }; + AutoCollectExceptions.prototype.dispose = function () { + AutoCollectExceptions.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + AutoCollectExceptions.INSTANCE = null; + AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME = "uncaughtExceptionMonitor"; + AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME = "uncaughtException"; + AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME = "unhandledRejection"; + AutoCollectExceptions._RETHROW_EXIT_MESSAGE = "Application Insights Rethrow Exception Handler"; + AutoCollectExceptions._FALLBACK_ERROR_MESSAGE = "A promise was rejected without providing an error. Application Insights generated this error stack for you."; + AutoCollectExceptions._canUseUncaughtExceptionMonitor = false; + return AutoCollectExceptions; +}()); +module.exports = AutoCollectExceptions; +//# sourceMappingURL=Exceptions.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Exceptions.js.map b/node_modules/applicationinsights/out/AutoCollection/Exceptions.js.map new file mode 100644 index 0000000..5fffc19 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Exceptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Exceptions.js","sourceRoot":"","sources":["../../AutoCollection/Exceptions.ts"],"names":[],"mappings":";AAIA;IAeI,+BAAY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CAAC,cAAc,CAAC,qBAAqB,CAAC,+BAA+B,EAAE,IAAI,CAAC,wBAAwB,CAAC,CAAC;oBAC7G,OAAO,CAAC,cAAc,CAAC,qBAAqB,CAAC,gCAAgC,EAAE,IAAI,CAAC,wBAAwB,CAAC,CAAC;iBACjH;gBACD,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;gBAC1C,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;gBAC1C,OAAO,IAAI,CAAC,wBAAwB,CAAC;gBACrC,OAAO,IAAI,CAAC,wBAAwB,CAAC;aACxC;SACJ;IACL,CAAC;IAEM,uCAAO,GAAd;QACI,qBAAqB,CAAC,QAAQ,GAAG,IAAI,CAAC;QACtC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IAlFa,8BAAQ,GAA0B,IAAI,CAAC;IACvC,6DAAuC,GAAG,0BAA0B,CAAC;IACrE,qDAA+B,GAAG,mBAAmB,CAAC;IACtD,sDAAgC,GAAG,oBAAoB,CAAC;IAEvD,2CAAqB,GAAG,gDAAgD,CAAC;IACzE,6CAAuB,GAAG,6GAA6G,CAAC;IACxI,qDAA+B,GAAG,KAAK,CAAC;IA4E3D,4BAAC;CAAA,AArFD,IAqFC;AAID,iBAAS,qBAAqB,CAAC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\n\r\n\r\nclass AutoCollectExceptions {\r\n\r\n public static INSTANCE: AutoCollectExceptions = null;\r\n public static UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME = \"uncaughtExceptionMonitor\";\r\n public static UNCAUGHT_EXCEPTION_HANDLER_NAME = \"uncaughtException\";\r\n public static UNHANDLED_REJECTION_HANDLER_NAME = \"unhandledRejection\";\r\n\r\n private static _RETHROW_EXIT_MESSAGE = \"Application Insights Rethrow Exception Handler\";\r\n private static _FALLBACK_ERROR_MESSAGE = \"A promise was rejected without providing an error. Application Insights generated this error stack for you.\";\r\n private static _canUseUncaughtExceptionMonitor = false;\r\n private _exceptionListenerHandle: (reThrow: boolean, error: Error) => void;\r\n private _rejectionListenerHandle: (reThrow: boolean, error: Error) => void;\r\n private _client: TelemetryClient;\r\n private _isInitialized: boolean;\r\n\r\n constructor(client: TelemetryClient) {\r\n if (!!AutoCollectExceptions.INSTANCE) {\r\n throw new Error(\"Exception tracking should be configured from the applicationInsights object\");\r\n }\r\n\r\n AutoCollectExceptions.INSTANCE = this;\r\n this._client = client;\r\n\r\n // Only use for 13.7.0+\r\n const nodeVer = process.versions.node.split(\".\");\r\n AutoCollectExceptions._canUseUncaughtExceptionMonitor = parseInt(nodeVer[0]) > 13 || (parseInt(nodeVer[0]) === 13 && parseInt(nodeVer[1]) >= 7);\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n if (isEnabled) {\r\n this._isInitialized = true;\r\n if (!this._exceptionListenerHandle) {\r\n // For scenarios like Promise.reject(), an error won't be passed to the handle. Create a placeholder\r\n // error for these scenarios.\r\n var handle = (reThrow: boolean, name: string, error: Error = new Error(AutoCollectExceptions._FALLBACK_ERROR_MESSAGE)) => {\r\n let exceptionTelemetry: Contracts.ExceptionTelemetry = { exception: error };\r\n // Add full error in context so it could used in telemetryProcessors\r\n exceptionTelemetry.contextObjects = {};\r\n exceptionTelemetry.contextObjects[\"Error\"] = error;\r\n this._client.trackException(exceptionTelemetry);\r\n this._client.flush({ isAppCrashing: true });\r\n // only rethrow when we are the only listener\r\n if (reThrow && name && (process).listeners(name).length === 1) {\r\n console.error(error);\r\n process.exit(1);\r\n }\r\n };\r\n\r\n if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) {\r\n // Node.js >= 13.7.0, use uncaughtExceptionMonitor. It handles both promises and exceptions\r\n this._exceptionListenerHandle = handle.bind(this, false, undefined); // never rethrows\r\n (process).on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle);\r\n } else {\r\n this._exceptionListenerHandle = handle.bind(this, true, AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME);\r\n this._rejectionListenerHandle = handle.bind(this, false, undefined); // never rethrows\r\n (process).on(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle);\r\n (process).on(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle);\r\n }\r\n }\r\n\r\n } else {\r\n if (this._exceptionListenerHandle) {\r\n if (AutoCollectExceptions._canUseUncaughtExceptionMonitor) {\r\n process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_MONITOR_HANDLER_NAME, this._exceptionListenerHandle);\r\n } else {\r\n process.removeListener(AutoCollectExceptions.UNCAUGHT_EXCEPTION_HANDLER_NAME, this._exceptionListenerHandle);\r\n process.removeListener(AutoCollectExceptions.UNHANDLED_REJECTION_HANDLER_NAME, this._rejectionListenerHandle);\r\n }\r\n this._exceptionListenerHandle = undefined;\r\n this._rejectionListenerHandle = undefined;\r\n delete this._exceptionListenerHandle;\r\n delete this._rejectionListenerHandle;\r\n }\r\n }\r\n }\r\n\r\n public dispose() {\r\n AutoCollectExceptions.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\n\r\n\r\nexport = AutoCollectExceptions;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HeartBeat.d.ts b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.d.ts new file mode 100644 index 0000000..9b3e329 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.d.ts @@ -0,0 +1,18 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +import Config = require("../Library/Config"); +declare class HeartBeat { + static INSTANCE: HeartBeat; + private _collectionInterval; + private _client; + private _handle; + private _isEnabled; + private _isInitialized; + private _isVM; + constructor(client: TelemetryClient); + enable(isEnabled: boolean): void; + isInitialized(): boolean; + static isEnabled(): boolean; + trackHeartBeat(config: Config, callback: () => void): void; + dispose(): void; +} +export = HeartBeat; diff --git a/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js new file mode 100644 index 0000000..13fa861 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js @@ -0,0 +1,83 @@ +"use strict"; +var os = require("os"); +var Vm = require("../Library/AzureVirtualMachine"); +var Constants = require("../Declarations/Constants"); +var Context = require("../Library/Context"); +var HeartBeat = /** @class */ (function () { + function HeartBeat(client) { + this._collectionInterval = 900000; + if (!HeartBeat.INSTANCE) { + HeartBeat.INSTANCE = this; + } + this._isInitialized = false; + this._client = client; + } + HeartBeat.prototype.enable = function (isEnabled) { + var _this = this; + this._isEnabled = isEnabled; + if (this._isEnabled && !this._isInitialized) { + this._isInitialized = true; + } + if (isEnabled) { + if (!this._handle) { + this._handle = setInterval(function () { return _this.trackHeartBeat(_this._client.config, function () { }); }, this._collectionInterval); + this._handle.unref(); // Allow the app to terminate even while this loop is going on + } + } + else { + if (this._handle) { + clearInterval(this._handle); + this._handle = null; + } + } + }; + HeartBeat.prototype.isInitialized = function () { + return this._isInitialized; + }; + HeartBeat.isEnabled = function () { + return HeartBeat.INSTANCE && HeartBeat.INSTANCE._isEnabled; + }; + HeartBeat.prototype.trackHeartBeat = function (config, callback) { + var _this = this; + var waiting = false; + var properties = {}; + var sdkVersion = Context.sdkVersion; // "node" or "node-nativeperf" + properties["sdk"] = sdkVersion; + properties["osType"] = os.type(); + if (process.env.WEBSITE_SITE_NAME) { // Web apps + properties["appSrv_SiteName"] = process.env.WEBSITE_SITE_NAME || ""; + properties["appSrv_wsStamp"] = process.env.WEBSITE_HOME_STAMPNAME || ""; + properties["appSrv_wsHost"] = process.env.WEBSITE_HOSTNAME || ""; + } + else if (process.env.FUNCTIONS_WORKER_RUNTIME) { // Function apps + properties["azfunction_appId"] = process.env.WEBSITE_HOSTNAME; + } + else if (config) { + if (this._isVM === undefined) { + waiting = true; + Vm.AzureVirtualMachine.getAzureComputeMetadata(config, function (vmInfo) { + _this._isVM = vmInfo.isVM; + if (_this._isVM) { + properties["azInst_vmId"] = vmInfo.id; + properties["azInst_subscriptionId"] = vmInfo.subscriptionId; + properties["azInst_osType"] = vmInfo.osType; + } + _this._client.trackMetric({ name: Constants.HeartBeatMetricName, value: 0, properties: properties }); + callback(); + }); + } + } + if (!waiting) { + this._client.trackMetric({ name: Constants.HeartBeatMetricName, value: 0, properties: properties }); + callback(); + } + }; + HeartBeat.prototype.dispose = function () { + HeartBeat.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + return HeartBeat; +}()); +module.exports = HeartBeat; +//# sourceMappingURL=HeartBeat.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js.map b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js.map new file mode 100644 index 0000000..2cf0be0 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HeartBeat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HeartBeat.js","sourceRoot":"","sources":["../../AutoCollection/HeartBeat.ts"],"names":[],"mappings":";AAAA,uBAA0B;AAC1B,mDAAsD;AAEtD,qDAAwD;AAExD,4CAA+C;AAE/C;IAWI,mBAAY,MAAuB;QAP3B,wBAAmB,GAAW,MAAM,CAAC;QAQzC,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE;YACrB,SAAS,CAAC,QAAQ,GAAG,IAAI,CAAC;SAC7B;QACD,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;QAC5B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAEM,0BAAM,GAAb,UAAc,SAAkB;QAAhC,iBAiBC;QAhBG,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,UAAU,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AC,QAAQ,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IACL,gBAAC;AAAD,CAAC,AApFD,IAoFC;AAED,iBAAS,SAAS,CAAC","sourcesContent":["import os = require(\"os\");\r\nimport Vm = require(\"../Library/AzureVirtualMachine\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport Config = require(\"../Library/Config\");\r\nimport Context = require(\"../Library/Context\");\r\n\r\nclass HeartBeat {\r\n\r\n public static INSTANCE: HeartBeat;\r\n\r\n private _collectionInterval: number = 900000;\r\n private _client: TelemetryClient;\r\n private _handle: NodeJS.Timer | null;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _isVM: boolean;\r\n\r\n constructor(client: TelemetryClient) {\r\n if (!HeartBeat.INSTANCE) {\r\n HeartBeat.INSTANCE = this;\r\n }\r\n this._isInitialized = false;\r\n this._client = client;\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n this._isEnabled = isEnabled;\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._isInitialized = true;\r\n }\r\n\r\n if (isEnabled) {\r\n if (!this._handle) {\r\n this._handle = setInterval(() => this.trackHeartBeat(this._client.config, () => { }), this._collectionInterval);\r\n this._handle.unref(); // Allow the app to terminate even while this loop is going on\r\n }\r\n } else {\r\n if (this._handle) {\r\n clearInterval(this._handle);\r\n this._handle = null;\r\n }\r\n }\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public static isEnabled() {\r\n return HeartBeat.INSTANCE && HeartBeat.INSTANCE._isEnabled;\r\n }\r\n\r\n public trackHeartBeat(config: Config, callback: () => void) {\r\n let waiting: boolean = false;\r\n let properties: { [key: string]: string } = {};\r\n const sdkVersion = Context.sdkVersion; // \"node\" or \"node-nativeperf\"\r\n properties[\"sdk\"] = sdkVersion;\r\n properties[\"osType\"] = os.type();\r\n if (process.env.WEBSITE_SITE_NAME) { // Web apps\r\n properties[\"appSrv_SiteName\"] = process.env.WEBSITE_SITE_NAME || \"\";\r\n properties[\"appSrv_wsStamp\"] = process.env.WEBSITE_HOME_STAMPNAME || \"\";\r\n properties[\"appSrv_wsHost\"] = process.env.WEBSITE_HOSTNAME || \"\";\r\n } else if (process.env.FUNCTIONS_WORKER_RUNTIME) { // Function apps\r\n properties[\"azfunction_appId\"] = process.env.WEBSITE_HOSTNAME;\r\n } else if (config) {\r\n if (this._isVM === undefined) {\r\n waiting = true;\r\n Vm.AzureVirtualMachine.getAzureComputeMetadata(config, (vmInfo) => {\r\n this._isVM = vmInfo.isVM;\r\n if (this._isVM) {\r\n properties[\"azInst_vmId\"] = vmInfo.id;\r\n properties[\"azInst_subscriptionId\"] = vmInfo.subscriptionId;\r\n properties[\"azInst_osType\"] = vmInfo.osType;\r\n }\r\n this._client.trackMetric({ name: Constants.HeartBeatMetricName, value: 0, properties: properties });\r\n callback();\r\n });\r\n }\r\n }\r\n if (!waiting) {\r\n this._client.trackMetric({ name: Constants.HeartBeatMetricName, value: 0, properties: properties });\r\n callback();\r\n }\r\n }\r\n\r\n public dispose() {\r\n HeartBeat.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\nexport = HeartBeat;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.d.ts b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.d.ts new file mode 100644 index 0000000..0de48ee --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.d.ts @@ -0,0 +1,22 @@ +import Contracts = require("../Declarations/Contracts"); +import TelemetryClient = require("../Library/TelemetryClient"); +declare class AutoCollectHttpDependencies { + static disableCollectionRequestOption: string; + static INSTANCE: AutoCollectHttpDependencies; + private static requestNumber; + private static alreadyAutoCollectedFlag; + private _client; + private _isEnabled; + private _isInitialized; + constructor(client: TelemetryClient); + enable(isEnabled: boolean): void; + isInitialized(): boolean; + private _initialize; + /** + * Tracks an outgoing request. Because it may set headers this method must be called before + * writing content to or ending the request. + */ + static trackRequest(client: TelemetryClient, telemetry: Contracts.NodeHttpDependencyTelemetry): void; + dispose(): void; +} +export = AutoCollectHttpDependencies; diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js new file mode 100644 index 0000000..5b953e5 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js @@ -0,0 +1,267 @@ +"use strict"; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +var http = require("http"); +var https = require("https"); +var Logging = require("../Library/Logging"); +var Util = require("../Library/Util"); +var RequestResponseHeaders = require("../Library/RequestResponseHeaders"); +var HttpDependencyParser = require("./HttpDependencyParser"); +var CorrelationContextManager_1 = require("./CorrelationContextManager"); +var Traceparent = require("../Library/Traceparent"); +var DiagChannel = require("./diagnostic-channel/initialization"); +var CorrelationIdManager = require("../Library/CorrelationIdManager"); +var AutoCollectHttpDependencies = /** @class */ (function () { + function AutoCollectHttpDependencies(client) { + if (!!AutoCollectHttpDependencies.INSTANCE) { + throw new Error("Client request tracking should be configured from the applicationInsights object"); + } + AutoCollectHttpDependencies.INSTANCE = this; + this._client = client; + } + AutoCollectHttpDependencies.prototype.enable = function (isEnabled) { + this._isEnabled = isEnabled; + if (this._isEnabled && !this._isInitialized) { + this._initialize(); + } + if (DiagChannel.IsInitialized) { + require("./diagnostic-channel/azure-coretracing.sub").enable(isEnabled, this._client); + require("./diagnostic-channel/mongodb.sub").enable(isEnabled, this._client); + require("./diagnostic-channel/mysql.sub").enable(isEnabled, this._client); + require("./diagnostic-channel/redis.sub").enable(isEnabled, this._client); + require("./diagnostic-channel/postgres.sub").enable(isEnabled, this._client); + } + }; + AutoCollectHttpDependencies.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectHttpDependencies.prototype._initialize = function () { + var _this = this; + this._isInitialized = true; + var originalRequest = http.request; + var originalHttpsRequest = https.request; + var clientRequestPatch = function (request, options) { + try { + var shouldCollect = !options[AutoCollectHttpDependencies.disableCollectionRequestOption] && + !request[AutoCollectHttpDependencies.alreadyAutoCollectedFlag]; + // If someone else patched traceparent headers onto this request + var userAgentHeader = null; + // Azure SDK special handling + if (options.headers) { + userAgentHeader = options.headers["User-Agent"] || options.headers["user-agent"]; + if (userAgentHeader && userAgentHeader.toString().indexOf("azsdk-js") !== -1) { + shouldCollect = false; + } + } + if (request && options && shouldCollect) { + CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(request); + if (_this._isEnabled) { + // Mark as auto collected + request[AutoCollectHttpDependencies.alreadyAutoCollectedFlag] = true; + // If there is no context create one, this apply when no request is triggering the dependency + if (!CorrelationContextManager_1.CorrelationContextManager.getCurrentContext()) { + // Create correlation context and wrap execution + var operationId = null; + if (CorrelationIdManager.w3cEnabled) { + var traceparent = new Traceparent(); + operationId = traceparent.traceId; + } + else { + var requestId = CorrelationIdManager.generateRequestId(null); + operationId = CorrelationIdManager.getRootId(requestId); + } + var correlationContext = CorrelationContextManager_1.CorrelationContextManager.generateContextObject(operationId); + CorrelationContextManager_1.CorrelationContextManager.runWithContext(correlationContext, function () { + AutoCollectHttpDependencies.trackRequest(_this._client, { options: options, request: request }); + }); + } + else { + AutoCollectHttpDependencies.trackRequest(_this._client, { options: options, request: request }); + } + } + } + } + catch (err) { + Logging.warn("Failed to generate dependency telemetry.", Util.dumpObj(err)); + } + }; + // On node >= v0.11.12 and < 9.0 (excluding 8.9.0) https.request just calls http.request (with additional options). + // On node < 0.11.12, 8.9.0, and 9.0 > https.request is handled separately + // Patch both and leave a flag to not double-count on versions that just call through + // We add the flag to both http and https to protect against strange double collection in other scenarios + http.request = function (options) { + var requestArgs = []; + for (var _i = 1; _i < arguments.length; _i++) { + requestArgs[_i - 1] = arguments[_i]; + } + var request = originalRequest.call.apply(originalRequest, __spreadArrays([http, options], requestArgs)); + clientRequestPatch(request, options); + return request; + }; + https.request = function (options) { + var requestArgs = []; + for (var _i = 1; _i < arguments.length; _i++) { + requestArgs[_i - 1] = arguments[_i]; + } + var request = originalHttpsRequest.call.apply(originalHttpsRequest, __spreadArrays([https, options], requestArgs)); + clientRequestPatch(request, options); + return request; + }; + // Node 8 calls http.request from http.get using a local reference! + // We have to patch .get manually in this case and can't just assume request is enough + // We have to replace the entire method in this case. We can't call the original. + // This is because calling the original will give us no chance to set headers as it internally does .end(). + http.get = function (options) { + var _a; + var requestArgs = []; + for (var _i = 1; _i < arguments.length; _i++) { + requestArgs[_i - 1] = arguments[_i]; + } + var request = (_a = http.request).call.apply(_a, __spreadArrays([http, options], requestArgs)); + request.end(); + return request; + }; + https.get = function (options) { + var _a; + var requestArgs = []; + for (var _i = 1; _i < arguments.length; _i++) { + requestArgs[_i - 1] = arguments[_i]; + } + var request = (_a = https.request).call.apply(_a, __spreadArrays([https, options], requestArgs)); + request.end(); + return request; + }; + }; + /** + * Tracks an outgoing request. Because it may set headers this method must be called before + * writing content to or ending the request. + */ + AutoCollectHttpDependencies.trackRequest = function (client, telemetry) { + if (!telemetry.options || !telemetry.request || !client) { + Logging.info("AutoCollectHttpDependencies.trackRequest was called with invalid parameters: ", !telemetry.options, !telemetry.request, !client); + return; + } + var requestParser = new HttpDependencyParser(telemetry.options, telemetry.request); + var currentContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + var uniqueRequestId; + var uniqueTraceparent; + if (currentContext && currentContext.operation && currentContext.operation.traceparent && Traceparent.isValidTraceId(currentContext.operation.traceparent.traceId)) { + currentContext.operation.traceparent.updateSpanId(); + uniqueRequestId = currentContext.operation.traceparent.getBackCompatRequestId(); + } + else if (CorrelationIdManager.w3cEnabled) { + // Start an operation now so that we can include the w3c headers in the outgoing request + var traceparent = new Traceparent(); + uniqueTraceparent = traceparent.toString(); + uniqueRequestId = traceparent.getBackCompatRequestId(); + } + else { + uniqueRequestId = currentContext && currentContext.operation && (currentContext.operation.parentId + AutoCollectHttpDependencies.requestNumber++ + "."); + } + // Add the source correlationId to the request headers, if a value was not already provided. + // The getHeader/setHeader methods aren't available on very old Node versions, and + // are not included in the v0.10 type declarations currently used. So check if the + // methods exist before invoking them. + if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl()) && telemetry.request.getHeader && telemetry.request.setHeader) { + if (client.config && client.config.correlationId) { + // getHeader returns "any" type in newer versions of node. In basic scenarios, this will be , but could be modified to anything else via middleware + var correlationHeader = telemetry.request.getHeader(RequestResponseHeaders.requestContextHeader); + try { + Util.safeIncludeCorrelationHeader(client, telemetry.request, correlationHeader); + } + catch (err) { + Logging.warn("Request-Context header could not be set. Correlation of requests may be lost", err); + } + if (currentContext && currentContext.operation) { + try { + telemetry.request.setHeader(RequestResponseHeaders.requestIdHeader, uniqueRequestId); + // Also set legacy headers + if (!client.config.ignoreLegacyHeaders) { + telemetry.request.setHeader(RequestResponseHeaders.parentIdHeader, currentContext.operation.id); + telemetry.request.setHeader(RequestResponseHeaders.rootIdHeader, uniqueRequestId); + } + // Set W3C headers, if available + if (uniqueTraceparent || currentContext.operation.traceparent) { + telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, uniqueTraceparent || currentContext.operation.traceparent.toString()); + } + else if (CorrelationIdManager.w3cEnabled) { + // should never get here since we set uniqueTraceparent above for the w3cEnabled scenario + var traceparent = new Traceparent().toString(); + telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, traceparent); + } + if (currentContext.operation.tracestate) { + var tracestate = currentContext.operation.tracestate.toString(); + if (tracestate) { + telemetry.request.setHeader(RequestResponseHeaders.traceStateHeader, tracestate); + } + } + var correlationContextHeader = currentContext.customProperties.serializeToHeader(); + if (correlationContextHeader) { + telemetry.request.setHeader(RequestResponseHeaders.correlationContextHeader, correlationContextHeader); + } + } + catch (err) { + Logging.warn("Correlation headers could not be set. Correlation of requests may be lost.", err); + } + } + } + } + // Collect dependency telemetry about the request when it finishes. + if (telemetry.request.on) { + telemetry.request.on("response", function (response) { + if (telemetry.isProcessed) { + return; + } + telemetry.isProcessed = true; + requestParser.onResponse(response); + var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId); + dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {}; + dependencyTelemetry.contextObjects["http.RequestOptions"] = telemetry.options; + dependencyTelemetry.contextObjects["http.ClientRequest"] = telemetry.request; + dependencyTelemetry.contextObjects["http.ClientResponse"] = response; + client.trackDependency(dependencyTelemetry); + }); + telemetry.request.on("error", function (error) { + if (telemetry.isProcessed) { + return; + } + telemetry.isProcessed = true; + requestParser.onError(error); + var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId); + dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {}; + dependencyTelemetry.contextObjects["http.RequestOptions"] = telemetry.options; + dependencyTelemetry.contextObjects["http.ClientRequest"] = telemetry.request; + dependencyTelemetry.contextObjects["Error"] = error; + client.trackDependency(dependencyTelemetry); + }); + telemetry.request.on("abort", function () { + if (telemetry.isProcessed) { + return; + } + telemetry.isProcessed = true; + requestParser.onError(new Error("The request has been aborted and the network socket has closed.")); + var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId); + dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {}; + dependencyTelemetry.contextObjects["http.RequestOptions"] = telemetry.options; + dependencyTelemetry.contextObjects["http.ClientRequest"] = telemetry.request; + client.trackDependency(dependencyTelemetry); + }); + } + }; + AutoCollectHttpDependencies.prototype.dispose = function () { + AutoCollectHttpDependencies.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + AutoCollectHttpDependencies.disableCollectionRequestOption = "disableAppInsightsAutoCollection"; + AutoCollectHttpDependencies.requestNumber = 1; + AutoCollectHttpDependencies.alreadyAutoCollectedFlag = "_appInsightsAutoCollected"; + return AutoCollectHttpDependencies; +}()); +module.exports = AutoCollectHttpDependencies; +//# sourceMappingURL=HttpDependencies.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js.map b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js.map new file mode 100644 index 0000000..3bb667a --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencies.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HttpDependencies.js","sourceRoot":"","sources":["../../AutoCollection/HttpDependencies.ts"],"names":[],"mappings":";;;;;;;;AAAA,2BAA8B;AAC9B,6BAAgC;AAGhC,4CAA+C;AAC/C,sCAAyC;AACzC,0EAA6E;AAC7E,6DAAgE;AAChE,yEAAiG;AACjG,oDAAuD;AACvD,iEAAmE;AACnE,sEAAyE;AAEzE;IAYI,qCAAY,MAAuB;QAC/B,IAAI,CAAC,CAAC,2BAA2B,CAAC,QAAQ,EAAE;YACxC,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAC;SACvG;QAED,2BAA2B,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC5C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAEM,4CAAM,GAAb,UAAc,SAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE;YACzC,IAAI,CAAC,WAAW,EAAE,CAAC;SACtB;QACD,IAAI,WAAW,CAAC,aAAa,EAAE;YAC3B,OAAO,CAAC,4CAA4C,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACtF,OAAO,CAAC,kCAAkC,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC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AC,CAAC;gBACpG,IAAI,mBAAmB,GAAG,aAAa,CAAC,sBAAsB,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;gBAC3F,mBAAmB,CAAC,cAAc,GAAG,mBAAmB,CAAC,cAAc,IAAI,EAAE,CAAC;gBAC9E,mBAAmB,CAAC,cAAc,CAAC,qBAAqB,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC;gBAC9E,mBAAmB,CAAC,cAAc,CAAC,oBAAoB,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC;gBAE7E,MAAM,CAAC,eAAe,CAAC,mBAAmB,CAAC,CAAC;YAChD,CAAC,CAAC,CAAC;SACN;IACL,CAAC;IAEM,6CAAO,GAAd;QACI,2BAA2B,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC5C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IA7Pa,0DAA8B,GAAG,kCAAkC,CAAC;IAInE,yCAAa,GAAG,CAAC,CAAC;IAClB,oDAAwB,GAAG,2BAA2B,CAAC;IAyP1E,kCAAC;CAAA,AA/PD,IA+PC;AAED,iBAAS,2BAA2B,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Logging = require(\"../Library/Logging\");\r\nimport Util = require(\"../Library/Util\");\r\nimport RequestResponseHeaders = require(\"../Library/RequestResponseHeaders\");\r\nimport HttpDependencyParser = require(\"./HttpDependencyParser\");\r\nimport { CorrelationContextManager, PrivateCustomProperties } from \"./CorrelationContextManager\";\r\nimport Traceparent = require(\"../Library/Traceparent\");\r\nimport * as DiagChannel from \"./diagnostic-channel/initialization\";\r\nimport CorrelationIdManager = require(\"../Library/CorrelationIdManager\");\r\n\r\nclass AutoCollectHttpDependencies {\r\n public static disableCollectionRequestOption = \"disableAppInsightsAutoCollection\";\r\n\r\n public static INSTANCE: AutoCollectHttpDependencies;\r\n\r\n private static requestNumber = 1;\r\n private static alreadyAutoCollectedFlag = \"_appInsightsAutoCollected\";\r\n\r\n private _client: TelemetryClient;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n\r\n constructor(client: TelemetryClient) {\r\n if (!!AutoCollectHttpDependencies.INSTANCE) {\r\n throw new Error(\"Client request tracking should be configured from the applicationInsights object\");\r\n }\r\n\r\n AutoCollectHttpDependencies.INSTANCE = this;\r\n this._client = client;\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n this._isEnabled = isEnabled;\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._initialize();\r\n }\r\n if (DiagChannel.IsInitialized) {\r\n require(\"./diagnostic-channel/azure-coretracing.sub\").enable(isEnabled, this._client);\r\n require(\"./diagnostic-channel/mongodb.sub\").enable(isEnabled, this._client);\r\n require(\"./diagnostic-channel/mysql.sub\").enable(isEnabled, this._client);\r\n require(\"./diagnostic-channel/redis.sub\").enable(isEnabled, this._client);\r\n require(\"./diagnostic-channel/postgres.sub\").enable(isEnabled, this._client);\r\n }\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n private _initialize() {\r\n this._isInitialized = true;\r\n\r\n const originalRequest = http.request;\r\n const originalHttpsRequest = https.request;\r\n\r\n const clientRequestPatch = (request: http.ClientRequest, options: string | URL | http.RequestOptions | https.RequestOptions) => {\r\n try {\r\n var shouldCollect = !(options)[AutoCollectHttpDependencies.disableCollectionRequestOption] &&\r\n !(request)[AutoCollectHttpDependencies.alreadyAutoCollectedFlag];\r\n\r\n // If someone else patched traceparent headers onto this request\r\n let userAgentHeader = null;\r\n\r\n // Azure SDK special handling\r\n if ((options).headers) {\r\n userAgentHeader = (options).headers[\"User-Agent\"] || (options).headers[\"user-agent\"];\r\n if (userAgentHeader && userAgentHeader.toString().indexOf(\"azsdk-js\") !== -1) {\r\n shouldCollect = false;\r\n }\r\n }\r\n\r\n if (request && options && shouldCollect) {\r\n CorrelationContextManager.wrapEmitter(request);\r\n if (this._isEnabled) {\r\n // Mark as auto collected\r\n (request)[AutoCollectHttpDependencies.alreadyAutoCollectedFlag] = true;\r\n\r\n // If there is no context create one, this apply when no request is triggering the dependency\r\n if (!CorrelationContextManager.getCurrentContext()) {\r\n // Create correlation context and wrap execution\r\n let operationId = null;\r\n if (CorrelationIdManager.w3cEnabled) {\r\n let traceparent = new Traceparent();\r\n operationId = traceparent.traceId;\r\n }\r\n else {\r\n let requestId = CorrelationIdManager.generateRequestId(null);\r\n operationId = CorrelationIdManager.getRootId(requestId);\r\n }\r\n let correlationContext = CorrelationContextManager.generateContextObject(operationId);\r\n CorrelationContextManager.runWithContext(correlationContext, () => {\r\n AutoCollectHttpDependencies.trackRequest(this._client, { options: options, request: request });\r\n });\r\n }\r\n else {\r\n AutoCollectHttpDependencies.trackRequest(this._client, { options: options, request: request });\r\n }\r\n }\r\n }\r\n }\r\n catch (err) {\r\n Logging.warn(\"Failed to generate dependency telemetry.\", Util.dumpObj(err));\r\n }\r\n\r\n };\r\n\r\n // On node >= v0.11.12 and < 9.0 (excluding 8.9.0) https.request just calls http.request (with additional options).\r\n // On node < 0.11.12, 8.9.0, and 9.0 > https.request is handled separately\r\n // Patch both and leave a flag to not double-count on versions that just call through\r\n // We add the flag to both http and https to protect against strange double collection in other scenarios\r\n http.request = (options, ...requestArgs: any[]) => {\r\n const request: http.ClientRequest = originalRequest.call(http, options, ...requestArgs);\r\n clientRequestPatch(request, options);\r\n return request;\r\n };\r\n\r\n https.request = (options, ...requestArgs: any[]) => {\r\n const request: http.ClientRequest = originalHttpsRequest.call(https, options, ...requestArgs);\r\n clientRequestPatch(request, options);\r\n return request;\r\n };\r\n\r\n // Node 8 calls http.request from http.get using a local reference!\r\n // We have to patch .get manually in this case and can't just assume request is enough\r\n // We have to replace the entire method in this case. We can't call the original.\r\n // This is because calling the original will give us no chance to set headers as it internally does .end().\r\n http.get = (options, ...requestArgs: any[]) => {\r\n const request: http.ClientRequest = http.request.call(http, options, ...requestArgs);\r\n request.end();\r\n return request;\r\n };\r\n https.get = (options, ...requestArgs: any[]) => {\r\n const request: http.ClientRequest = https.request.call(https, options, ...requestArgs);\r\n request.end();\r\n return request;\r\n };\r\n }\r\n\r\n /**\r\n * Tracks an outgoing request. Because it may set headers this method must be called before\r\n * writing content to or ending the request.\r\n */\r\n public static trackRequest(client: TelemetryClient, telemetry: Contracts.NodeHttpDependencyTelemetry) {\r\n if (!telemetry.options || !telemetry.request || !client) {\r\n Logging.info(\"AutoCollectHttpDependencies.trackRequest was called with invalid parameters: \", !telemetry.options, !telemetry.request, !client);\r\n return;\r\n }\r\n\r\n let requestParser = new HttpDependencyParser(telemetry.options, telemetry.request);\r\n\r\n const currentContext = CorrelationContextManager.getCurrentContext();\r\n let uniqueRequestId: string;\r\n let uniqueTraceparent: string;\r\n if (currentContext && currentContext.operation && currentContext.operation.traceparent && Traceparent.isValidTraceId(currentContext.operation.traceparent.traceId)) {\r\n currentContext.operation.traceparent.updateSpanId();\r\n uniqueRequestId = currentContext.operation.traceparent.getBackCompatRequestId();\r\n } else if (CorrelationIdManager.w3cEnabled) {\r\n // Start an operation now so that we can include the w3c headers in the outgoing request\r\n const traceparent = new Traceparent();\r\n uniqueTraceparent = traceparent.toString();\r\n uniqueRequestId = traceparent.getBackCompatRequestId();\r\n } else {\r\n uniqueRequestId = currentContext && currentContext.operation && (currentContext.operation.parentId + AutoCollectHttpDependencies.requestNumber++ + \".\");\r\n }\r\n\r\n // Add the source correlationId to the request headers, if a value was not already provided.\r\n // The getHeader/setHeader methods aren't available on very old Node versions, and\r\n // are not included in the v0.10 type declarations currently used. So check if the\r\n // methods exist before invoking them.\r\n if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl()) && telemetry.request.getHeader && telemetry.request.setHeader) {\r\n if (client.config && client.config.correlationId) {\r\n // getHeader returns \"any\" type in newer versions of node. In basic scenarios, this will be , but could be modified to anything else via middleware\r\n const correlationHeader = telemetry.request.getHeader(RequestResponseHeaders.requestContextHeader)\r\n try {\r\n Util.safeIncludeCorrelationHeader(client, telemetry.request, correlationHeader);\r\n } catch (err) {\r\n Logging.warn(\"Request-Context header could not be set. Correlation of requests may be lost\", err);\r\n }\r\n\r\n if (currentContext && currentContext.operation) {\r\n try {\r\n telemetry.request.setHeader(RequestResponseHeaders.requestIdHeader, uniqueRequestId);\r\n // Also set legacy headers\r\n if (!client.config.ignoreLegacyHeaders) {\r\n telemetry.request.setHeader(RequestResponseHeaders.parentIdHeader, currentContext.operation.id);\r\n telemetry.request.setHeader(RequestResponseHeaders.rootIdHeader, uniqueRequestId);\r\n }\r\n\r\n // Set W3C headers, if available\r\n if (uniqueTraceparent || currentContext.operation.traceparent) {\r\n telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, uniqueTraceparent || currentContext.operation.traceparent.toString());\r\n } else if (CorrelationIdManager.w3cEnabled) {\r\n // should never get here since we set uniqueTraceparent above for the w3cEnabled scenario\r\n const traceparent = new Traceparent().toString();\r\n telemetry.request.setHeader(RequestResponseHeaders.traceparentHeader, traceparent);\r\n }\r\n if (currentContext.operation.tracestate) {\r\n const tracestate = currentContext.operation.tracestate.toString();\r\n if (tracestate) {\r\n telemetry.request.setHeader(RequestResponseHeaders.traceStateHeader, tracestate);\r\n }\r\n }\r\n\r\n const correlationContextHeader = (currentContext.customProperties).serializeToHeader();\r\n if (correlationContextHeader) {\r\n telemetry.request.setHeader(RequestResponseHeaders.correlationContextHeader, correlationContextHeader);\r\n }\r\n } catch (err) {\r\n Logging.warn(\"Correlation headers could not be set. Correlation of requests may be lost.\", err);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Collect dependency telemetry about the request when it finishes.\r\n if (telemetry.request.on) {\r\n telemetry.request.on(\"response\", (response: http.ClientResponse) => {\r\n if (telemetry.isProcessed) {\r\n return;\r\n }\r\n telemetry.isProcessed = true;\r\n requestParser.onResponse(response);\r\n var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);\r\n dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {};\r\n dependencyTelemetry.contextObjects[\"http.RequestOptions\"] = telemetry.options;\r\n dependencyTelemetry.contextObjects[\"http.ClientRequest\"] = telemetry.request;\r\n dependencyTelemetry.contextObjects[\"http.ClientResponse\"] = response;\r\n\r\n client.trackDependency(dependencyTelemetry);\r\n });\r\n telemetry.request.on(\"error\", (error: Error) => {\r\n if (telemetry.isProcessed) {\r\n return;\r\n }\r\n telemetry.isProcessed = true;\r\n requestParser.onError(error);\r\n var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);\r\n dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {};\r\n dependencyTelemetry.contextObjects[\"http.RequestOptions\"] = telemetry.options;\r\n dependencyTelemetry.contextObjects[\"http.ClientRequest\"] = telemetry.request;\r\n dependencyTelemetry.contextObjects[\"Error\"] = error;\r\n\r\n client.trackDependency(dependencyTelemetry);\r\n });\r\n telemetry.request.on(\"abort\", () => {\r\n if (telemetry.isProcessed) {\r\n return;\r\n }\r\n telemetry.isProcessed = true;\r\n requestParser.onError(new Error(\"The request has been aborted and the network socket has closed.\"));\r\n var dependencyTelemetry = requestParser.getDependencyTelemetry(telemetry, uniqueRequestId);\r\n dependencyTelemetry.contextObjects = dependencyTelemetry.contextObjects || {};\r\n dependencyTelemetry.contextObjects[\"http.RequestOptions\"] = telemetry.options;\r\n dependencyTelemetry.contextObjects[\"http.ClientRequest\"] = telemetry.request;\r\n\r\n client.trackDependency(dependencyTelemetry);\r\n });\r\n }\r\n }\r\n\r\n public dispose() {\r\n AutoCollectHttpDependencies.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\nexport = AutoCollectHttpDependencies;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.d.ts b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.d.ts new file mode 100644 index 0000000..6707e7e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.d.ts @@ -0,0 +1,30 @@ +/// +import http = require("http"); +import https = require("https"); +import Contracts = require("../Declarations/Contracts"); +import RequestParser = require("./RequestParser"); +/** + * Helper class to read data from the request/response objects and convert them into the telemetry contract + */ +declare class HttpDependencyParser extends RequestParser { + private correlationId; + constructor(requestOptions: object | string | http.RequestOptions | https.RequestOptions, request: http.ClientRequest); + /** + * Called when the ClientRequest emits an error event. + */ + onError(error: Error): void; + /** + * Called when the ClientRequest emits a response event. + */ + onResponse(response: http.ClientResponse): void; + /** + * Gets a dependency data contract object for a completed ClientRequest. + */ + getDependencyTelemetry(baseTelemetry?: Contracts.Telemetry, dependencyId?: string): Contracts.DependencyTelemetry; + /** + * Builds a URL from request options, using the same logic as http.request(). This is + * necessary because a ClientRequest object does not expose a url property. + */ + private static _getUrlFromRequestOptions; +} +export = HttpDependencyParser; diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js new file mode 100644 index 0000000..36e314c --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js @@ -0,0 +1,211 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var url = require("url"); +var Contracts = require("../Declarations/Contracts"); +var Util = require("../Library/Util"); +var RequestResponseHeaders = require("../Library/RequestResponseHeaders"); +var RequestParser = require("./RequestParser"); +var CorrelationIdManager = require("../Library/CorrelationIdManager"); +/** + * Helper class to read data from the request/response objects and convert them into the telemetry contract + */ +var HttpDependencyParser = /** @class */ (function (_super) { + __extends(HttpDependencyParser, _super); + function HttpDependencyParser(requestOptions, request) { + var _this = _super.call(this) || this; + if (request && request.method && requestOptions) { + // The ClientRequest.method property isn't documented, but is always there. + _this.method = request.method; + _this.url = HttpDependencyParser._getUrlFromRequestOptions(requestOptions, request); + _this.startTime = +new Date(); + } + return _this; + } + /** + * Called when the ClientRequest emits an error event. + */ + HttpDependencyParser.prototype.onError = function (error) { + this._setStatus(undefined, error); + }; + /** + * Called when the ClientRequest emits a response event. + */ + HttpDependencyParser.prototype.onResponse = function (response) { + this._setStatus(response.statusCode, undefined); + this.correlationId = Util.getCorrelationContextTarget(response, RequestResponseHeaders.requestContextTargetKey); + }; + /** + * Gets a dependency data contract object for a completed ClientRequest. + */ + HttpDependencyParser.prototype.getDependencyTelemetry = function (baseTelemetry, dependencyId) { + var dependencyName = this.method.toUpperCase(); + var remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP; + var remoteDependencyTarget = ""; + try { + var urlObject = new url.URL(this.url); + urlObject.search = undefined; + urlObject.hash = undefined; + dependencyName += " " + urlObject.pathname; + remoteDependencyTarget = urlObject.hostname; + if (urlObject.port) { + remoteDependencyTarget += ":" + urlObject.port; + } + } + catch (ex) { // Invalid URL + // Ignore error + } + if (this.correlationId) { + remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_AI; + if (this.correlationId !== CorrelationIdManager.correlationIdPrefix) { + remoteDependencyTarget += " | " + this.correlationId; + } + } + else { + remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP; + } + var dependencyTelemetry = { + id: dependencyId, + name: dependencyName, + data: this.url, + duration: this.duration, + success: this._isSuccess(), + resultCode: this.statusCode ? this.statusCode.toString() : null, + properties: this.properties || {}, + dependencyTypeName: remoteDependencyType, + target: remoteDependencyTarget + }; + if (baseTelemetry && baseTelemetry.time) { + dependencyTelemetry.time = baseTelemetry.time; + } + else if (this.startTime) { + dependencyTelemetry.time = new Date(this.startTime); + } + // We should keep any parameters the user passed in + // Except the fields defined above in requestTelemetry, which take priority + // Except the properties field, where they're merged instead, with baseTelemetry taking priority + if (baseTelemetry) { + // Copy missing fields + for (var key in baseTelemetry) { + if (!dependencyTelemetry[key]) { + dependencyTelemetry[key] = baseTelemetry[key]; + } + } + // Merge properties + if (baseTelemetry.properties) { + for (var key in baseTelemetry.properties) { + dependencyTelemetry.properties[key] = baseTelemetry.properties[key]; + } + } + } + return dependencyTelemetry; + }; + /** + * Builds a URL from request options, using the same logic as http.request(). This is + * necessary because a ClientRequest object does not expose a url property. + */ + HttpDependencyParser._getUrlFromRequestOptions = function (options, request) { + if (typeof options === "string") { + if (options.indexOf("http://") === 0 || options.indexOf("https://") === 0) { + // protocol exists, parse normally + try { + options = new url.URL(options); + } + catch (ex) { + // Ignore error + } + } + else { + // protocol not found, insert http/https where appropriate + try { + var parsed = new url.URL("http://" + options); + if (parsed.port === "443") { + options = new url.URL("https://" + options); + } + else { + options = new url.URL("http://" + options); + } + } + catch (ex) { + // Ignore error + } + } + } + else if (options && typeof url.URL === "function" && options instanceof url.URL) { + return url.format(options); + } + else { + // Avoid modifying the original options object. + var originalOptions_1 = options; + options = {}; + if (originalOptions_1) { + Object.keys(originalOptions_1).forEach(function (key) { + options[key] = originalOptions_1[key]; + }); + } + } + // Oddly, url.format ignores path and only uses pathname and search, + // so create them from the path, if path was specified + if (options.path && options.host) { + // need to force a protocol to make parameter valid - base url is required when input is a relative url + try { + var parsedQuery = new url.URL(options.path, "http://" + options.host + options.path); + options.pathname = parsedQuery.pathname; + options.search = parsedQuery.search; + } + catch (ex) { + // Ignore error + } + } + // Sometimes the hostname is provided but not the host + // Add in the path when this occurs + if (options.path && options.hostname && !options.host) { + // need to force a protocol to make parameter valid - base url is required when input is a relative url + try { + var parsedQuery = new url.URL(options.path, "http://" + options.hostname + options.path); + options.pathname = parsedQuery.pathname; + options.search = parsedQuery.search; + } + catch (ex) { + // Ignore error + } + } + // Similarly, url.format ignores hostname and port if host is specified, + // even if host doesn't have the port, but http.request does not work + // this way. It will use the port if one is not specified in host, + // effectively treating host as hostname, but will use the port specified + // in host if it exists. + if (options.host && options.port) { + // Force a protocol so it will parse the host as the host, not path. + // It is discarded and not used, so it doesn't matter if it doesn't match + try { + var parsedHost = new url.URL("http://" + options.host); + if (!parsedHost.port && options.port) { + options.hostname = options.host; + delete options.host; + } + } + catch (ex) { + // Ignore error + } + } + // Mix in default values used by http.request and others + options.protocol = options.protocol || (request.agent && request.agent.protocol) || (request.protocol) || undefined; + options.hostname = options.hostname || "localhost"; + return url.format(options); + }; + return HttpDependencyParser; +}(RequestParser)); +module.exports = HttpDependencyParser; +//# sourceMappingURL=HttpDependencyParser.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js.map b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js.map new file mode 100644 index 0000000..8c3bd5d --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpDependencyParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HttpDependencyParser.js","sourceRoot":"","sources":["../../AutoCollection/HttpDependencyParser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAEA,yBAA4B;AAC5B,qDAAwD;AACxD,sCAAyC;AACzC,0EAA6E;AAC7E,+CAAkD;AAClD,sEAAyE;AAEzE;;GAEG;AACH;IAAmC,wCAAa;IAG5C,8BAAY,cAA4E,EAAE,OAA2B;QAArH,YACI,iBAAO,SAQV;QAPG,IAAI,OAAO,IAAU,OAAQ,CAAC,MAAM,IAAI,cAAc,EAAE;YACpD,2EAA2E;YAC3E,KAAI,CAAC,MAAM,GAAS,OAAQ,CAAC,MAAM,CAAC;YAEpC,KAAI,CAAC,GAAG,GAAG,oBAAoB,CAAC,yBAAyB,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;YACnF,KAAI,CAAC,SAAS,GAAG,CAAC,IAAI,IAAI,EAAE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BACzD,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,EAAE;oBAClC,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;oBAChC,OAAO,OAAO,CAAC,IAAI,CAAC;iBACvB;aACJ;YACD,OAAO,EAAE,EAAE;gBACP,eAAe;aAClB;SACJ;QAED,wDAAwD;QACxD,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAO,OAAQ,CAAC,KAAK,IAAU,OAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAO,OAAQ,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC;QACzI,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,WAAW,CAAC;QAEnD,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IACL,2BAAC;AAAD,CAAC,AAjMD,CAAmC,aAAa,GAiM/C;AAED,iBAAS,oBAAoB,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport url = require(\"url\");\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport Util = require(\"../Library/Util\");\r\nimport RequestResponseHeaders = require(\"../Library/RequestResponseHeaders\");\r\nimport RequestParser = require(\"./RequestParser\");\r\nimport CorrelationIdManager = require(\"../Library/CorrelationIdManager\");\r\n\r\n/**\r\n * Helper class to read data from the request/response objects and convert them into the telemetry contract\r\n */\r\nclass HttpDependencyParser extends RequestParser {\r\n private correlationId: string;\r\n\r\n constructor(requestOptions: object | string | http.RequestOptions | https.RequestOptions, request: http.ClientRequest) {\r\n super();\r\n if (request && (request).method && requestOptions) {\r\n // The ClientRequest.method property isn't documented, but is always there.\r\n this.method = (request).method;\r\n\r\n this.url = HttpDependencyParser._getUrlFromRequestOptions(requestOptions, request);\r\n this.startTime = +new Date();\r\n }\r\n }\r\n\r\n /**\r\n * Called when the ClientRequest emits an error event.\r\n */\r\n public onError(error: Error) {\r\n this._setStatus(undefined, error);\r\n }\r\n\r\n /**\r\n * Called when the ClientRequest emits a response event.\r\n */\r\n public onResponse(response: http.ClientResponse) {\r\n this._setStatus(response.statusCode, undefined);\r\n this.correlationId = Util.getCorrelationContextTarget(response, RequestResponseHeaders.requestContextTargetKey);\r\n }\r\n\r\n /**\r\n * Gets a dependency data contract object for a completed ClientRequest.\r\n */\r\n public getDependencyTelemetry(baseTelemetry?: Contracts.Telemetry, dependencyId?: string): Contracts.DependencyTelemetry {\r\n let dependencyName = this.method.toUpperCase();\r\n let remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP;\r\n let remoteDependencyTarget = \"\";\r\n try {\r\n let urlObject = new url.URL(this.url);\r\n urlObject.search = undefined;\r\n urlObject.hash = undefined;\r\n dependencyName += \" \" + urlObject.pathname;\r\n remoteDependencyTarget = urlObject.hostname;\r\n if (urlObject.port) {\r\n remoteDependencyTarget += \":\" + urlObject.port;\r\n }\r\n\r\n }\r\n catch (ex) { // Invalid URL\r\n // Ignore error\r\n }\r\n if (this.correlationId) {\r\n remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_AI;\r\n if (this.correlationId !== CorrelationIdManager.correlationIdPrefix) {\r\n remoteDependencyTarget += \" | \" + this.correlationId;\r\n }\r\n } else {\r\n remoteDependencyType = Contracts.RemoteDependencyDataConstants.TYPE_HTTP;\r\n }\r\n\r\n var dependencyTelemetry: Contracts.DependencyTelemetry & Contracts.Identified = {\r\n id: dependencyId,\r\n name: dependencyName,\r\n data: this.url,\r\n duration: this.duration,\r\n success: this._isSuccess(),\r\n resultCode: this.statusCode ? this.statusCode.toString() : null,\r\n properties: this.properties || {},\r\n dependencyTypeName: remoteDependencyType,\r\n target: remoteDependencyTarget\r\n };\r\n\r\n if (baseTelemetry && baseTelemetry.time) {\r\n dependencyTelemetry.time = baseTelemetry.time;\r\n } else if (this.startTime) {\r\n dependencyTelemetry.time = new Date(this.startTime);\r\n }\r\n\r\n // We should keep any parameters the user passed in\r\n // Except the fields defined above in requestTelemetry, which take priority\r\n // Except the properties field, where they're merged instead, with baseTelemetry taking priority\r\n if (baseTelemetry) {\r\n // Copy missing fields\r\n for (let key in baseTelemetry) {\r\n if (!(dependencyTelemetry)[key]) {\r\n (dependencyTelemetry)[key] = (baseTelemetry)[key];\r\n }\r\n }\r\n // Merge properties\r\n if (baseTelemetry.properties) {\r\n for (let key in baseTelemetry.properties) {\r\n dependencyTelemetry.properties[key] = baseTelemetry.properties[key];\r\n }\r\n }\r\n }\r\n\r\n return dependencyTelemetry;\r\n }\r\n\r\n /**\r\n * Builds a URL from request options, using the same logic as http.request(). This is\r\n * necessary because a ClientRequest object does not expose a url property.\r\n */\r\n private static _getUrlFromRequestOptions(options: any, request: http.ClientRequest) {\r\n if (typeof options === \"string\") {\r\n if (options.indexOf(\"http://\") === 0 || options.indexOf(\"https://\") === 0) {\r\n // protocol exists, parse normally\r\n try {\r\n options = new url.URL(options);\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n } else {\r\n // protocol not found, insert http/https where appropriate\r\n try {\r\n const parsed = new url.URL(\"http://\" + options);\r\n if (parsed.port === \"443\") {\r\n options = new url.URL(\"https://\" + options);\r\n } else {\r\n options = new url.URL(\"http://\" + options);\r\n }\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n }\r\n } else if (options && typeof url.URL === \"function\" && options instanceof url.URL) {\r\n return url.format(options);\r\n } else {\r\n // Avoid modifying the original options object.\r\n let originalOptions = options;\r\n options = {};\r\n if (originalOptions) {\r\n Object.keys(originalOptions).forEach(key => {\r\n options[key] = originalOptions[key];\r\n });\r\n }\r\n }\r\n\r\n // Oddly, url.format ignores path and only uses pathname and search,\r\n // so create them from the path, if path was specified\r\n if (options.path && options.host) {\r\n // need to force a protocol to make parameter valid - base url is required when input is a relative url\r\n try {\r\n const parsedQuery = new url.URL(options.path, \"http://\" + options.host + options.path);\r\n options.pathname = parsedQuery.pathname;\r\n options.search = parsedQuery.search;\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n }\r\n\r\n // Sometimes the hostname is provided but not the host\r\n // Add in the path when this occurs\r\n if (options.path && options.hostname && !options.host) {\r\n // need to force a protocol to make parameter valid - base url is required when input is a relative url\r\n try {\r\n const parsedQuery = new url.URL(options.path, \"http://\" + options.hostname + options.path);\r\n options.pathname = parsedQuery.pathname;\r\n options.search = parsedQuery.search;\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n }\r\n\r\n // Similarly, url.format ignores hostname and port if host is specified,\r\n // even if host doesn't have the port, but http.request does not work\r\n // this way. It will use the port if one is not specified in host,\r\n // effectively treating host as hostname, but will use the port specified\r\n // in host if it exists.\r\n if (options.host && options.port) {\r\n // Force a protocol so it will parse the host as the host, not path.\r\n // It is discarded and not used, so it doesn't matter if it doesn't match\r\n try {\r\n const parsedHost = new url.URL(`http://${options.host}`);\r\n if (!parsedHost.port && options.port) {\r\n options.hostname = options.host;\r\n delete options.host;\r\n }\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n }\r\n\r\n // Mix in default values used by http.request and others\r\n options.protocol = options.protocol || ((request).agent && (request).agent.protocol) || ((request).protocol) || undefined;\r\n options.hostname = options.hostname || \"localhost\";\r\n\r\n return url.format(options);\r\n }\r\n}\r\n\r\nexport = HttpDependencyParser;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.d.ts b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.d.ts new file mode 100644 index 0000000..bdd0099 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.d.ts @@ -0,0 +1,59 @@ +/// +import http = require("http"); +import Contracts = require("../Declarations/Contracts"); +import RequestParser = require("./RequestParser"); +import Tracestate = require("../Library/Tracestate"); +import Traceparent = require("../Library/Traceparent"); +import { HttpRequest } from "../Library/Functions"; +/** + * Helper class to read data from the request/response objects and convert them into the telemetry contract + */ +declare class HttpRequestParser extends RequestParser { + private static keys; + private rawHeaders; + private socketRemoteAddress; + private connectionRemoteAddress; + private legacySocketRemoteAddress; + private userAgent; + private sourceCorrelationId; + private parentId; + private operationId; + private requestId; + private traceparent; + private tracestate; + private legacyRootId; + private correlationContextHeader; + constructor(request: http.IncomingMessage | HttpRequest, requestId?: string); + onError(error: Error | string, ellapsedMilliseconds?: number): void; + onResponse(response: http.ServerResponse, ellapsedMilliseconds?: number): void; + getRequestTelemetry(baseTelemetry?: Contracts.Telemetry): Contracts.RequestTelemetry; + getRequestTags(tags: { + [key: string]: string; + }): { + [key: string]: string; + }; + getOperationId(tags: { + [key: string]: string; + }): string; + getOperationParentId(tags: { + [key: string]: string; + }): string; + getOperationName(tags: { + [key: string]: string; + }): string; + getRequestId(): string; + getCorrelationContextHeader(): string; + getTraceparent(): Traceparent; + getTracestate(): Tracestate; + getLegacyRootId(): string; + private _getAbsoluteUrl; + private _getIp; + private _getId; + /** + * Sets this operation's operationId, parentId, requestId (and legacyRootId, if necessary) based on this operation's traceparent + */ + private setBackCompatFromThisTraceContext; + private parseHeaders; + static parseId(cookieValue: string): string; +} +export = HttpRequestParser; diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js new file mode 100644 index 0000000..8716567 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js @@ -0,0 +1,292 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var url = require("url"); +var Contracts = require("../Declarations/Contracts"); +var Util = require("../Library/Util"); +var RequestResponseHeaders = require("../Library/RequestResponseHeaders"); +var RequestParser = require("./RequestParser"); +var CorrelationIdManager = require("../Library/CorrelationIdManager"); +var Tracestate = require("../Library/Tracestate"); +var Traceparent = require("../Library/Traceparent"); +/** + * Helper class to read data from the request/response objects and convert them into the telemetry contract + */ +var HttpRequestParser = /** @class */ (function (_super) { + __extends(HttpRequestParser, _super); + function HttpRequestParser(request, requestId) { + var _this = _super.call(this) || this; + if (request) { + _this.method = request.method; + _this.url = _this._getAbsoluteUrl(request); + _this.startTime = +new Date(); + _this.socketRemoteAddress = request.socket && request.socket.remoteAddress; + _this.parseHeaders(request, requestId); + if (request.connection) { + _this.connectionRemoteAddress = request.connection.remoteAddress; + _this.legacySocketRemoteAddress = request.connection["socket"] && request.connection["socket"].remoteAddress; + } + } + return _this; + } + HttpRequestParser.prototype.onError = function (error, ellapsedMilliseconds) { + this._setStatus(undefined, error); + // This parameter is only for overrides. setStatus handles this internally for the autocollected case + if (ellapsedMilliseconds) { + this.duration = ellapsedMilliseconds; + } + }; + HttpRequestParser.prototype.onResponse = function (response, ellapsedMilliseconds) { + this._setStatus(response.statusCode, undefined); + // This parameter is only for overrides. setStatus handles this internally for the autocollected case + if (ellapsedMilliseconds) { + this.duration = ellapsedMilliseconds; + } + }; + HttpRequestParser.prototype.getRequestTelemetry = function (baseTelemetry) { + var name = this.method; + try { + name += " " + new url.URL(this.url).pathname; + } + catch (ex) { // Invalid URL + // Ignore error + } + var requestTelemetry = { + id: this.requestId, + name: name, + url: this.url, + /* + See https://github.com/microsoft/ApplicationInsights-dotnet-server/blob/25d695e6a906fbe977f67be3966d25dbf1c50a79/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs#L250 + for reference + */ + source: this.sourceCorrelationId, + duration: this.duration, + resultCode: this.statusCode ? this.statusCode.toString() : null, + success: this._isSuccess(), + properties: this.properties + }; + if (baseTelemetry && baseTelemetry.time) { + requestTelemetry.time = baseTelemetry.time; + } + else if (this.startTime) { + requestTelemetry.time = new Date(this.startTime); + } + // We should keep any parameters the user passed in + // Except the fields defined above in requestTelemetry, which take priority + // Except the properties field, where they're merged instead, with baseTelemetry taking priority + if (baseTelemetry) { + // Copy missing fields + for (var key in baseTelemetry) { + if (!requestTelemetry[key]) { + requestTelemetry[key] = baseTelemetry[key]; + } + } + // Merge properties + if (baseTelemetry.properties) { + for (var key in baseTelemetry.properties) { + requestTelemetry.properties[key] = baseTelemetry.properties[key]; + } + } + } + return requestTelemetry; + }; + HttpRequestParser.prototype.getRequestTags = function (tags) { + // create a copy of the context for requests since client info will be used here + var newTags = {}; + for (var key in tags) { + newTags[key] = tags[key]; + } + // don't override tags if they are already set + newTags[HttpRequestParser.keys.locationIp] = tags[HttpRequestParser.keys.locationIp] || this._getIp(); + newTags[HttpRequestParser.keys.sessionId] = tags[HttpRequestParser.keys.sessionId] || this._getId("ai_session"); + newTags[HttpRequestParser.keys.userId] = tags[HttpRequestParser.keys.userId] || this._getId("ai_user"); + newTags[HttpRequestParser.keys.userAuthUserId] = tags[HttpRequestParser.keys.userAuthUserId] || this._getId("ai_authUser"); + newTags[HttpRequestParser.keys.operationName] = this.getOperationName(tags); + newTags[HttpRequestParser.keys.operationParentId] = this.getOperationParentId(tags); + newTags[HttpRequestParser.keys.operationId] = this.getOperationId(tags); + return newTags; + }; + HttpRequestParser.prototype.getOperationId = function (tags) { + return tags[HttpRequestParser.keys.operationId] || this.operationId; + }; + HttpRequestParser.prototype.getOperationParentId = function (tags) { + return tags[HttpRequestParser.keys.operationParentId] || this.parentId || this.getOperationId(tags); + }; + HttpRequestParser.prototype.getOperationName = function (tags) { + if (tags[HttpRequestParser.keys.operationName]) { + return tags[HttpRequestParser.keys.operationName]; + } + var pathName = ""; + try { + pathName = new url.URL(this.url).pathname; + } + catch (ex) { // Invalid URL + // Ignore error + } + var operationName = this.method; + if (pathName) { + operationName += " " + pathName; + } + return operationName; + }; + HttpRequestParser.prototype.getRequestId = function () { + return this.requestId; + }; + HttpRequestParser.prototype.getCorrelationContextHeader = function () { + return this.correlationContextHeader; + }; + HttpRequestParser.prototype.getTraceparent = function () { + return this.traceparent; + }; + HttpRequestParser.prototype.getTracestate = function () { + return this.tracestate; + }; + HttpRequestParser.prototype.getLegacyRootId = function () { + return this.legacyRootId; + }; + HttpRequestParser.prototype._getAbsoluteUrl = function (request) { + if (!request.headers) { + return request.url; + } + var encrypted = request.connection ? request.connection.encrypted : null; + var protocol = (encrypted || request.headers["x-forwarded-proto"] == "https") ? "https" : "http"; + var baseUrl = protocol + "://" + request.headers.host + "/"; + var pathName = ""; + var search = ""; + try { + var requestUrl = new url.URL(request.url, baseUrl); + pathName = requestUrl.pathname; + search = requestUrl.search; + } + catch (ex) { + // Ignore errors + } + var absoluteUrl = url.format({ + protocol: protocol, + host: request.headers.host, + pathname: pathName, + search: search + }); + return absoluteUrl; + }; + HttpRequestParser.prototype._getIp = function () { + // regex to match ipv4 without port + // Note: including the port would cause the payload to be rejected by the data collector + var ipMatch = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/; + var check = function (str) { + var results = ipMatch.exec(str); + if (results) { + return results[0]; + } + }; + var ip = check(this.rawHeaders["x-forwarded-for"]) + || check(this.rawHeaders["x-client-ip"]) + || check(this.rawHeaders["x-real-ip"]) + || check(this.connectionRemoteAddress) + || check(this.socketRemoteAddress) + || check(this.legacySocketRemoteAddress); + // node v12 returns this if the address is "localhost" + if (!ip + && this.connectionRemoteAddress + && this.connectionRemoteAddress.substr + && this.connectionRemoteAddress.substr(0, 2) === "::") { + ip = "127.0.0.1"; + } + return ip; + }; + HttpRequestParser.prototype._getId = function (name) { + var cookie = (this.rawHeaders && this.rawHeaders["cookie"] && + typeof this.rawHeaders["cookie"] === "string" && this.rawHeaders["cookie"]) || ""; + var value = HttpRequestParser.parseId(Util.getCookie(name, cookie)); + return value; + }; + /** + * Sets this operation's operationId, parentId, requestId (and legacyRootId, if necessary) based on this operation's traceparent + */ + HttpRequestParser.prototype.setBackCompatFromThisTraceContext = function () { + // Set operationId + this.operationId = this.traceparent.traceId; + if (this.traceparent.legacyRootId) { + this.legacyRootId = this.traceparent.legacyRootId; + } + // Set parentId with existing spanId + this.parentId = this.traceparent.parentId; + // Update the spanId and set the current requestId + this.traceparent.updateSpanId(); + this.requestId = this.traceparent.getBackCompatRequestId(); + }; + HttpRequestParser.prototype.parseHeaders = function (request, requestId) { + this.rawHeaders = request.headers || request.rawHeaders; + this.userAgent = request.headers && request.headers["user-agent"]; + this.sourceCorrelationId = Util.getCorrelationContextTarget(request, RequestResponseHeaders.requestContextSourceKey); + if (request.headers) { + var tracestateHeader = request.headers[RequestResponseHeaders.traceStateHeader] ? request.headers[RequestResponseHeaders.traceStateHeader].toString() : null; // w3c header + var traceparentHeader = request.headers[RequestResponseHeaders.traceparentHeader] ? request.headers[RequestResponseHeaders.traceparentHeader].toString() : null; // w3c header + var requestIdHeader = request.headers[RequestResponseHeaders.requestIdHeader] ? request.headers[RequestResponseHeaders.requestIdHeader].toString() : null; // default AI header + var legacy_parentId = request.headers[RequestResponseHeaders.parentIdHeader] ? request.headers[RequestResponseHeaders.parentIdHeader].toString() : null; // legacy AI header + var legacy_rootId = request.headers[RequestResponseHeaders.rootIdHeader] ? request.headers[RequestResponseHeaders.rootIdHeader].toString() : null; // legacy AI header + this.correlationContextHeader = request.headers[RequestResponseHeaders.correlationContextHeader] ? request.headers[RequestResponseHeaders.correlationContextHeader].toString() : null; + if (CorrelationIdManager.w3cEnabled && (traceparentHeader || tracestateHeader)) { + // Parse W3C Trace Context headers + this.traceparent = new Traceparent(traceparentHeader ? traceparentHeader.toString() : null); // new traceparent is always created from this + this.tracestate = traceparentHeader && tracestateHeader && new Tracestate(tracestateHeader ? tracestateHeader.toString() : null); // discard tracestate if no traceparent is present + this.setBackCompatFromThisTraceContext(); + } + else if (requestIdHeader) { + // Parse AI headers + if (CorrelationIdManager.w3cEnabled) { + this.traceparent = new Traceparent(null, requestIdHeader); + this.setBackCompatFromThisTraceContext(); + } + else { + this.parentId = requestIdHeader; + this.requestId = CorrelationIdManager.generateRequestId(this.parentId); + this.operationId = CorrelationIdManager.getRootId(this.requestId); + } + } + else { + // Legacy fallback + if (CorrelationIdManager.w3cEnabled) { + this.traceparent = new Traceparent(); + this.traceparent.parentId = legacy_parentId; + this.traceparent.legacyRootId = legacy_rootId || legacy_parentId; + this.setBackCompatFromThisTraceContext(); + } + else { + this.parentId = legacy_parentId; + this.requestId = CorrelationIdManager.generateRequestId(legacy_rootId || this.parentId); + this.correlationContextHeader = null; + this.operationId = CorrelationIdManager.getRootId(this.requestId); + } + } + if (requestId) { + // For the scenarios that don't guarantee an AI-created context, + // override the requestId with the provided one. + this.requestId = requestId; + this.operationId = CorrelationIdManager.getRootId(this.requestId); + } + } + }; + HttpRequestParser.parseId = function (cookieValue) { + var cookieParts = cookieValue.split("|"); + if (cookieParts.length > 0) { + return cookieParts[0]; + } + return ""; // old behavior was to return "" for incorrect parsing + }; + HttpRequestParser.keys = new Contracts.ContextTagKeys(); + return HttpRequestParser; +}(RequestParser)); +module.exports = HttpRequestParser; +//# sourceMappingURL=HttpRequestParser.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js.map b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js.map new file mode 100644 index 0000000..a74e87e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequestParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HttpRequestParser.js","sourceRoot":"","sources":["../../AutoCollection/HttpRequestParser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,yBAA4B;AAG5B,qDAAwD;AACxD,sCAAyC;AACzC,0EAA6E;AAC7E,+CAAkD;AAClD,sEAAyE;AACzE,kDAAqD;AACrD,oDAAuD;AAIvD;;GAEG;AACH;IAAgC,qCAAa;IAkBzC,2BAAY,OAA2C,EAAE,SAAkB;QAA3E,YACI,iBAAO,SAYV;QAXG,IAAI,OAAO,EAAE;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M,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAE3C,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE;YACxB,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC;SACzB;QAED,OAAO,EAAE,CAAC,CAAC,sDAAsD;IACrE,CAAC;IA3Tc,sBAAI,GAAG,IAAI,SAAS,CAAC,cAAc,EAAE,CAAC;IA4TzD,wBAAC;CAAA,AA7TD,CAAgC,aAAa,GA6T5C;AAED,iBAAS,iBAAiB,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport url = require(\"url\");\r\nimport net = require(\"net\");\r\n\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport Util = require(\"../Library/Util\");\r\nimport RequestResponseHeaders = require(\"../Library/RequestResponseHeaders\");\r\nimport RequestParser = require(\"./RequestParser\");\r\nimport CorrelationIdManager = require(\"../Library/CorrelationIdManager\");\r\nimport Tracestate = require(\"../Library/Tracestate\");\r\nimport Traceparent = require(\"../Library/Traceparent\");\r\nimport { HttpRequest } from \"../Library/Functions\";\r\n\r\n\r\n/**\r\n * Helper class to read data from the request/response objects and convert them into the telemetry contract\r\n */\r\nclass HttpRequestParser extends RequestParser {\r\n private static keys = new Contracts.ContextTagKeys();\r\n\r\n private rawHeaders: { [key: string]: string };\r\n private socketRemoteAddress: string;\r\n private connectionRemoteAddress: string;\r\n private legacySocketRemoteAddress: string;\r\n private userAgent: string;\r\n private sourceCorrelationId: string;\r\n private parentId: string;\r\n private operationId: string;\r\n private requestId: string;\r\n private traceparent: Traceparent;\r\n private tracestate: Tracestate;\r\n private legacyRootId: string; // if original operationId is not w3c compat, move it here\r\n\r\n private correlationContextHeader: string;\r\n\r\n constructor(request: http.IncomingMessage | HttpRequest, requestId?: string) {\r\n super();\r\n if (request) {\r\n this.method = request.method;\r\n this.url = this._getAbsoluteUrl(request);\r\n this.startTime = +new Date();\r\n this.socketRemoteAddress = (request).socket && (request).socket.remoteAddress;\r\n this.parseHeaders(request, requestId);\r\n if ((request).connection) {\r\n this.connectionRemoteAddress = ((request).connection as net.Socket).remoteAddress;\r\n this.legacySocketRemoteAddress = ((request).connection)[\"socket\"] && ((request).connection)[\"socket\"].remoteAddress;\r\n }\r\n }\r\n }\r\n\r\n public onError(error: Error | string, ellapsedMilliseconds?: number) {\r\n this._setStatus(undefined, error);\r\n\r\n // This parameter is only for overrides. setStatus handles this internally for the autocollected case\r\n if (ellapsedMilliseconds) {\r\n this.duration = ellapsedMilliseconds;\r\n }\r\n }\r\n\r\n public onResponse(response: http.ServerResponse, ellapsedMilliseconds?: number) {\r\n this._setStatus(response.statusCode, undefined);\r\n\r\n // This parameter is only for overrides. setStatus handles this internally for the autocollected case\r\n if (ellapsedMilliseconds) {\r\n this.duration = ellapsedMilliseconds;\r\n }\r\n }\r\n\r\n public getRequestTelemetry(baseTelemetry?: Contracts.Telemetry): Contracts.RequestTelemetry {\r\n\r\n let name = this.method;\r\n try {\r\n name += \" \" + new url.URL(this.url).pathname;\r\n }\r\n catch (ex) { // Invalid URL\r\n // Ignore error\r\n }\r\n\r\n var requestTelemetry: Contracts.RequestTelemetry & Contracts.Identified = {\r\n id: this.requestId,\r\n name: name,\r\n url: this.url,\r\n /*\r\n See https://github.com/microsoft/ApplicationInsights-dotnet-server/blob/25d695e6a906fbe977f67be3966d25dbf1c50a79/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs#L250\r\n for reference\r\n */\r\n source: this.sourceCorrelationId,\r\n duration: this.duration,\r\n resultCode: this.statusCode ? this.statusCode.toString() : null,\r\n success: this._isSuccess(),\r\n properties: this.properties\r\n };\r\n\r\n if (baseTelemetry && baseTelemetry.time) {\r\n requestTelemetry.time = baseTelemetry.time;\r\n } else if (this.startTime) {\r\n requestTelemetry.time = new Date(this.startTime);\r\n }\r\n\r\n // We should keep any parameters the user passed in\r\n // Except the fields defined above in requestTelemetry, which take priority\r\n // Except the properties field, where they're merged instead, with baseTelemetry taking priority\r\n if (baseTelemetry) {\r\n // Copy missing fields\r\n for (let key in baseTelemetry) {\r\n if (!(requestTelemetry)[key]) {\r\n (requestTelemetry)[key] = (baseTelemetry)[key];\r\n }\r\n }\r\n // Merge properties\r\n if (baseTelemetry.properties) {\r\n for (let key in baseTelemetry.properties) {\r\n requestTelemetry.properties[key] = baseTelemetry.properties[key];\r\n }\r\n }\r\n }\r\n\r\n return requestTelemetry;\r\n }\r\n\r\n public getRequestTags(tags: { [key: string]: string }): { [key: string]: string } {\r\n // create a copy of the context for requests since client info will be used here\r\n var newTags = <{ [key: string]: string }>{};\r\n for (var key in tags) {\r\n newTags[key] = tags[key];\r\n }\r\n\r\n // don't override tags if they are already set\r\n newTags[HttpRequestParser.keys.locationIp] = tags[HttpRequestParser.keys.locationIp] || this._getIp();\r\n newTags[HttpRequestParser.keys.sessionId] = tags[HttpRequestParser.keys.sessionId] || this._getId(\"ai_session\");\r\n newTags[HttpRequestParser.keys.userId] = tags[HttpRequestParser.keys.userId] || this._getId(\"ai_user\");\r\n newTags[HttpRequestParser.keys.userAuthUserId] = tags[HttpRequestParser.keys.userAuthUserId] || this._getId(\"ai_authUser\");\r\n newTags[HttpRequestParser.keys.operationName] = this.getOperationName(tags);\r\n newTags[HttpRequestParser.keys.operationParentId] = this.getOperationParentId(tags);\r\n newTags[HttpRequestParser.keys.operationId] = this.getOperationId(tags);\r\n\r\n return newTags;\r\n }\r\n\r\n public getOperationId(tags: { [key: string]: string }) {\r\n return tags[HttpRequestParser.keys.operationId] || this.operationId;\r\n }\r\n\r\n public getOperationParentId(tags: { [key: string]: string }) {\r\n return tags[HttpRequestParser.keys.operationParentId] || this.parentId || this.getOperationId(tags);\r\n }\r\n\r\n public getOperationName(tags: { [key: string]: string }) {\r\n if (tags[HttpRequestParser.keys.operationName]) {\r\n return tags[HttpRequestParser.keys.operationName];\r\n }\r\n let pathName = \"\";\r\n try {\r\n pathName = new url.URL(this.url).pathname;\r\n }\r\n catch (ex) { // Invalid URL\r\n // Ignore error\r\n }\r\n let operationName = this.method;\r\n if (pathName) {\r\n operationName += \" \" + pathName;\r\n }\r\n return operationName;\r\n }\r\n\r\n public getRequestId() {\r\n return this.requestId;\r\n }\r\n\r\n public getCorrelationContextHeader() {\r\n return this.correlationContextHeader;\r\n }\r\n\r\n public getTraceparent() {\r\n return this.traceparent;\r\n }\r\n\r\n public getTracestate() {\r\n return this.tracestate;\r\n }\r\n\r\n public getLegacyRootId() {\r\n return this.legacyRootId;\r\n }\r\n\r\n private _getAbsoluteUrl(request: http.IncomingMessage | HttpRequest): string {\r\n if (!request.headers) {\r\n return request.url;\r\n }\r\n\r\n var encrypted = (request).connection ? ((request).connection as any).encrypted : null;\r\n\r\n var protocol = (encrypted || request.headers[\"x-forwarded-proto\"] == \"https\") ? \"https\" : \"http\";\r\n\r\n var baseUrl = protocol + \"://\" + request.headers.host + \"/\";\r\n\r\n var pathName = \"\";\r\n var search = \"\";\r\n try {\r\n var requestUrl = new url.URL(request.url, baseUrl);\r\n pathName = requestUrl.pathname;\r\n search = requestUrl.search;\r\n }\r\n catch (ex) {\r\n // Ignore errors\r\n }\r\n var absoluteUrl = url.format({\r\n protocol: protocol,\r\n host: request.headers.host,\r\n pathname: pathName,\r\n search: search\r\n });\r\n return absoluteUrl;\r\n }\r\n\r\n private _getIp() {\r\n\r\n // regex to match ipv4 without port\r\n // Note: including the port would cause the payload to be rejected by the data collector\r\n var ipMatch = /[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}/;\r\n\r\n var check = (str: string): string => {\r\n var results = ipMatch.exec(str);\r\n if (results) {\r\n return results[0];\r\n }\r\n };\r\n\r\n var ip = check(this.rawHeaders[\"x-forwarded-for\"])\r\n || check(this.rawHeaders[\"x-client-ip\"])\r\n || check(this.rawHeaders[\"x-real-ip\"])\r\n || check(this.connectionRemoteAddress)\r\n || check(this.socketRemoteAddress)\r\n || check(this.legacySocketRemoteAddress);\r\n\r\n // node v12 returns this if the address is \"localhost\"\r\n if (!ip\r\n && this.connectionRemoteAddress\r\n && this.connectionRemoteAddress.substr\r\n && this.connectionRemoteAddress.substr(0, 2) === \"::\") {\r\n ip = \"127.0.0.1\";\r\n }\r\n\r\n return ip;\r\n }\r\n\r\n private _getId(name: string) {\r\n var cookie = (this.rawHeaders && this.rawHeaders[\"cookie\"] &&\r\n typeof this.rawHeaders[\"cookie\"] === \"string\" && this.rawHeaders[\"cookie\"]) || \"\";\r\n var value = HttpRequestParser.parseId(Util.getCookie(name, cookie));\r\n return value;\r\n }\r\n\r\n /**\r\n * Sets this operation's operationId, parentId, requestId (and legacyRootId, if necessary) based on this operation's traceparent\r\n */\r\n private setBackCompatFromThisTraceContext() {\r\n // Set operationId\r\n this.operationId = this.traceparent.traceId;\r\n if (this.traceparent.legacyRootId) {\r\n this.legacyRootId = this.traceparent.legacyRootId;\r\n }\r\n\r\n // Set parentId with existing spanId\r\n this.parentId = this.traceparent.parentId;\r\n\r\n // Update the spanId and set the current requestId\r\n this.traceparent.updateSpanId();\r\n this.requestId = this.traceparent.getBackCompatRequestId();\r\n }\r\n\r\n private parseHeaders(request: http.IncomingMessage | HttpRequest, requestId?: string) {\r\n\r\n this.rawHeaders = request.headers || (request).rawHeaders;\r\n this.userAgent = request.headers && request.headers[\"user-agent\"];\r\n this.sourceCorrelationId = Util.getCorrelationContextTarget(request, RequestResponseHeaders.requestContextSourceKey);\r\n\r\n if (request.headers) {\r\n const tracestateHeader = request.headers[RequestResponseHeaders.traceStateHeader] ? request.headers[RequestResponseHeaders.traceStateHeader].toString() : null; // w3c header\r\n const traceparentHeader = request.headers[RequestResponseHeaders.traceparentHeader] ? request.headers[RequestResponseHeaders.traceparentHeader].toString() : null; // w3c header\r\n const requestIdHeader = request.headers[RequestResponseHeaders.requestIdHeader] ? request.headers[RequestResponseHeaders.requestIdHeader].toString() : null; // default AI header\r\n const legacy_parentId = request.headers[RequestResponseHeaders.parentIdHeader] ? request.headers[RequestResponseHeaders.parentIdHeader].toString() : null; // legacy AI header\r\n const legacy_rootId = request.headers[RequestResponseHeaders.rootIdHeader] ? request.headers[RequestResponseHeaders.rootIdHeader].toString() : null; // legacy AI header\r\n\r\n this.correlationContextHeader = request.headers[RequestResponseHeaders.correlationContextHeader] ? request.headers[RequestResponseHeaders.correlationContextHeader].toString() : null;\r\n\r\n if (CorrelationIdManager.w3cEnabled && (traceparentHeader || tracestateHeader)) {\r\n // Parse W3C Trace Context headers\r\n this.traceparent = new Traceparent(traceparentHeader ? traceparentHeader.toString() : null); // new traceparent is always created from this\r\n this.tracestate = traceparentHeader && tracestateHeader && new Tracestate(tracestateHeader ? tracestateHeader.toString() : null); // discard tracestate if no traceparent is present\r\n this.setBackCompatFromThisTraceContext();\r\n } else if (requestIdHeader) {\r\n // Parse AI headers\r\n if (CorrelationIdManager.w3cEnabled) {\r\n this.traceparent = new Traceparent(null, requestIdHeader);\r\n this.setBackCompatFromThisTraceContext();\r\n } else {\r\n this.parentId = requestIdHeader;\r\n this.requestId = CorrelationIdManager.generateRequestId(this.parentId);\r\n this.operationId = CorrelationIdManager.getRootId(this.requestId);\r\n }\r\n } else {\r\n // Legacy fallback\r\n if (CorrelationIdManager.w3cEnabled) {\r\n this.traceparent = new Traceparent();\r\n this.traceparent.parentId = legacy_parentId;\r\n this.traceparent.legacyRootId = legacy_rootId || legacy_parentId;\r\n this.setBackCompatFromThisTraceContext();\r\n } else {\r\n this.parentId = legacy_parentId;\r\n this.requestId = CorrelationIdManager.generateRequestId(legacy_rootId || this.parentId);\r\n this.correlationContextHeader = null;\r\n this.operationId = CorrelationIdManager.getRootId(this.requestId);\r\n }\r\n }\r\n\r\n if (requestId) {\r\n // For the scenarios that don't guarantee an AI-created context,\r\n // override the requestId with the provided one.\r\n this.requestId = requestId;\r\n this.operationId = CorrelationIdManager.getRootId(this.requestId);\r\n }\r\n }\r\n }\r\n\r\n public static parseId(cookieValue: string): string {\r\n const cookieParts = cookieValue.split(\"|\");\r\n\r\n if (cookieParts.length > 0) {\r\n return cookieParts[0];\r\n }\r\n\r\n return \"\"; // old behavior was to return \"\" for incorrect parsing\r\n }\r\n}\r\n\r\nexport = HttpRequestParser;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequests.d.ts b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.d.ts new file mode 100644 index 0000000..d642d01 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.d.ts @@ -0,0 +1,35 @@ +import Contracts = require("../Declarations/Contracts"); +import TelemetryClient = require("../Library/TelemetryClient"); +import HttpRequestParser = require("./HttpRequestParser"); +declare class AutoCollectHttpRequests { + static INSTANCE: AutoCollectHttpRequests; + private static HANDLER_READY; + private static alreadyAutoCollectedFlag; + private _client; + private _isEnabled; + private _isInitialized; + private _isAutoCorrelating; + constructor(client: TelemetryClient); + enable(isEnabled: boolean): void; + useAutoCorrelation(isEnabled: boolean, forceClsHooked?: boolean): void; + isInitialized(): boolean; + isAutoCorrelating(): boolean; + private _generateCorrelationContext; + private _registerRequest; + private _initialize; + /** + * Tracks a request synchronously (doesn't wait for response 'finish' event) + */ + static trackRequestSync(client: TelemetryClient, telemetry: Contracts.NodeHttpRequestTelemetry): void; + /** + * Tracks a request by listening to the response 'finish' event + */ + static trackRequest(client: TelemetryClient, telemetry: Contracts.NodeHttpRequestTelemetry, _requestParser?: HttpRequestParser): void; + /** + * Add the target correlationId to the response headers, if not already provided. + */ + private static addResponseCorrelationIdHeader; + private static endRequest; + dispose(): void; +} +export = AutoCollectHttpRequests; diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js new file mode 100644 index 0000000..aad3ff2 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js @@ -0,0 +1,262 @@ +"use strict"; +var http = require("http"); +var https = require("https"); +var Logging = require("../Library/Logging"); +var Util = require("../Library/Util"); +var RequestResponseHeaders = require("../Library/RequestResponseHeaders"); +var HttpRequestParser = require("./HttpRequestParser"); +var CorrelationContextManager_1 = require("./CorrelationContextManager"); +var AutoCollectPerformance = require("./Performance"); +var AutoCollectHttpRequests = /** @class */ (function () { + function AutoCollectHttpRequests(client) { + if (!!AutoCollectHttpRequests.INSTANCE) { + throw new Error("Server request tracking should be configured from the applicationInsights object"); + } + AutoCollectHttpRequests.INSTANCE = this; + this._client = client; + } + AutoCollectHttpRequests.prototype.enable = function (isEnabled) { + this._isEnabled = isEnabled; + // Autocorrelation requires automatic monitoring of incoming server requests + // Disabling autocollection but enabling autocorrelation will still enable + // request monitoring but will not produce request events + if ((this._isAutoCorrelating || this._isEnabled || AutoCollectPerformance.isEnabled()) && !this._isInitialized) { + this.useAutoCorrelation(this._isAutoCorrelating); + this._initialize(); + } + }; + AutoCollectHttpRequests.prototype.useAutoCorrelation = function (isEnabled, forceClsHooked) { + if (isEnabled && !this._isAutoCorrelating) { + CorrelationContextManager_1.CorrelationContextManager.enable(forceClsHooked); + } + else if (!isEnabled && this._isAutoCorrelating) { + CorrelationContextManager_1.CorrelationContextManager.disable(); + } + this._isAutoCorrelating = isEnabled; + }; + AutoCollectHttpRequests.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectHttpRequests.prototype.isAutoCorrelating = function () { + return this._isAutoCorrelating; + }; + AutoCollectHttpRequests.prototype._generateCorrelationContext = function (requestParser) { + if (!this._isAutoCorrelating) { + return; + } + return CorrelationContextManager_1.CorrelationContextManager.generateContextObject(requestParser.getOperationId(this._client.context.tags), requestParser.getRequestId(), requestParser.getOperationName(this._client.context.tags), requestParser.getCorrelationContextHeader(), requestParser.getTraceparent(), requestParser.getTracestate()); + }; + AutoCollectHttpRequests.prototype._registerRequest = function (request, response, onRequest) { + var _this = this; + // Set up correlation context + var requestParser = new HttpRequestParser(request); + var correlationContext = this._generateCorrelationContext(requestParser); + // Note: Check for if correlation is enabled happens within this method. + // If not enabled, function will directly call the callback. + CorrelationContextManager_1.CorrelationContextManager.runWithContext(correlationContext, function () { + if (_this._isEnabled) { + // Mark as auto collected + request[AutoCollectHttpRequests.alreadyAutoCollectedFlag] = true; + // Auto collect request + AutoCollectHttpRequests.trackRequest(_this._client, { request: request, response: response }, requestParser); + } + if (typeof onRequest === "function") { + onRequest(request, response); + } + }); + }; + AutoCollectHttpRequests.prototype._initialize = function () { + this._isInitialized = true; + // Avoid the creation of multiple handler on http(s).createServer + if (AutoCollectHttpRequests.HANDLER_READY) { + return; + } + AutoCollectHttpRequests.HANDLER_READY = true; + var wrapOnRequestHandler = function (onRequest) { + if (!onRequest) { + return undefined; + } + if (typeof onRequest !== "function") { + throw new Error("onRequest handler must be a function"); + } + return function (request, response) { + var _a; + CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(request); + CorrelationContextManager_1.CorrelationContextManager.wrapEmitter(response); + var shouldCollect = request && !request[AutoCollectHttpRequests.alreadyAutoCollectedFlag]; + if (request && shouldCollect) { + (_a = AutoCollectHttpRequests.INSTANCE) === null || _a === void 0 ? void 0 : _a._registerRequest(request, response, onRequest); + } + else { + if (typeof onRequest === "function") { + onRequest(request, response); + } + } + }; + }; + // The `http.createServer` function will instantiate a new http.Server object. + // Inside the Server's constructor, it is using addListener to register the + // onRequest handler. So there are two ways to inject the wrapped onRequest handler: + // 1) Overwrite Server.prototype.addListener (and .on()) globally and not patching + // the http.createServer call. Or + // 2) Overwrite the http.createServer method and add a patched addListener to the + // fresh server instance. This seems more stable for possible future changes as + // it also covers the case where the Server might not use addListener to manage + // the callback internally. + // And also as long as the constructor uses addListener to add the handle, it is + // ok to patch the addListener after construction only. Because if we would patch + // the prototype one and the createServer method, we would wrap the handler twice + // in case of the constructor call. + var wrapServerEventHandler = function (server) { + var originalAddListener = server.addListener.bind(server); + server.addListener = function (eventType, eventHandler) { + switch (eventType) { + case "request": + case "checkContinue": + return originalAddListener(eventType, wrapOnRequestHandler(eventHandler)); + default: + return originalAddListener(eventType, eventHandler); + } + }; + // on is an alias to addListener only + server.on = server.addListener; + }; + var originalHttpServer = http.createServer; + // options parameter was added in Node.js v9.6.0, v8.12.0 + // function createServer(requestListener?: RequestListener): Server; + // function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + http.createServer = function (param1, param2) { + // todo: get a pointer to the server so the IP address can be read from server.address + if (param2 && typeof param2 === "function") { + var server = originalHttpServer(param1, wrapOnRequestHandler(param2)); + wrapServerEventHandler(server); + return server; + } + else { + var server = originalHttpServer(wrapOnRequestHandler(param1)); + wrapServerEventHandler(server); + return server; + } + }; + var originalHttpsServer = https.createServer; + https.createServer = function (options, onRequest) { + var server = originalHttpsServer(options, wrapOnRequestHandler(onRequest)); + wrapServerEventHandler(server); + return server; + }; + }; + /** + * Tracks a request synchronously (doesn't wait for response 'finish' event) + */ + AutoCollectHttpRequests.trackRequestSync = function (client, telemetry) { + if (!telemetry.request || !telemetry.response || !client) { + Logging.info("AutoCollectHttpRequests.trackRequestSync was called with invalid parameters: ", !telemetry.request, !telemetry.response, !client); + return; + } + telemetry.isProcessed = false; + AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response); + // store data about the request + var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + var requestParser = new HttpRequestParser(telemetry.request, (correlationContext && correlationContext.operation.parentId)); + // Overwrite correlation context with request parser results + if (correlationContext) { + correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id; + correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name; + correlationContext.operation.parentId = requestParser.getRequestId() || correlationContext.operation.parentId; + correlationContext.customProperties.addHeaderData(requestParser.getCorrelationContextHeader()); + } + AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, telemetry.duration, telemetry.error); + }; + /** + * Tracks a request by listening to the response 'finish' event + */ + AutoCollectHttpRequests.trackRequest = function (client, telemetry, _requestParser) { + if (!telemetry.request || !telemetry.response || !client) { + Logging.info("AutoCollectHttpRequests.trackRequest was called with invalid parameters: ", !telemetry.request, !telemetry.response, !client); + return; + } + telemetry.isProcessed = false; + // store data about the request + var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + var requestParser = _requestParser || new HttpRequestParser(telemetry.request, correlationContext && correlationContext.operation.parentId); + if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl())) { + AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response); + } + // Overwrite correlation context with request parser results (if not an automatic track. we've already precalculated the correlation context in that case) + if (correlationContext && !_requestParser) { + correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id; + correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name; + correlationContext.operation.parentId = requestParser.getOperationParentId(client.context.tags) || correlationContext.operation.parentId; + correlationContext.customProperties.addHeaderData(requestParser.getCorrelationContextHeader()); + } + // response listeners + if (telemetry.response.once) { + telemetry.response.once("finish", function () { + AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, null); + }); + } + // track a failed request if an error is emitted + if (telemetry.request.on) { + telemetry.request.on("error", function (error) { + AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, error); + }); + } + // track an aborted request if an aborted event is emitted + // Newer versions of Node.js runtime will trigger error event as well, we need to ensure telemetry is not generated multiple times + if (telemetry.request.on) { + telemetry.request.on("aborted", function () { + var errorMessage = "The request has been aborted and the network socket has closed."; + AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, errorMessage); + }); + } + }; + /** + * Add the target correlationId to the response headers, if not already provided. + */ + AutoCollectHttpRequests.addResponseCorrelationIdHeader = function (client, response) { + if (client.config && client.config.correlationId && + response.getHeader && response.setHeader && !response.headersSent) { + var correlationHeader = response.getHeader(RequestResponseHeaders.requestContextHeader); + Util.safeIncludeCorrelationHeader(client, response, correlationHeader); + } + }; + AutoCollectHttpRequests.endRequest = function (client, requestParser, telemetry, ellapsedMilliseconds, error) { + if (telemetry.isProcessed) { + return; + } + telemetry.isProcessed = true; + if (error) { + requestParser.onError(error, ellapsedMilliseconds); + } + else { + requestParser.onResponse(telemetry.response, ellapsedMilliseconds); + } + var requestTelemetry = requestParser.getRequestTelemetry(telemetry); + requestTelemetry.tagOverrides = requestParser.getRequestTags(client.context.tags); + if (telemetry.tagOverrides) { + for (var key in telemetry.tagOverrides) { + requestTelemetry.tagOverrides[key] = telemetry.tagOverrides[key]; + } + } + var legacyRootId = requestParser.getLegacyRootId(); + if (legacyRootId) { + requestTelemetry.properties["ai_legacyRootId"] = legacyRootId; + } + requestTelemetry.contextObjects = requestTelemetry.contextObjects || {}; + requestTelemetry.contextObjects["http.ServerRequest"] = telemetry.request; + requestTelemetry.contextObjects["http.ServerResponse"] = telemetry.response; + client.trackRequest(requestTelemetry); + }; + AutoCollectHttpRequests.prototype.dispose = function () { + AutoCollectHttpRequests.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + CorrelationContextManager_1.CorrelationContextManager.disable(); + this._isAutoCorrelating = false; + }; + AutoCollectHttpRequests.HANDLER_READY = false; + AutoCollectHttpRequests.alreadyAutoCollectedFlag = "_appInsightsAutoCollected"; + return AutoCollectHttpRequests; +}()); +module.exports = AutoCollectHttpRequests; +//# sourceMappingURL=HttpRequests.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js.map b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js.map new file mode 100644 index 0000000..14d8662 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/HttpRequests.js.map @@ -0,0 +1 @@ +{"version":3,"file":"HttpRequests.js","sourceRoot":"","sources":["../../AutoCollection/HttpRequests.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,6BAAgC;AAIhC,4CAA+C;AAC/C,sCAAyC;AACzC,0EAA6E;AAC7E,uDAA0D;AAC1D,yEAAqH;AACrH,sDAAyD;AAEzD;IAYI,iCAAY,MAAuB;QAC/B,IAAI,CAAC,CAAC,uBAAuB,CAAC,QAAQ,EAAE;YACpC,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAC;SACvG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AAC;IAvSc,qCAAa,GAAY,KAAK,CAAC;IAE/B,gDAAwB,GAAG,2BAA2B,CAAC;IAsS1E,8BAAC;CAAA,AA3SD,IA2SC;AAED,iBAAS,uBAAuB,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\n\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Logging = require(\"../Library/Logging\");\r\nimport Util = require(\"../Library/Util\");\r\nimport RequestResponseHeaders = require(\"../Library/RequestResponseHeaders\");\r\nimport HttpRequestParser = require(\"./HttpRequestParser\");\r\nimport { CorrelationContextManager, CorrelationContext, PrivateCustomProperties } from \"./CorrelationContextManager\";\r\nimport AutoCollectPerformance = require(\"./Performance\");\r\n\r\nclass AutoCollectHttpRequests {\r\n\r\n public static INSTANCE: AutoCollectHttpRequests;\r\n private static HANDLER_READY: boolean = false;\r\n\r\n private static alreadyAutoCollectedFlag = \"_appInsightsAutoCollected\";\r\n\r\n private _client: TelemetryClient;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _isAutoCorrelating: boolean;\r\n\r\n constructor(client: TelemetryClient) {\r\n if (!!AutoCollectHttpRequests.INSTANCE) {\r\n throw new Error(\"Server request tracking should be configured from the applicationInsights object\");\r\n }\r\n\r\n AutoCollectHttpRequests.INSTANCE = this;\r\n this._client = client;\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n this._isEnabled = isEnabled;\r\n\r\n // Autocorrelation requires automatic monitoring of incoming server requests\r\n // Disabling autocollection but enabling autocorrelation will still enable\r\n // request monitoring but will not produce request events\r\n if ((this._isAutoCorrelating || this._isEnabled || AutoCollectPerformance.isEnabled()) && !this._isInitialized) {\r\n this.useAutoCorrelation(this._isAutoCorrelating);\r\n this._initialize();\r\n }\r\n }\r\n\r\n public useAutoCorrelation(isEnabled: boolean, forceClsHooked?: boolean) {\r\n if (isEnabled && !this._isAutoCorrelating) {\r\n CorrelationContextManager.enable(forceClsHooked);\r\n } else if (!isEnabled && this._isAutoCorrelating) {\r\n CorrelationContextManager.disable();\r\n }\r\n this._isAutoCorrelating = isEnabled;\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public isAutoCorrelating() {\r\n return this._isAutoCorrelating;\r\n }\r\n\r\n private _generateCorrelationContext(requestParser: HttpRequestParser): CorrelationContext {\r\n if (!this._isAutoCorrelating) {\r\n return;\r\n }\r\n\r\n return CorrelationContextManager.generateContextObject(\r\n requestParser.getOperationId(this._client.context.tags),\r\n requestParser.getRequestId(),\r\n requestParser.getOperationName(this._client.context.tags),\r\n requestParser.getCorrelationContextHeader(),\r\n requestParser.getTraceparent(),\r\n requestParser.getTracestate()\r\n );\r\n }\r\n\r\n private _registerRequest(request: http.ServerRequest, response: http.ServerResponse, onRequest: Function) {\r\n // Set up correlation context\r\n const requestParser = new HttpRequestParser(request);\r\n const correlationContext = this._generateCorrelationContext(requestParser);\r\n\r\n // Note: Check for if correlation is enabled happens within this method.\r\n // If not enabled, function will directly call the callback.\r\n CorrelationContextManager.runWithContext(correlationContext, () => {\r\n if (this._isEnabled) {\r\n // Mark as auto collected\r\n (request)[AutoCollectHttpRequests.alreadyAutoCollectedFlag] = true;\r\n\r\n // Auto collect request\r\n AutoCollectHttpRequests.trackRequest(this._client, { request: request, response: response }, requestParser);\r\n }\r\n\r\n if (typeof onRequest === \"function\") {\r\n onRequest(request, response);\r\n }\r\n });\r\n }\r\n\r\n private _initialize() {\r\n this._isInitialized = true;\r\n\r\n // Avoid the creation of multiple handler on http(s).createServer\r\n if (AutoCollectHttpRequests.HANDLER_READY) {\r\n return;\r\n }\r\n\r\n AutoCollectHttpRequests.HANDLER_READY = true;\r\n\r\n const wrapOnRequestHandler: Function = (onRequest?: Function) => {\r\n if (!onRequest) {\r\n return undefined;\r\n }\r\n if (typeof onRequest !== \"function\") {\r\n throw new Error(\"onRequest handler must be a function\");\r\n }\r\n return (request: http.ServerRequest, response: http.ServerResponse) => {\r\n CorrelationContextManager.wrapEmitter(request);\r\n CorrelationContextManager.wrapEmitter(response);\r\n const shouldCollect: boolean = request && !(request)[AutoCollectHttpRequests.alreadyAutoCollectedFlag];\r\n\r\n if (request && shouldCollect) {\r\n AutoCollectHttpRequests.INSTANCE?._registerRequest(request, response, onRequest)\r\n } else {\r\n if (typeof onRequest === \"function\") {\r\n onRequest(request, response);\r\n }\r\n }\r\n }\r\n };\r\n\r\n // The `http.createServer` function will instantiate a new http.Server object.\r\n // Inside the Server's constructor, it is using addListener to register the\r\n // onRequest handler. So there are two ways to inject the wrapped onRequest handler:\r\n // 1) Overwrite Server.prototype.addListener (and .on()) globally and not patching\r\n // the http.createServer call. Or\r\n // 2) Overwrite the http.createServer method and add a patched addListener to the\r\n // fresh server instance. This seems more stable for possible future changes as\r\n // it also covers the case where the Server might not use addListener to manage\r\n // the callback internally.\r\n // And also as long as the constructor uses addListener to add the handle, it is\r\n // ok to patch the addListener after construction only. Because if we would patch\r\n // the prototype one and the createServer method, we would wrap the handler twice\r\n // in case of the constructor call.\r\n const wrapServerEventHandler: Function = (server: (http.Server | https.Server)) => {\r\n const originalAddListener = server.addListener.bind(server);\r\n server.addListener = (eventType: string, eventHandler: Function) => {\r\n switch (eventType) {\r\n case \"request\":\r\n case \"checkContinue\":\r\n return originalAddListener(eventType, wrapOnRequestHandler(eventHandler));\r\n default:\r\n return originalAddListener(eventType, eventHandler);\r\n }\r\n };\r\n // on is an alias to addListener only\r\n server.on = server.addListener;\r\n };\r\n\r\n const originalHttpServer: any = http.createServer;\r\n\r\n // options parameter was added in Node.js v9.6.0, v8.12.0\r\n // function createServer(requestListener?: RequestListener): Server;\r\n // function createServer(options: ServerOptions, requestListener?: RequestListener): Server;\r\n http.createServer = (param1?: Object, param2?: Function) => {\r\n // todo: get a pointer to the server so the IP address can be read from server.address\r\n if (param2 && typeof param2 === \"function\") {\r\n const server: http.Server = originalHttpServer(param1, wrapOnRequestHandler(param2));\r\n wrapServerEventHandler(server);\r\n return server;\r\n }\r\n else {\r\n const server: http.Server = originalHttpServer(wrapOnRequestHandler(param1));\r\n wrapServerEventHandler(server);\r\n return server;\r\n }\r\n };\r\n\r\n const originalHttpsServer = https.createServer;\r\n https.createServer = (options: https.ServerOptions, onRequest?: Function) => {\r\n const server: https.Server = originalHttpsServer(options, wrapOnRequestHandler(onRequest));\r\n wrapServerEventHandler(server);\r\n return server;\r\n };\r\n }\r\n\r\n /**\r\n * Tracks a request synchronously (doesn't wait for response 'finish' event)\r\n */\r\n public static trackRequestSync(client: TelemetryClient, telemetry: Contracts.NodeHttpRequestTelemetry) {\r\n if (!telemetry.request || !telemetry.response || !client) {\r\n Logging.info(\"AutoCollectHttpRequests.trackRequestSync was called with invalid parameters: \", !telemetry.request, !telemetry.response, !client);\r\n return;\r\n }\r\n telemetry.isProcessed = false;\r\n AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response);\r\n\r\n // store data about the request\r\n var correlationContext = CorrelationContextManager.getCurrentContext();\r\n var requestParser = new HttpRequestParser(telemetry.request, (correlationContext && correlationContext.operation.parentId));\r\n\r\n // Overwrite correlation context with request parser results\r\n if (correlationContext) {\r\n correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id;\r\n correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name;\r\n correlationContext.operation.parentId = requestParser.getRequestId() || correlationContext.operation.parentId;\r\n (correlationContext.customProperties).addHeaderData(requestParser.getCorrelationContextHeader());\r\n }\r\n\r\n AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, telemetry.duration, telemetry.error);\r\n }\r\n\r\n /**\r\n * Tracks a request by listening to the response 'finish' event\r\n */\r\n public static trackRequest(client: TelemetryClient, telemetry: Contracts.NodeHttpRequestTelemetry, _requestParser?: HttpRequestParser) {\r\n if (!telemetry.request || !telemetry.response || !client) {\r\n Logging.info(\"AutoCollectHttpRequests.trackRequest was called with invalid parameters: \", !telemetry.request, !telemetry.response, !client);\r\n return;\r\n }\r\n telemetry.isProcessed = false;\r\n // store data about the request\r\n var correlationContext = CorrelationContextManager.getCurrentContext();\r\n var requestParser = _requestParser || new HttpRequestParser(telemetry.request, correlationContext && correlationContext.operation.parentId);\r\n\r\n if (Util.canIncludeCorrelationHeader(client, requestParser.getUrl())) {\r\n AutoCollectHttpRequests.addResponseCorrelationIdHeader(client, telemetry.response);\r\n }\r\n\r\n // Overwrite correlation context with request parser results (if not an automatic track. we've already precalculated the correlation context in that case)\r\n if (correlationContext && !_requestParser) {\r\n correlationContext.operation.id = requestParser.getOperationId(client.context.tags) || correlationContext.operation.id;\r\n correlationContext.operation.name = requestParser.getOperationName(client.context.tags) || correlationContext.operation.name;\r\n correlationContext.operation.parentId = requestParser.getOperationParentId(client.context.tags) || correlationContext.operation.parentId;\r\n (correlationContext.customProperties).addHeaderData(requestParser.getCorrelationContextHeader());\r\n }\r\n\r\n // response listeners\r\n if (telemetry.response.once) {\r\n telemetry.response.once(\"finish\", () => {\r\n AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, null);\r\n });\r\n }\r\n\r\n // track a failed request if an error is emitted\r\n if (telemetry.request.on) {\r\n telemetry.request.on(\"error\", (error: any) => {\r\n AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, error);\r\n });\r\n }\r\n\r\n // track an aborted request if an aborted event is emitted\r\n // Newer versions of Node.js runtime will trigger error event as well, we need to ensure telemetry is not generated multiple times\r\n if (telemetry.request.on) {\r\n telemetry.request.on(\"aborted\", () => {\r\n const errorMessage = \"The request has been aborted and the network socket has closed.\";\r\n AutoCollectHttpRequests.endRequest(client, requestParser, telemetry, null, errorMessage);\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Add the target correlationId to the response headers, if not already provided.\r\n */\r\n private static addResponseCorrelationIdHeader(client: TelemetryClient, response: http.ServerResponse) {\r\n if (client.config && client.config.correlationId &&\r\n response.getHeader && response.setHeader && !(response).headersSent) {\r\n const correlationHeader = response.getHeader(RequestResponseHeaders.requestContextHeader);\r\n Util.safeIncludeCorrelationHeader(client, response, correlationHeader);\r\n }\r\n }\r\n\r\n private static endRequest(client: TelemetryClient, requestParser: HttpRequestParser, telemetry: Contracts.NodeHttpRequestTelemetry, ellapsedMilliseconds?: number, error?: any) {\r\n if (telemetry.isProcessed) {\r\n return;\r\n }\r\n telemetry.isProcessed = true;\r\n if (error) {\r\n requestParser.onError(error, ellapsedMilliseconds);\r\n } else {\r\n requestParser.onResponse(telemetry.response, ellapsedMilliseconds);\r\n }\r\n\r\n var requestTelemetry = requestParser.getRequestTelemetry(telemetry);\r\n\r\n requestTelemetry.tagOverrides = requestParser.getRequestTags(client.context.tags);\r\n if (telemetry.tagOverrides) {\r\n for (let key in telemetry.tagOverrides) {\r\n requestTelemetry.tagOverrides[key] = telemetry.tagOverrides[key];\r\n }\r\n }\r\n\r\n const legacyRootId = requestParser.getLegacyRootId();\r\n if (legacyRootId) {\r\n requestTelemetry.properties[\"ai_legacyRootId\"] = legacyRootId;\r\n }\r\n\r\n requestTelemetry.contextObjects = requestTelemetry.contextObjects || {};\r\n requestTelemetry.contextObjects[\"http.ServerRequest\"] = telemetry.request;\r\n requestTelemetry.contextObjects[\"http.ServerResponse\"] = telemetry.response;\r\n\r\n client.trackRequest(requestTelemetry);\r\n }\r\n\r\n public dispose() {\r\n AutoCollectHttpRequests.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n CorrelationContextManager.disable();\r\n this._isAutoCorrelating = false;\r\n }\r\n}\r\n\r\nexport = AutoCollectHttpRequests;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/NativePerformance.d.ts b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.d.ts new file mode 100644 index 0000000..a14117e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.d.ts @@ -0,0 +1,83 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +import { IBaseConfig } from "../Declarations/Interfaces"; +/** + * Interface which defines which specific extended metrics should be disabled + * + * @export + * @interface IDisabledExtendedMetrics + */ +export interface IDisabledExtendedMetrics { + gc?: boolean; + heap?: boolean; + loop?: boolean; +} +export declare class AutoCollectNativePerformance { + static INSTANCE: AutoCollectNativePerformance; + private static _emitter; + private static _metricsAvailable; + private _isEnabled; + private _isInitialized; + private _handle; + private _client; + private _disabledMetrics; + constructor(client: TelemetryClient); + /** + * Start instance of native metrics agent. + * + * @param {boolean} isEnabled + * @param {number} [collectionInterval=60000] + * @memberof AutoCollectNativePerformance + */ + enable(isEnabled: boolean, disabledMetrics?: IDisabledExtendedMetrics, collectionInterval?: number): void; + /** + * Cleanup this instance of AutoCollectNativePerformance + * + * @memberof AutoCollectNativePerformance + */ + dispose(): void; + /** + * Parse environment variable and overwrite isEnabled based on respective fields being set + * + * @private + * @static + * @param {(boolean | IDisabledExtendedMetrics)} collectExtendedMetrics + * @param {(IBaseConfig)} customConfig + * @returns {(boolean | IDisabledExtendedMetrics)} + * @memberof AutoCollectNativePerformance + */ + static parseEnabled(collectExtendedMetrics: boolean | IDisabledExtendedMetrics, customConfig: IBaseConfig): { + isEnabled: boolean; + disabledMetrics: IDisabledExtendedMetrics; + }; + /** + * Trigger an iteration of native metrics collection + * + * @private + * @memberof AutoCollectNativePerformance + */ + private _trackNativeMetrics; + /** + * Tracks garbage collection stats for this interval. One custom metric is sent per type of garbage + * collection that occurred during this collection interval. + * + * @private + * @memberof AutoCollectNativePerformance + */ + private _trackGarbageCollection; + /** + * Tracks event loop ticks per interval as a custom metric. Also included in the metric is min/max/avg + * time spent in event loop for this interval. + * + * @private + * @returns {void} + * @memberof AutoCollectNativePerformance + */ + private _trackEventLoop; + /** + * Track heap memory usage metrics as a custom metric. + * + * @private + * @memberof AutoCollectNativePerformance + */ + private _trackHeapUsage; +} diff --git a/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js new file mode 100644 index 0000000..4888cbe --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js @@ -0,0 +1,247 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoCollectNativePerformance = void 0; +var Context = require("../Library/Context"); +var Logging = require("../Library/Logging"); +var AutoCollectNativePerformance = /** @class */ (function () { + function AutoCollectNativePerformance(client) { + this._disabledMetrics = {}; + // Note: Only 1 instance of this can exist. So when we reconstruct this object, + // just disable old native instance and reset JS member variables + if (AutoCollectNativePerformance.INSTANCE) { + AutoCollectNativePerformance.INSTANCE.dispose(); + } + AutoCollectNativePerformance.INSTANCE = this; + this._client = client; + } + /** + * Start instance of native metrics agent. + * + * @param {boolean} isEnabled + * @param {number} [collectionInterval=60000] + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype.enable = function (isEnabled, disabledMetrics, collectionInterval) { + var _this = this; + if (disabledMetrics === void 0) { disabledMetrics = {}; } + if (collectionInterval === void 0) { collectionInterval = 60000; } + if (AutoCollectNativePerformance._metricsAvailable == undefined && isEnabled && !this._isInitialized) { + // Try to require in the native-metrics library. If it's found initialize it, else do nothing and never try again. + try { + var NativeMetricsEmitters = require("applicationinsights-native-metrics"); + AutoCollectNativePerformance._emitter = new NativeMetricsEmitters(); + AutoCollectNativePerformance._metricsAvailable = true; + Logging.info("Native metrics module successfully loaded!"); + } + catch (err) { + // Package not available. Never try again + AutoCollectNativePerformance._metricsAvailable = false; + return; + } + } + this._isEnabled = isEnabled; + this._disabledMetrics = disabledMetrics; + if (this._isEnabled && !this._isInitialized) { + this._isInitialized = true; + } + // Enable the emitter if we were able to construct one + if (this._isEnabled && AutoCollectNativePerformance._emitter) { + // enable self + AutoCollectNativePerformance._emitter.enable(true, collectionInterval); + if (!this._handle) { + this._handle = setInterval(function () { return _this._trackNativeMetrics(); }, collectionInterval); + this._handle.unref(); + } + } + else if (AutoCollectNativePerformance._emitter) { + // disable self + AutoCollectNativePerformance._emitter.enable(false); + if (this._handle) { + clearInterval(this._handle); + this._handle = undefined; + } + } + }; + /** + * Cleanup this instance of AutoCollectNativePerformance + * + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype.dispose = function () { + this.enable(false); + }; + /** + * Parse environment variable and overwrite isEnabled based on respective fields being set + * + * @private + * @static + * @param {(boolean | IDisabledExtendedMetrics)} collectExtendedMetrics + * @param {(IBaseConfig)} customConfig + * @returns {(boolean | IDisabledExtendedMetrics)} + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.parseEnabled = function (collectExtendedMetrics, customConfig) { + var disableAll = customConfig.disableAllExtendedMetrics; + var individualOptOuts = customConfig.extendedMetricDisablers; + // case 1: disable all env var set, RETURN with isEnabled=false + if (disableAll) { + return { isEnabled: false, disabledMetrics: {} }; + } + // case 2: individual env vars set, RETURN with isEnabled=true, disabledMetrics={...} + if (individualOptOuts) { + var optOutsArr = individualOptOuts.split(","); + var disabledMetrics = {}; + if (optOutsArr.length > 0) { + for (var _i = 0, optOutsArr_1 = optOutsArr; _i < optOutsArr_1.length; _i++) { + var opt = optOutsArr_1[_i]; + disabledMetrics[opt] = true; + } + } + // case 2a: collectExtendedMetrics is an object, overwrite existing ones if they exist + if (typeof collectExtendedMetrics === "object") { + return { isEnabled: true, disabledMetrics: __assign(__assign({}, collectExtendedMetrics), disabledMetrics) }; + } + // case 2b: collectExtendedMetrics is a boolean, set disabledMetrics as is + return { isEnabled: collectExtendedMetrics, disabledMetrics: disabledMetrics }; + } + // case 4: no env vars set, input arg is a boolean, RETURN with isEnabled=collectExtendedMetrics, disabledMetrics={} + if (typeof collectExtendedMetrics === "boolean") { + return { isEnabled: collectExtendedMetrics, disabledMetrics: {} }; + } + else { // use else so we don't need to force typing on collectExtendedMetrics + // case 5: no env vars set, input arg is object, RETURN with isEnabled=true, disabledMetrics=collectExtendedMetrics + return { isEnabled: true, disabledMetrics: collectExtendedMetrics }; + } + }; + /** + * Trigger an iteration of native metrics collection + * + * @private + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype._trackNativeMetrics = function () { + var shouldSendAll = true; + if (typeof this._isEnabled !== "object") { + shouldSendAll = this._isEnabled; + } + if (shouldSendAll) { + this._trackGarbageCollection(); + this._trackEventLoop(); + this._trackHeapUsage(); + } + }; + /** + * Tracks garbage collection stats for this interval. One custom metric is sent per type of garbage + * collection that occurred during this collection interval. + * + * @private + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype._trackGarbageCollection = function () { + var _a; + if (this._disabledMetrics.gc) { + return; + } + var gcData = AutoCollectNativePerformance._emitter.getGCData(); + for (var gc in gcData) { + var metrics = gcData[gc].metrics; + var name_1 = gc + " Garbage Collection Duration"; + var stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0; + this._client.trackMetric({ + name: name_1, + value: metrics.total, + count: metrics.count, + max: metrics.max, + min: metrics.min, + stdDev: stdDev, + tagOverrides: (_a = {}, + _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, + _a) + }); + } + }; + /** + * Tracks event loop ticks per interval as a custom metric. Also included in the metric is min/max/avg + * time spent in event loop for this interval. + * + * @private + * @returns {void} + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype._trackEventLoop = function () { + var _a; + if (this._disabledMetrics.loop) { + return; + } + var loopData = AutoCollectNativePerformance._emitter.getLoopData(); + var metrics = loopData.loopUsage; + if (metrics.count == 0) { + return; + } + var name = "Event Loop CPU Time"; + var stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0; + this._client.trackMetric({ + name: name, + value: metrics.total, + count: metrics.count, + min: metrics.min, + max: metrics.max, + stdDev: stdDev, + tagOverrides: (_a = {}, + _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, + _a) + }); + }; + /** + * Track heap memory usage metrics as a custom metric. + * + * @private + * @memberof AutoCollectNativePerformance + */ + AutoCollectNativePerformance.prototype._trackHeapUsage = function () { + var _a, _b, _c; + if (this._disabledMetrics.heap) { + return; + } + var memoryUsage = process.memoryUsage(); + var heapUsed = memoryUsage.heapUsed, heapTotal = memoryUsage.heapTotal, rss = memoryUsage.rss; + this._client.trackMetric({ + name: "Memory Usage (Heap)", + value: heapUsed, + count: 1, + tagOverrides: (_a = {}, + _a[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, + _a) + }); + this._client.trackMetric({ + name: "Memory Total (Heap)", + value: heapTotal, + count: 1, + tagOverrides: (_b = {}, + _b[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, + _b) + }); + this._client.trackMetric({ + name: "Memory Usage (Non-Heap)", + value: rss - heapTotal, + count: 1, + tagOverrides: (_c = {}, + _c[this._client.context.keys.internalSdkVersion] = "node-nativeperf:" + Context.sdkVersion, + _c) + }); + }; + return AutoCollectNativePerformance; +}()); +exports.AutoCollectNativePerformance = AutoCollectNativePerformance; +//# sourceMappingURL=NativePerformance.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js.map b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js.map new file mode 100644 index 0000000..6750a74 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NativePerformance.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NativePerformance.js","sourceRoot":"","sources":["../../AutoCollection/NativePerformance.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAEA,4CAA+C;AAC/C,4CAA+C;AAe/C;IAWI,sCAAY,MAAuB;QAF3B,qBAAgB,GAA6B,EAAE,CAAC;QAGpD,+EAA+E;QAC/E,iEAAiE;QACjE,IAAI,4BAA4B,CAAC,QAAQ,E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,CAAC,AAvPD,IAuPC;AAvPY,oEAA4B","sourcesContent":["import TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport Context = require(\"../Library/Context\");\r\nimport Logging = require(\"../Library/Logging\");\r\nimport { IBaseConfig } from \"../Declarations/Interfaces\";\r\n\r\n/**\r\n * Interface which defines which specific extended metrics should be disabled\r\n *\r\n * @export\r\n * @interface IDisabledExtendedMetrics\r\n */\r\nexport interface IDisabledExtendedMetrics {\r\n gc?: boolean;\r\n heap?: boolean;\r\n loop?: boolean;\r\n}\r\n\r\nexport class AutoCollectNativePerformance {\r\n public static INSTANCE: AutoCollectNativePerformance;\r\n\r\n private static _emitter: any;\r\n private static _metricsAvailable: boolean; // is the native metrics lib installed\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _handle: NodeJS.Timer;\r\n private _client: TelemetryClient;\r\n private _disabledMetrics: IDisabledExtendedMetrics = {};\r\n\r\n constructor(client: TelemetryClient) {\r\n // Note: Only 1 instance of this can exist. So when we reconstruct this object,\r\n // just disable old native instance and reset JS member variables\r\n if (AutoCollectNativePerformance.INSTANCE) {\r\n AutoCollectNativePerformance.INSTANCE.dispose();\r\n }\r\n AutoCollectNativePerformance.INSTANCE = this;\r\n this._client = client;\r\n }\r\n\r\n /**\r\n * Start instance of native metrics agent.\r\n *\r\n * @param {boolean} isEnabled\r\n * @param {number} [collectionInterval=60000]\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n public enable(isEnabled: boolean, disabledMetrics: IDisabledExtendedMetrics = {}, collectionInterval = 60000): void {\r\n if (AutoCollectNativePerformance._metricsAvailable == undefined && isEnabled && !this._isInitialized) {\r\n // Try to require in the native-metrics library. If it's found initialize it, else do nothing and never try again.\r\n try {\r\n const NativeMetricsEmitters = require(\"applicationinsights-native-metrics\");\r\n AutoCollectNativePerformance._emitter = new NativeMetricsEmitters();\r\n AutoCollectNativePerformance._metricsAvailable = true;\r\n Logging.info(\"Native metrics module successfully loaded!\");\r\n } catch (err) {\r\n // Package not available. Never try again\r\n AutoCollectNativePerformance._metricsAvailable = false;\r\n return;\r\n }\r\n }\r\n\r\n this._isEnabled = isEnabled;\r\n this._disabledMetrics = disabledMetrics\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._isInitialized = true;\r\n }\r\n\r\n // Enable the emitter if we were able to construct one\r\n if (this._isEnabled && AutoCollectNativePerformance._emitter) {\r\n // enable self\r\n AutoCollectNativePerformance._emitter.enable(true, collectionInterval);\r\n if (!this._handle) {\r\n this._handle = setInterval(() => this._trackNativeMetrics(), collectionInterval);\r\n this._handle.unref();\r\n }\r\n } else if (AutoCollectNativePerformance._emitter) {\r\n // disable self\r\n AutoCollectNativePerformance._emitter.enable(false);\r\n if (this._handle) {\r\n clearInterval(this._handle);\r\n this._handle = undefined;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Cleanup this instance of AutoCollectNativePerformance\r\n *\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n public dispose(): void {\r\n this.enable(false);\r\n }\r\n\r\n /**\r\n * Parse environment variable and overwrite isEnabled based on respective fields being set\r\n *\r\n * @private\r\n * @static\r\n * @param {(boolean | IDisabledExtendedMetrics)} collectExtendedMetrics\r\n * @param {(IBaseConfig)} customConfig\r\n * @returns {(boolean | IDisabledExtendedMetrics)}\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n public static parseEnabled(collectExtendedMetrics: boolean | IDisabledExtendedMetrics, customConfig: IBaseConfig): { isEnabled: boolean, disabledMetrics: IDisabledExtendedMetrics } {\r\n const disableAll = customConfig.disableAllExtendedMetrics;\r\n const individualOptOuts = customConfig.extendedMetricDisablers;\r\n\r\n // case 1: disable all env var set, RETURN with isEnabled=false\r\n if (disableAll) {\r\n return { isEnabled: false, disabledMetrics: {} };\r\n }\r\n\r\n // case 2: individual env vars set, RETURN with isEnabled=true, disabledMetrics={...}\r\n if (individualOptOuts) {\r\n const optOutsArr = individualOptOuts.split(\",\");\r\n const disabledMetrics: any = {};\r\n if (optOutsArr.length > 0) {\r\n for (const opt of optOutsArr) {\r\n disabledMetrics[opt] = true;\r\n }\r\n }\r\n\r\n // case 2a: collectExtendedMetrics is an object, overwrite existing ones if they exist\r\n if (typeof collectExtendedMetrics === \"object\") {\r\n return { isEnabled: true, disabledMetrics: { ...collectExtendedMetrics, ...disabledMetrics } };\r\n }\r\n\r\n // case 2b: collectExtendedMetrics is a boolean, set disabledMetrics as is\r\n return { isEnabled: collectExtendedMetrics, disabledMetrics };\r\n }\r\n\r\n // case 4: no env vars set, input arg is a boolean, RETURN with isEnabled=collectExtendedMetrics, disabledMetrics={}\r\n if (typeof collectExtendedMetrics === \"boolean\") {\r\n return { isEnabled: collectExtendedMetrics, disabledMetrics: {} };\r\n } else { // use else so we don't need to force typing on collectExtendedMetrics\r\n // case 5: no env vars set, input arg is object, RETURN with isEnabled=true, disabledMetrics=collectExtendedMetrics\r\n return { isEnabled: true, disabledMetrics: collectExtendedMetrics };\r\n }\r\n }\r\n\r\n /**\r\n * Trigger an iteration of native metrics collection\r\n *\r\n * @private\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n private _trackNativeMetrics() {\r\n let shouldSendAll = true;\r\n if (typeof this._isEnabled !== \"object\") {\r\n shouldSendAll = this._isEnabled;\r\n }\r\n\r\n if (shouldSendAll) {\r\n this._trackGarbageCollection();\r\n this._trackEventLoop();\r\n this._trackHeapUsage();\r\n }\r\n }\r\n\r\n /**\r\n * Tracks garbage collection stats for this interval. One custom metric is sent per type of garbage\r\n * collection that occurred during this collection interval.\r\n *\r\n * @private\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n private _trackGarbageCollection(): void {\r\n if (this._disabledMetrics.gc) {\r\n return;\r\n }\r\n\r\n const gcData = AutoCollectNativePerformance._emitter.getGCData();\r\n\r\n for (let gc in gcData) {\r\n const metrics = gcData[gc].metrics;\r\n const name = `${gc} Garbage Collection Duration`;\r\n const stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0;\r\n this._client.trackMetric({\r\n name: name,\r\n value: metrics.total,\r\n count: metrics.count,\r\n max: metrics.max,\r\n min: metrics.min,\r\n stdDev: stdDev,\r\n tagOverrides: {\r\n [this._client.context.keys.internalSdkVersion]: \"node-nativeperf:\" + Context.sdkVersion\r\n }\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Tracks event loop ticks per interval as a custom metric. Also included in the metric is min/max/avg\r\n * time spent in event loop for this interval.\r\n *\r\n * @private\r\n * @returns {void}\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n private _trackEventLoop(): void {\r\n if (this._disabledMetrics.loop) {\r\n return;\r\n }\r\n\r\n const loopData = AutoCollectNativePerformance._emitter.getLoopData();\r\n const metrics = loopData.loopUsage;\r\n if (metrics.count == 0) {\r\n return;\r\n }\r\n\r\n const name = \"Event Loop CPU Time\";\r\n const stdDev = Math.sqrt(metrics.sumSquares / metrics.count - Math.pow(metrics.total / metrics.count, 2)) || 0;\r\n this._client.trackMetric({\r\n name: name,\r\n value: metrics.total,\r\n count: metrics.count,\r\n min: metrics.min,\r\n max: metrics.max,\r\n stdDev: stdDev,\r\n tagOverrides: {\r\n [this._client.context.keys.internalSdkVersion]: \"node-nativeperf:\" + Context.sdkVersion\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Track heap memory usage metrics as a custom metric.\r\n *\r\n * @private\r\n * @memberof AutoCollectNativePerformance\r\n */\r\n private _trackHeapUsage(): void {\r\n if (this._disabledMetrics.heap) {\r\n return;\r\n }\r\n\r\n const memoryUsage = process.memoryUsage();\r\n const { heapUsed, heapTotal, rss } = memoryUsage;\r\n\r\n this._client.trackMetric({\r\n name: \"Memory Usage (Heap)\",\r\n value: heapUsed,\r\n count: 1,\r\n tagOverrides: {\r\n [this._client.context.keys.internalSdkVersion]: \"node-nativeperf:\" + Context.sdkVersion\r\n }\r\n });\r\n this._client.trackMetric({\r\n name: \"Memory Total (Heap)\",\r\n value: heapTotal,\r\n count: 1,\r\n tagOverrides: {\r\n [this._client.context.keys.internalSdkVersion]: \"node-nativeperf:\" + Context.sdkVersion\r\n }\r\n });\r\n this._client.trackMetric({\r\n name: \"Memory Usage (Non-Heap)\",\r\n value: rss - heapTotal,\r\n count: 1,\r\n tagOverrides: {\r\n [this._client.context.keys.internalSdkVersion]: \"node-nativeperf:\" + Context.sdkVersion\r\n }\r\n });\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.d.ts b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.d.ts new file mode 100644 index 0000000..7f2b60e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.d.ts @@ -0,0 +1,28 @@ +export declare class NetworkStatsbeat { + time: number; + lastTime: number; + endpoint: number; + host: string; + totalRequestCount: number; + lastRequestCount: number; + totalSuccesfulRequestCount: number; + totalFailedRequestCount: { + statusCode: number; + count: number; + }[]; + retryCount: { + statusCode: number; + count: number; + }[]; + exceptionCount: { + exceptionType: string; + count: number; + }[]; + throttleCount: { + statusCode: number; + count: number; + }[]; + intervalRequestExecutionTime: number; + lastIntervalRequestExecutionTime: number; + constructor(endpoint: number, host: string); +} diff --git a/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js new file mode 100644 index 0000000..d6be370 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NetworkStatsbeat = void 0; +var NetworkStatsbeat = /** @class */ (function () { + function NetworkStatsbeat(endpoint, host) { + this.endpoint = endpoint; + this.host = host; + this.totalRequestCount = 0; + this.totalSuccesfulRequestCount = 0; + this.totalFailedRequestCount = []; + this.retryCount = []; + this.exceptionCount = []; + this.throttleCount = []; + this.intervalRequestExecutionTime = 0; + this.lastIntervalRequestExecutionTime = 0; + this.lastTime = +new Date; + this.lastRequestCount = 0; + } + return NetworkStatsbeat; +}()); +exports.NetworkStatsbeat = NetworkStatsbeat; +//# sourceMappingURL=NetworkStatsbeat.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js.map b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js.map new file mode 100644 index 0000000..ab51c1e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/NetworkStatsbeat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NetworkStatsbeat.js","sourceRoot":"","sources":["../../AutoCollection/NetworkStatsbeat.ts"],"names":[],"mappings":";;;AAAA;IA4BI,0BAAY,QAAgB,EAAE,IAAY;QACtC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,0BAA0B,GAAG,CAAC,CAAC;QACpC,IAAI,CAAC,uBAAuB,GAAG,EAAE,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;QACxB,IAAI,CAAC,4BAA4B,GAAG,CAAC,CAAC;QACtC,IAAI,CAAC,gCAAgC,GAAG,CAAC,CAAC;QAC1C,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,IAAI,CAAC;QAC1B,IAAI,CAAC,gBAAgB,GAAG,CAAC,CAAC;IAC9B,CAAC;IACL,uBAAC;AAAD,CAAC,AA1CD,IA0CC;AA1CY,4CAAgB","sourcesContent":["export class NetworkStatsbeat {\r\n\r\n public time: number;\r\n\r\n public lastTime: number;\r\n\r\n public endpoint: number;\r\n\r\n public host: string;\r\n\r\n public totalRequestCount: number;\r\n\r\n public lastRequestCount: number;\r\n\r\n public totalSuccesfulRequestCount: number;\r\n\r\n public totalFailedRequestCount: { statusCode: number, count: number }[];\r\n\r\n public retryCount: { statusCode: number, count: number }[];\r\n\r\n public exceptionCount: { exceptionType: string, count: number }[];\r\n\r\n public throttleCount: { statusCode: number, count: number }[];\r\n\r\n public intervalRequestExecutionTime: number;\r\n\r\n public lastIntervalRequestExecutionTime: number;\r\n\r\n constructor(endpoint: number, host: string) {\r\n this.endpoint = endpoint;\r\n this.host = host;\r\n this.totalRequestCount = 0;\r\n this.totalSuccesfulRequestCount = 0;\r\n this.totalFailedRequestCount = [];\r\n this.retryCount = [];\r\n this.exceptionCount = [];\r\n this.throttleCount = [];\r\n this.intervalRequestExecutionTime = 0;\r\n this.lastIntervalRequestExecutionTime = 0;\r\n this.lastTime = +new Date;\r\n this.lastRequestCount = 0;\r\n }\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Performance.d.ts b/node_modules/applicationinsights/out/AutoCollection/Performance.d.ts new file mode 100644 index 0000000..ceddadd --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Performance.d.ts @@ -0,0 +1,43 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +declare class AutoCollectPerformance { + static INSTANCE: AutoCollectPerformance; + private static _totalRequestCount; + private static _totalFailedRequestCount; + private static _totalDependencyCount; + private static _totalFailedDependencyCount; + private static _totalExceptionCount; + private static _intervalDependencyExecutionTime; + private static _intervalRequestExecutionTime; + private _lastIntervalRequestExecutionTime; + private _lastIntervalDependencyExecutionTime; + private _enableLiveMetricsCounters; + private _collectionInterval; + private _client; + private _handle; + private _isEnabled; + private _isInitialized; + private _lastAppCpuUsage; + private _lastHrtime; + private _lastCpus; + private _lastDependencies; + private _lastRequests; + private _lastExceptions; + /** + * @param enableLiveMetricsCounters - enable sending additional live metrics information (dependency metrics, exception metrics, committed memory) + */ + constructor(client: TelemetryClient, collectionInterval?: number, enableLiveMetricsCounters?: boolean); + enable(isEnabled: boolean, collectionInterval?: number): void; + static countRequest(duration: number | string, success: boolean): void; + static countException(): void; + static countDependency(duration: number | string, success: boolean): void; + isInitialized(): boolean; + static isEnabled(): boolean; + trackPerformance(): void; + private _trackCpu; + private _trackMemory; + private _trackNetwork; + private _trackDependencyRate; + private _trackExceptionRate; + dispose(): void; +} +export = AutoCollectPerformance; diff --git a/node_modules/applicationinsights/out/AutoCollection/Performance.js b/node_modules/applicationinsights/out/AutoCollection/Performance.js new file mode 100644 index 0000000..1cdcb62 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Performance.js @@ -0,0 +1,279 @@ +"use strict"; +var os = require("os"); +var Constants = require("../Declarations/Constants"); +var AutoCollectPerformance = /** @class */ (function () { + /** + * @param enableLiveMetricsCounters - enable sending additional live metrics information (dependency metrics, exception metrics, committed memory) + */ + function AutoCollectPerformance(client, collectionInterval, enableLiveMetricsCounters) { + if (collectionInterval === void 0) { collectionInterval = 60000; } + if (enableLiveMetricsCounters === void 0) { enableLiveMetricsCounters = false; } + this._lastIntervalRequestExecutionTime = 0; // the sum of durations which took place during from app start until last interval + this._lastIntervalDependencyExecutionTime = 0; + if (!AutoCollectPerformance.INSTANCE) { + AutoCollectPerformance.INSTANCE = this; + } + this._lastRequests = { totalRequestCount: 0, totalFailedRequestCount: 0, time: 0 }; + this._lastDependencies = { totalDependencyCount: 0, totalFailedDependencyCount: 0, time: 0 }; + this._lastExceptions = { totalExceptionCount: 0, time: 0 }; + this._isInitialized = false; + this._client = client; + this._collectionInterval = collectionInterval; + this._enableLiveMetricsCounters = enableLiveMetricsCounters; + } + AutoCollectPerformance.prototype.enable = function (isEnabled, collectionInterval) { + var _this = this; + this._isEnabled = isEnabled; + if (this._isEnabled && !this._isInitialized) { + this._isInitialized = true; + } + if (isEnabled) { + if (!this._handle) { + this._lastCpus = os.cpus(); + this._lastRequests = { + totalRequestCount: AutoCollectPerformance._totalRequestCount, + totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount, + time: +new Date + }; + this._lastDependencies = { + totalDependencyCount: AutoCollectPerformance._totalDependencyCount, + totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount, + time: +new Date + }; + this._lastExceptions = { + totalExceptionCount: AutoCollectPerformance._totalExceptionCount, + time: +new Date + }; + if (typeof process.cpuUsage === "function") { + this._lastAppCpuUsage = process.cpuUsage(); + } + this._lastHrtime = process.hrtime(); + this._collectionInterval = collectionInterval || this._collectionInterval; + this._handle = setInterval(function () { return _this.trackPerformance(); }, this._collectionInterval); + this._handle.unref(); // Allow the app to terminate even while this loop is going on + } + } + else { + if (this._handle) { + clearInterval(this._handle); + this._handle = undefined; + } + } + }; + AutoCollectPerformance.countRequest = function (duration, success) { + var durationMs; + if (!AutoCollectPerformance.isEnabled()) { + return; + } + if (typeof duration === "string") { + // dependency duration is passed in as "00:00:00.123" by autocollectors + durationMs = +new Date("1970-01-01T" + duration + "Z"); // convert to num ms, returns NaN if wrong + } + else if (typeof duration === "number") { + durationMs = duration; + } + else { + return; + } + AutoCollectPerformance._intervalRequestExecutionTime += durationMs; + if (success === false) { + AutoCollectPerformance._totalFailedRequestCount++; + } + AutoCollectPerformance._totalRequestCount++; + }; + AutoCollectPerformance.countException = function () { + AutoCollectPerformance._totalExceptionCount++; + }; + AutoCollectPerformance.countDependency = function (duration, success) { + var durationMs; + if (!AutoCollectPerformance.isEnabled()) { + return; + } + if (typeof duration === "string") { + // dependency duration is passed in as "00:00:00.123" by autocollectors + durationMs = +new Date("1970-01-01T" + duration + "Z"); // convert to num ms, returns NaN if wrong + } + else if (typeof duration === "number") { + durationMs = duration; + } + else { + return; + } + AutoCollectPerformance._intervalDependencyExecutionTime += durationMs; + if (success === false) { + AutoCollectPerformance._totalFailedDependencyCount++; + } + AutoCollectPerformance._totalDependencyCount++; + }; + AutoCollectPerformance.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectPerformance.isEnabled = function () { + return AutoCollectPerformance.INSTANCE && AutoCollectPerformance.INSTANCE._isEnabled; + }; + AutoCollectPerformance.prototype.trackPerformance = function () { + this._trackCpu(); + this._trackMemory(); + this._trackNetwork(); + this._trackDependencyRate(); + this._trackExceptionRate(); + }; + AutoCollectPerformance.prototype._trackCpu = function () { + // this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary + // to find the delta since the last measurement + var cpus = os.cpus(); + if (cpus && cpus.length && this._lastCpus && cpus.length === this._lastCpus.length) { + var totalUser = 0; + var totalSys = 0; + var totalNice = 0; + var totalIdle = 0; + var totalIrq = 0; + for (var i = 0; !!cpus && i < cpus.length; i++) { + var cpu = cpus[i]; + var lastCpu = this._lastCpus[i]; + var name = "% cpu(" + i + ") "; + var model = cpu.model; + var speed = cpu.speed; + var times = cpu.times; + var lastTimes = lastCpu.times; + // user cpu time (or) % CPU time spent in user space + var user = (times.user - lastTimes.user) || 0; + totalUser += user; + // system cpu time (or) % CPU time spent in kernel space + var sys = (times.sys - lastTimes.sys) || 0; + totalSys += sys; + // user nice cpu time (or) % CPU time spent on low priority processes + var nice = (times.nice - lastTimes.nice) || 0; + totalNice += nice; + // idle cpu time (or) % CPU time spent idle + var idle = (times.idle - lastTimes.idle) || 0; + totalIdle += idle; + // irq (or) % CPU time spent servicing/handling hardware interrupts + var irq = (times.irq - lastTimes.irq) || 0; + totalIrq += irq; + } + // Calculate % of total cpu time (user + system) this App Process used (Only supported by node v6.1.0+) + var appCpuPercent = undefined; + if (typeof process.cpuUsage === "function") { + var appCpuUsage = process.cpuUsage(); + var hrtime = process.hrtime(); + var totalApp = ((appCpuUsage.user - this._lastAppCpuUsage.user) + (appCpuUsage.system - this._lastAppCpuUsage.system)) || 0; + if (typeof this._lastHrtime !== "undefined" && this._lastHrtime.length === 2) { + var elapsedTime = ((hrtime[0] - this._lastHrtime[0]) * 1e6 + (hrtime[1] - this._lastHrtime[1]) / 1e3) || 0; // convert to microseconds + appCpuPercent = 100 * totalApp / (elapsedTime * cpus.length); + } + // Set previous + this._lastAppCpuUsage = appCpuUsage; + this._lastHrtime = hrtime; + } + var combinedTotal = (totalUser + totalSys + totalNice + totalIdle + totalIrq) || 1; + this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESSOR_TIME, value: ((combinedTotal - totalIdle) / combinedTotal) * 100 }); + this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESS_TIME, value: appCpuPercent || ((totalUser / combinedTotal) * 100) }); + } + this._lastCpus = cpus; + }; + AutoCollectPerformance.prototype._trackMemory = function () { + var freeMem = os.freemem(); + var usedMem = process.memoryUsage().rss; + var committedMemory = os.totalmem() - freeMem; + this._client.trackMetric({ name: Constants.PerformanceCounter.PRIVATE_BYTES, value: usedMem }); + this._client.trackMetric({ name: Constants.PerformanceCounter.AVAILABLE_BYTES, value: freeMem }); + // Only supported by quickpulse service + if (this._enableLiveMetricsCounters) { + this._client.trackMetric({ name: Constants.QuickPulseCounter.COMMITTED_BYTES, value: committedMemory }); + } + }; + AutoCollectPerformance.prototype._trackNetwork = function () { + // track total request counters + var lastRequests = this._lastRequests; + var requests = { + totalRequestCount: AutoCollectPerformance._totalRequestCount, + totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount, + time: +new Date + }; + var intervalRequests = (requests.totalRequestCount - lastRequests.totalRequestCount) || 0; + var intervalFailedRequests = (requests.totalFailedRequestCount - lastRequests.totalFailedRequestCount) || 0; + var elapsedMs = requests.time - lastRequests.time; + var elapsedSeconds = elapsedMs / 1000; + var averageRequestExecutionTime = ((AutoCollectPerformance._intervalRequestExecutionTime - this._lastIntervalRequestExecutionTime) / intervalRequests) || 0; // default to 0 in case no requests in this interval + this._lastIntervalRequestExecutionTime = AutoCollectPerformance._intervalRequestExecutionTime; // reset + if (elapsedMs > 0) { + var requestsPerSec = intervalRequests / elapsedSeconds; + var failedRequestsPerSec = intervalFailedRequests / elapsedSeconds; + this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_RATE, value: requestsPerSec }); + // Only send duration to live metrics if it has been updated! + if (!this._enableLiveMetricsCounters || intervalRequests > 0) { + this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_DURATION, value: averageRequestExecutionTime }); + } + // Only supported by quickpulse service + if (this._enableLiveMetricsCounters) { + this._client.trackMetric({ name: Constants.QuickPulseCounter.REQUEST_FAILURE_RATE, value: failedRequestsPerSec }); + } + } + this._lastRequests = requests; + }; + // Static counter is accumulated externally. Report the rate to client here + // Note: This is currently only used with QuickPulse client + AutoCollectPerformance.prototype._trackDependencyRate = function () { + if (this._enableLiveMetricsCounters) { + var lastDependencies = this._lastDependencies; + var dependencies = { + totalDependencyCount: AutoCollectPerformance._totalDependencyCount, + totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount, + time: +new Date + }; + var intervalDependencies = (dependencies.totalDependencyCount - lastDependencies.totalDependencyCount) || 0; + var intervalFailedDependencies = (dependencies.totalFailedDependencyCount - lastDependencies.totalFailedDependencyCount) || 0; + var elapsedMs = dependencies.time - lastDependencies.time; + var elapsedSeconds = elapsedMs / 1000; + var averageDependencyExecutionTime = ((AutoCollectPerformance._intervalDependencyExecutionTime - this._lastIntervalDependencyExecutionTime) / intervalDependencies) || 0; + this._lastIntervalDependencyExecutionTime = AutoCollectPerformance._intervalDependencyExecutionTime; // reset + if (elapsedMs > 0) { + var dependenciesPerSec = intervalDependencies / elapsedSeconds; + var failedDependenciesPerSec = intervalFailedDependencies / elapsedSeconds; + this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_RATE, value: dependenciesPerSec }); + this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_FAILURE_RATE, value: failedDependenciesPerSec }); + // redundant check for livemetrics, but kept for consistency w/ requests + // Only send duration to live metrics if it has been updated! + if (!this._enableLiveMetricsCounters || intervalDependencies > 0) { + this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_DURATION, value: averageDependencyExecutionTime }); + } + } + this._lastDependencies = dependencies; + } + }; + // Static counter is accumulated externally. Report the rate to client here + // Note: This is currently only used with QuickPulse client + AutoCollectPerformance.prototype._trackExceptionRate = function () { + if (this._enableLiveMetricsCounters) { + var lastExceptions = this._lastExceptions; + var exceptions = { + totalExceptionCount: AutoCollectPerformance._totalExceptionCount, + time: +new Date + }; + var intervalExceptions = (exceptions.totalExceptionCount - lastExceptions.totalExceptionCount) || 0; + var elapsedMs = exceptions.time - lastExceptions.time; + var elapsedSeconds = elapsedMs / 1000; + if (elapsedMs > 0) { + var exceptionsPerSec = intervalExceptions / elapsedSeconds; + this._client.trackMetric({ name: Constants.QuickPulseCounter.EXCEPTION_RATE, value: exceptionsPerSec }); + } + this._lastExceptions = exceptions; + } + }; + AutoCollectPerformance.prototype.dispose = function () { + AutoCollectPerformance.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + AutoCollectPerformance._totalRequestCount = 0; + AutoCollectPerformance._totalFailedRequestCount = 0; + AutoCollectPerformance._totalDependencyCount = 0; + AutoCollectPerformance._totalFailedDependencyCount = 0; + AutoCollectPerformance._totalExceptionCount = 0; + AutoCollectPerformance._intervalDependencyExecutionTime = 0; + AutoCollectPerformance._intervalRequestExecutionTime = 0; + return AutoCollectPerformance; +}()); +module.exports = AutoCollectPerformance; +//# sourceMappingURL=Performance.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Performance.js.map b/node_modules/applicationinsights/out/AutoCollection/Performance.js.map new file mode 100644 index 0000000..251a0d1 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Performance.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Performance.js","sourceRoot":"","sources":["../../AutoCollection/Performance.ts"],"names":[],"mappings":";AAAA,uBAA0B;AAG1B,qDAAwD;AAExD;IA2BI;;OAEG;IACH,gCAAY,MAAuB,EAAE,kBAA0B,EAAE,yBAAiC;QAA7D,mCAAA,EAAA,0BAA0B;QAAE,0CAAA,EAAA,iCAAiC;QAlB1F,sCAAiC,GAAW,CAAC,CAAC,CAAC,kFAAkF;QACjI,yCAAoC,GAAW,CAAC,CAAC;QAkBrD,IAAI,CAAC,sBAAsB,CAAC,QAAQ,EAAE;YA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I,CAAC,CAAC;YACpG,IAAI,SAAS,GAAG,UAAU,CAAC,IAAI,GAAG,cAAc,CAAC,IAAI,CAAC;YACtD,IAAI,cAAc,GAAG,SAAS,GAAG,IAAI,CAAC;YAEtC,IAAI,SAAS,GAAG,CAAC,EAAE;gBACf,IAAI,gBAAgB,GAAG,kBAAkB,GAAG,cAAc,CAAC;gBAC3D,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,iBAAiB,CAAC,cAAc,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;aAC3G;YACD,IAAI,CAAC,eAAe,GAAG,UAAU,CAAC;SACrC;IACL,CAAC;IAEM,wCAAO,GAAd;QACI,sBAAsB,CAAC,QAAQ,GAAG,IAAI,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IAnUc,yCAAkB,GAAW,CAAC,CAAC;IAC/B,+CAAwB,GAAW,CAAC,CAAC;IACrC,4CAAqB,GAAW,CAAC,CAAC;IAClC,kDAA2B,GAAW,CAAC,CAAC;IACxC,2CAAoB,GAAW,CAAC,CAAC;IACjC,uDAAgC,GAAW,CAAC,CAAC;IAC7C,oDAA6B,GAAW,CAAC,CAAC;IA8T7D,6BAAC;CAAA,AAxUD,IAwUC;AAED,iBAAS,sBAAsB,CAAC","sourcesContent":["import os = require(\"os\");\r\n\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\n\r\nclass AutoCollectPerformance {\r\n\r\n public static INSTANCE: AutoCollectPerformance;\r\n\r\n private static _totalRequestCount: number = 0;\r\n private static _totalFailedRequestCount: number = 0;\r\n private static _totalDependencyCount: number = 0;\r\n private static _totalFailedDependencyCount: number = 0;\r\n private static _totalExceptionCount: number = 0;\r\n private static _intervalDependencyExecutionTime: number = 0;\r\n private static _intervalRequestExecutionTime: number = 0;\r\n\r\n private _lastIntervalRequestExecutionTime: number = 0; // the sum of durations which took place during from app start until last interval\r\n private _lastIntervalDependencyExecutionTime: number = 0;\r\n private _enableLiveMetricsCounters: boolean;\r\n private _collectionInterval: number;\r\n private _client: TelemetryClient;\r\n private _handle: NodeJS.Timer;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _lastAppCpuUsage: { user: number, system: number };\r\n private _lastHrtime: number[];\r\n private _lastCpus: { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];\r\n private _lastDependencies: { totalDependencyCount: number; totalFailedDependencyCount: number; time: number; };\r\n private _lastRequests: { totalRequestCount: number; totalFailedRequestCount: number; time: number; };\r\n private _lastExceptions: { totalExceptionCount: number, time: number };\r\n\r\n /**\r\n * @param enableLiveMetricsCounters - enable sending additional live metrics information (dependency metrics, exception metrics, committed memory)\r\n */\r\n constructor(client: TelemetryClient, collectionInterval = 60000, enableLiveMetricsCounters = false) {\r\n if (!AutoCollectPerformance.INSTANCE) {\r\n AutoCollectPerformance.INSTANCE = this;\r\n }\r\n\r\n this._lastRequests = { totalRequestCount: 0, totalFailedRequestCount: 0, time: 0 };\r\n this._lastDependencies = { totalDependencyCount: 0, totalFailedDependencyCount: 0, time: 0 };\r\n this._lastExceptions = { totalExceptionCount: 0,time: 0 };\r\n this._isInitialized = false;\r\n this._client = client;\r\n this._collectionInterval = collectionInterval;\r\n this._enableLiveMetricsCounters = enableLiveMetricsCounters;\r\n }\r\n\r\n public enable(isEnabled: boolean, collectionInterval?: number) {\r\n this._isEnabled = isEnabled;\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._isInitialized = true;\r\n }\r\n\r\n if (isEnabled) {\r\n if (!this._handle) {\r\n this._lastCpus = os.cpus();\r\n this._lastRequests = {\r\n totalRequestCount: AutoCollectPerformance._totalRequestCount,\r\n totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount,\r\n time: +new Date\r\n };\r\n this._lastDependencies = {\r\n totalDependencyCount: AutoCollectPerformance._totalDependencyCount,\r\n totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount,\r\n time: +new Date\r\n };\r\n this._lastExceptions = {\r\n totalExceptionCount: AutoCollectPerformance._totalExceptionCount,\r\n time: +new Date\r\n };\r\n\r\n if (typeof (process as any).cpuUsage === \"function\") {\r\n this._lastAppCpuUsage = (process as any).cpuUsage();\r\n }\r\n this._lastHrtime = process.hrtime();\r\n this._collectionInterval = collectionInterval || this._collectionInterval;\r\n this._handle = setInterval(() => this.trackPerformance(), this._collectionInterval);\r\n this._handle.unref(); // Allow the app to terminate even while this loop is going on\r\n }\r\n } else {\r\n if (this._handle) {\r\n clearInterval(this._handle);\r\n this._handle = undefined;\r\n }\r\n }\r\n }\r\n\r\n public static countRequest(duration: number | string, success: boolean) {\r\n let durationMs: number;\r\n if (!AutoCollectPerformance.isEnabled()) {\r\n return;\r\n }\r\n\r\n if (typeof duration === \"string\") {\r\n // dependency duration is passed in as \"00:00:00.123\" by autocollectors\r\n durationMs = +new Date(\"1970-01-01T\" + duration + \"Z\"); // convert to num ms, returns NaN if wrong\r\n } else if (typeof duration === \"number\") {\r\n durationMs = duration;\r\n } else {\r\n return;\r\n }\r\n\r\n AutoCollectPerformance._intervalRequestExecutionTime += durationMs;\r\n if (success === false) {\r\n AutoCollectPerformance._totalFailedRequestCount++;\r\n }\r\n AutoCollectPerformance._totalRequestCount++;\r\n }\r\n\r\n public static countException() {\r\n AutoCollectPerformance._totalExceptionCount++;\r\n }\r\n\r\n public static countDependency(duration: number | string, success: boolean) {\r\n let durationMs: number;\r\n if (!AutoCollectPerformance.isEnabled()) {\r\n return;\r\n }\r\n\r\n if (typeof duration === \"string\") {\r\n // dependency duration is passed in as \"00:00:00.123\" by autocollectors\r\n durationMs = +new Date(\"1970-01-01T\" + duration + \"Z\"); // convert to num ms, returns NaN if wrong\r\n } else if (typeof duration === \"number\") {\r\n durationMs = duration;\r\n } else {\r\n return;\r\n }\r\n\r\n AutoCollectPerformance._intervalDependencyExecutionTime += durationMs;\r\n if (success === false) {\r\n AutoCollectPerformance._totalFailedDependencyCount++;\r\n }\r\n AutoCollectPerformance._totalDependencyCount++;\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public static isEnabled() {\r\n return AutoCollectPerformance.INSTANCE && AutoCollectPerformance.INSTANCE._isEnabled;\r\n }\r\n\r\n public trackPerformance() {\r\n this._trackCpu();\r\n this._trackMemory();\r\n this._trackNetwork();\r\n this._trackDependencyRate();\r\n this._trackExceptionRate();\r\n }\r\n\r\n private _trackCpu() {\r\n // this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary\r\n // to find the delta since the last measurement\r\n var cpus = os.cpus();\r\n if (cpus && cpus.length && this._lastCpus && cpus.length === this._lastCpus.length) {\r\n var totalUser = 0;\r\n var totalSys = 0;\r\n var totalNice = 0;\r\n var totalIdle = 0;\r\n var totalIrq = 0;\r\n for (var i = 0; !!cpus && i < cpus.length; i++) {\r\n var cpu = cpus[i];\r\n var lastCpu = this._lastCpus[i];\r\n\r\n var name = \"% cpu(\" + i + \") \";\r\n var model = cpu.model;\r\n var speed = cpu.speed;\r\n var times = cpu.times;\r\n var lastTimes = lastCpu.times;\r\n\r\n // user cpu time (or) % CPU time spent in user space\r\n var user = (times.user - lastTimes.user) || 0;\r\n totalUser += user;\r\n\r\n // system cpu time (or) % CPU time spent in kernel space\r\n var sys = (times.sys - lastTimes.sys) || 0;\r\n totalSys += sys;\r\n\r\n // user nice cpu time (or) % CPU time spent on low priority processes\r\n var nice = (times.nice - lastTimes.nice) || 0;\r\n totalNice += nice;\r\n\r\n // idle cpu time (or) % CPU time spent idle\r\n var idle = (times.idle - lastTimes.idle) || 0;\r\n totalIdle += idle;\r\n\r\n // irq (or) % CPU time spent servicing/handling hardware interrupts\r\n var irq = (times.irq - lastTimes.irq) || 0;\r\n totalIrq += irq;\r\n }\r\n\r\n // Calculate % of total cpu time (user + system) this App Process used (Only supported by node v6.1.0+)\r\n let appCpuPercent: number = undefined;\r\n if (typeof (process as any).cpuUsage === \"function\") {\r\n const appCpuUsage = (process as any).cpuUsage();\r\n const hrtime = process.hrtime();\r\n\r\n const totalApp = ((appCpuUsage.user - this._lastAppCpuUsage.user) + (appCpuUsage.system - this._lastAppCpuUsage.system)) || 0;\r\n\r\n if (typeof this._lastHrtime !== \"undefined\" && this._lastHrtime.length === 2) {\r\n const elapsedTime = ((hrtime[0] - this._lastHrtime[0]) * 1e6 + (hrtime[1] - this._lastHrtime[1]) / 1e3) || 0; // convert to microseconds\r\n\r\n appCpuPercent = 100 * totalApp / (elapsedTime * cpus.length);\r\n }\r\n\r\n // Set previous\r\n this._lastAppCpuUsage = appCpuUsage;\r\n this._lastHrtime = hrtime;\r\n }\r\n\r\n var combinedTotal = (totalUser + totalSys + totalNice + totalIdle + totalIrq) || 1;\r\n\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESSOR_TIME, value: ((combinedTotal - totalIdle) / combinedTotal) * 100 });\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESS_TIME, value: appCpuPercent || ((totalUser / combinedTotal) * 100) });\r\n }\r\n\r\n this._lastCpus = cpus;\r\n }\r\n\r\n private _trackMemory() {\r\n var freeMem = os.freemem();\r\n var usedMem = process.memoryUsage().rss;\r\n var committedMemory = os.totalmem() - freeMem;\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.PRIVATE_BYTES, value: usedMem });\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.AVAILABLE_BYTES, value: freeMem });\r\n\r\n // Only supported by quickpulse service\r\n if (this._enableLiveMetricsCounters) {\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.COMMITTED_BYTES, value: committedMemory });\r\n }\r\n }\r\n\r\n private _trackNetwork() {\r\n // track total request counters\r\n var lastRequests = this._lastRequests;\r\n var requests = {\r\n totalRequestCount: AutoCollectPerformance._totalRequestCount,\r\n totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount,\r\n time: +new Date\r\n };\r\n\r\n var intervalRequests = (requests.totalRequestCount - lastRequests.totalRequestCount) || 0;\r\n var intervalFailedRequests = (requests.totalFailedRequestCount - lastRequests.totalFailedRequestCount) || 0;\r\n var elapsedMs = requests.time - lastRequests.time;\r\n var elapsedSeconds = elapsedMs / 1000;\r\n var averageRequestExecutionTime = ((AutoCollectPerformance._intervalRequestExecutionTime - this._lastIntervalRequestExecutionTime) / intervalRequests) || 0; // default to 0 in case no requests in this interval\r\n this._lastIntervalRequestExecutionTime = AutoCollectPerformance._intervalRequestExecutionTime // reset\r\n\r\n if (elapsedMs > 0) {\r\n var requestsPerSec = intervalRequests / elapsedSeconds;\r\n var failedRequestsPerSec = intervalFailedRequests / elapsedSeconds;\r\n\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_RATE, value: requestsPerSec });\r\n\r\n // Only send duration to live metrics if it has been updated!\r\n if (!this._enableLiveMetricsCounters || intervalRequests > 0) {\r\n this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_DURATION, value: averageRequestExecutionTime });\r\n }\r\n\r\n // Only supported by quickpulse service\r\n if (this._enableLiveMetricsCounters) {\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.REQUEST_FAILURE_RATE, value: failedRequestsPerSec });\r\n }\r\n }\r\n\r\n this._lastRequests = requests;\r\n }\r\n\r\n // Static counter is accumulated externally. Report the rate to client here\r\n // Note: This is currently only used with QuickPulse client\r\n private _trackDependencyRate() {\r\n if (this._enableLiveMetricsCounters) {\r\n var lastDependencies = this._lastDependencies;\r\n var dependencies = {\r\n totalDependencyCount: AutoCollectPerformance._totalDependencyCount,\r\n totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount,\r\n time: +new Date\r\n };\r\n\r\n var intervalDependencies = (dependencies.totalDependencyCount - lastDependencies.totalDependencyCount) || 0;\r\n var intervalFailedDependencies = (dependencies.totalFailedDependencyCount - lastDependencies.totalFailedDependencyCount) || 0;\r\n var elapsedMs = dependencies.time - lastDependencies.time;\r\n var elapsedSeconds = elapsedMs / 1000;\r\n var averageDependencyExecutionTime = ((AutoCollectPerformance._intervalDependencyExecutionTime - this._lastIntervalDependencyExecutionTime) / intervalDependencies) || 0;\r\n this._lastIntervalDependencyExecutionTime = AutoCollectPerformance._intervalDependencyExecutionTime // reset\r\n\r\n if (elapsedMs > 0) {\r\n var dependenciesPerSec = intervalDependencies / elapsedSeconds;\r\n var failedDependenciesPerSec = intervalFailedDependencies / elapsedSeconds;\r\n\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_RATE, value: dependenciesPerSec });\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_FAILURE_RATE, value: failedDependenciesPerSec });\r\n\r\n // redundant check for livemetrics, but kept for consistency w/ requests\r\n // Only send duration to live metrics if it has been updated!\r\n if (!this._enableLiveMetricsCounters || intervalDependencies > 0) {\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_DURATION, value: averageDependencyExecutionTime });\r\n }\r\n }\r\n this._lastDependencies = dependencies;\r\n }\r\n }\r\n\r\n // Static counter is accumulated externally. Report the rate to client here\r\n // Note: This is currently only used with QuickPulse client\r\n private _trackExceptionRate() {\r\n if (this._enableLiveMetricsCounters) {\r\n var lastExceptions = this._lastExceptions;\r\n var exceptions = {\r\n totalExceptionCount: AutoCollectPerformance._totalExceptionCount,\r\n time: +new Date\r\n };\r\n\r\n var intervalExceptions = (exceptions.totalExceptionCount - lastExceptions.totalExceptionCount) || 0;\r\n var elapsedMs = exceptions.time - lastExceptions.time;\r\n var elapsedSeconds = elapsedMs / 1000;\r\n\r\n if (elapsedMs > 0) {\r\n var exceptionsPerSec = intervalExceptions / elapsedSeconds;\r\n this._client.trackMetric({ name: Constants.QuickPulseCounter.EXCEPTION_RATE, value: exceptionsPerSec });\r\n }\r\n this._lastExceptions = exceptions;\r\n }\r\n }\r\n\r\n public dispose() {\r\n AutoCollectPerformance.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\nexport = AutoCollectPerformance;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.d.ts b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.d.ts new file mode 100644 index 0000000..ab6e4e2 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.d.ts @@ -0,0 +1,35 @@ +import TelemetryClient = require("../Library/TelemetryClient"); +import { MetricDependencyDimensions, MetricExceptionDimensions, MetricRequestDimensions, MetricTraceDimensions } from "../Declarations/Metrics/AggregatedMetricDimensions"; +declare class AutoCollectPreAggregatedMetrics { + static INSTANCE: AutoCollectPreAggregatedMetrics; + private _collectionInterval; + private _client; + private _handle; + private _isEnabled; + private _isInitialized; + private static _dependencyCountersCollection; + private static _requestCountersCollection; + private static _exceptionCountersCollection; + private static _traceCountersCollection; + /** + * @param client - Telemetry Client + * @param collectionInterval - Metric collection interval in ms + */ + constructor(client: TelemetryClient, collectionInterval?: number); + enable(isEnabled: boolean, collectionInterval?: number): void; + static countException(dimensions: MetricExceptionDimensions): void; + static countTrace(dimensions: MetricTraceDimensions): void; + static countRequest(duration: number | string, dimensions: MetricRequestDimensions): void; + static countDependency(duration: number | string, dimensions: MetricDependencyDimensions): void; + isInitialized(): boolean; + static isEnabled(): boolean; + trackPreAggregatedMetrics(): void; + private static _getAggregatedCounter; + private _trackRequestMetrics; + private _trackDependencyMetrics; + private _trackExceptionMetrics; + private _trackTraceMetrics; + private _trackPreAggregatedMetric; + dispose(): void; +} +export = AutoCollectPreAggregatedMetrics; diff --git a/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js new file mode 100644 index 0000000..7763424 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js @@ -0,0 +1,259 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var Constants = require("../Declarations/Constants"); +var AggregatedMetricCounters_1 = require("../Declarations/Metrics/AggregatedMetricCounters"); +var AggregatedMetricDimensions_1 = require("../Declarations/Metrics/AggregatedMetricDimensions"); +var AutoCollectPreAggregatedMetrics = /** @class */ (function () { + /** + * @param client - Telemetry Client + * @param collectionInterval - Metric collection interval in ms + */ + function AutoCollectPreAggregatedMetrics(client, collectionInterval) { + if (collectionInterval === void 0) { collectionInterval = 60000; } + if (!AutoCollectPreAggregatedMetrics.INSTANCE) { + AutoCollectPreAggregatedMetrics.INSTANCE = this; + } + this._isInitialized = false; + AutoCollectPreAggregatedMetrics._dependencyCountersCollection = []; + AutoCollectPreAggregatedMetrics._requestCountersCollection = []; + AutoCollectPreAggregatedMetrics._exceptionCountersCollection = []; + AutoCollectPreAggregatedMetrics._traceCountersCollection = []; + this._client = client; + this._collectionInterval = collectionInterval; + } + AutoCollectPreAggregatedMetrics.prototype.enable = function (isEnabled, collectionInterval) { + var _this = this; + this._isEnabled = isEnabled; + if (this._isEnabled && !this._isInitialized) { + this._isInitialized = true; + } + if (isEnabled) { + if (!this._handle) { + this._collectionInterval = collectionInterval || this._collectionInterval; + this._handle = setInterval(function () { return _this.trackPreAggregatedMetrics(); }, this._collectionInterval); + this._handle.unref(); // Allow the app to terminate even while this loop is going on + } + } + else { + if (this._handle) { + clearInterval(this._handle); + this._handle = undefined; + } + } + }; + AutoCollectPreAggregatedMetrics.countException = function (dimensions) { + if (!AutoCollectPreAggregatedMetrics.isEnabled()) { + return; + } + var counter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._exceptionCountersCollection); + counter.totalCount++; + }; + AutoCollectPreAggregatedMetrics.countTrace = function (dimensions) { + if (!AutoCollectPreAggregatedMetrics.isEnabled()) { + return; + } + var counter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._traceCountersCollection); + counter.totalCount++; + }; + AutoCollectPreAggregatedMetrics.countRequest = function (duration, dimensions) { + if (!AutoCollectPreAggregatedMetrics.isEnabled()) { + return; + } + var durationMs; + var counter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._requestCountersCollection); + if (typeof duration === "string") { + // dependency duration is passed in as "00:00:00.123" by autocollectors + durationMs = +new Date("1970-01-01T" + duration + "Z"); // convert to num ms, returns NaN if wrong + } + else if (typeof duration === "number") { + durationMs = duration; + } + else { + return; + } + counter.intervalExecutionTime += durationMs; + counter.totalCount++; + }; + AutoCollectPreAggregatedMetrics.countDependency = function (duration, dimensions) { + if (!AutoCollectPreAggregatedMetrics.isEnabled()) { + return; + } + var counter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._dependencyCountersCollection); + var durationMs; + if (typeof duration === "string") { + // dependency duration is passed in as "00:00:00.123" by autocollectors + durationMs = +new Date("1970-01-01T" + duration + "Z"); // convert to num ms, returns NaN if wrong + } + else if (typeof duration === "number") { + durationMs = duration; + } + else { + return; + } + counter.intervalExecutionTime += durationMs; + counter.totalCount++; + }; + AutoCollectPreAggregatedMetrics.prototype.isInitialized = function () { + return this._isInitialized; + }; + AutoCollectPreAggregatedMetrics.isEnabled = function () { + return AutoCollectPreAggregatedMetrics.INSTANCE && AutoCollectPreAggregatedMetrics.INSTANCE._isEnabled; + }; + AutoCollectPreAggregatedMetrics.prototype.trackPreAggregatedMetrics = function () { + this._trackRequestMetrics(); + this._trackDependencyMetrics(); + this._trackExceptionMetrics(); + this._trackTraceMetrics(); + }; + AutoCollectPreAggregatedMetrics._getAggregatedCounter = function (dimensions, counterCollection) { + var notMatch = false; + // Check if counter with specified dimensions is available + for (var i = 0; i < counterCollection.length; i++) { + // Same object + if (dimensions === counterCollection[i].dimensions) { + return counterCollection[i]; + } + // Diferent number of keys skip + if (Object.keys(dimensions).length !== Object.keys(counterCollection[i].dimensions).length) { + continue; + } + // Check dimension values + for (var dim in dimensions) { + if (dimensions[dim] != counterCollection[i].dimensions[dim]) { + notMatch = true; + break; + } + } + if (!notMatch) { // Found + return counterCollection[i]; + } + notMatch = false; + } + // Create a new one if not found + var newCounter = new AggregatedMetricCounters_1.AggregatedMetricCounter(dimensions); + counterCollection.push(newCounter); + return newCounter; + }; + AutoCollectPreAggregatedMetrics.prototype._trackRequestMetrics = function () { + for (var i = 0; i < AutoCollectPreAggregatedMetrics._requestCountersCollection.length; i++) { + var currentCounter = AutoCollectPreAggregatedMetrics._requestCountersCollection[i]; + currentCounter.time = +new Date; + var intervalRequests = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0; + var elapsedMs = currentCounter.time - currentCounter.lastTime; + var averageRequestExecutionTime = ((currentCounter.intervalExecutionTime - currentCounter.lastIntervalExecutionTime) / intervalRequests) || 0; + currentCounter.lastIntervalExecutionTime = currentCounter.intervalExecutionTime; // reset + if (elapsedMs > 0 && intervalRequests > 0) { + this._trackPreAggregatedMetric({ + name: "Server response time", + dimensions: currentCounter.dimensions, + value: averageRequestExecutionTime, + count: intervalRequests, + aggregationInterval: elapsedMs, + metricType: Constants.MetricId.REQUESTS_DURATION + }); + } + // Set last counters + currentCounter.lastTotalCount = currentCounter.totalCount; + currentCounter.lastTime = currentCounter.time; + } + }; + AutoCollectPreAggregatedMetrics.prototype._trackDependencyMetrics = function () { + for (var i = 0; i < AutoCollectPreAggregatedMetrics._dependencyCountersCollection.length; i++) { + var currentCounter = AutoCollectPreAggregatedMetrics._dependencyCountersCollection[i]; + currentCounter.time = +new Date; + var intervalDependencies = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0; + var elapsedMs = currentCounter.time - currentCounter.lastTime; + var averageDependencyExecutionTime = ((currentCounter.intervalExecutionTime - currentCounter.lastIntervalExecutionTime) / intervalDependencies) || 0; + currentCounter.lastIntervalExecutionTime = currentCounter.intervalExecutionTime; // reset + if (elapsedMs > 0 && intervalDependencies > 0) { + this._trackPreAggregatedMetric({ + name: "Dependency duration", + dimensions: currentCounter.dimensions, + value: averageDependencyExecutionTime, + count: intervalDependencies, + aggregationInterval: elapsedMs, + metricType: Constants.MetricId.DEPENDENCIES_DURATION + }); + } + // Set last counters + currentCounter.lastTotalCount = currentCounter.totalCount; + currentCounter.lastTime = currentCounter.time; + } + }; + AutoCollectPreAggregatedMetrics.prototype._trackExceptionMetrics = function () { + for (var i = 0; i < AutoCollectPreAggregatedMetrics._exceptionCountersCollection.length; i++) { + var currentCounter = AutoCollectPreAggregatedMetrics._exceptionCountersCollection[i]; + currentCounter.time = +new Date; + var intervalExceptions = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0; + var elapsedMs = currentCounter.time - currentCounter.lastTime; + if (elapsedMs > 0 && intervalExceptions > 0) { + this._trackPreAggregatedMetric({ + name: "Exceptions", + dimensions: currentCounter.dimensions, + value: intervalExceptions, + count: intervalExceptions, + aggregationInterval: elapsedMs, + metricType: Constants.MetricId.EXCEPTIONS_COUNT + }); + } + // Set last counters + currentCounter.lastTotalCount = currentCounter.totalCount; + currentCounter.lastTime = currentCounter.time; + } + }; + AutoCollectPreAggregatedMetrics.prototype._trackTraceMetrics = function () { + for (var i = 0; i < AutoCollectPreAggregatedMetrics._traceCountersCollection.length; i++) { + var currentCounter = AutoCollectPreAggregatedMetrics._traceCountersCollection[i]; + currentCounter.time = +new Date; + var intervalTraces = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0; + var elapsedMs = currentCounter.time - currentCounter.lastTime; + if (elapsedMs > 0 && intervalTraces > 0) { + this._trackPreAggregatedMetric({ + name: "Traces", + dimensions: currentCounter.dimensions, + value: intervalTraces, + count: intervalTraces, + aggregationInterval: elapsedMs, + metricType: Constants.MetricId.TRACES_COUNT + }); + } + // Set last counters + currentCounter.lastTotalCount = currentCounter.totalCount; + currentCounter.lastTime = currentCounter.time; + } + }; + AutoCollectPreAggregatedMetrics.prototype._trackPreAggregatedMetric = function (metric) { + // Build metric properties + var metricProperties = {}; + for (var dim in metric.dimensions) { + metricProperties[AggregatedMetricDimensions_1.PreaggregatedMetricPropertyNames[dim]] = metric.dimensions[dim]; + } + metricProperties = __assign(__assign({}, metricProperties), { "_MS.MetricId": metric.metricType, "_MS.AggregationIntervalMs": String(metric.aggregationInterval), "_MS.IsAutocollected": "True" }); + var telemetry = { + name: metric.name, + value: metric.value, + count: metric.count, + properties: metricProperties, + kind: "Aggregation" + }; + this._client.trackMetric(telemetry); + }; + AutoCollectPreAggregatedMetrics.prototype.dispose = function () { + AutoCollectPreAggregatedMetrics.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + return AutoCollectPreAggregatedMetrics; +}()); +module.exports = AutoCollectPreAggregatedMetrics; +//# sourceMappingURL=PreAggregatedMetrics.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js.map b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js.map new file mode 100644 index 0000000..c49691f --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/PreAggregatedMetrics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PreAggregatedMetrics.js","sourceRoot":"","sources":["../../AutoCollection/PreAggregatedMetrics.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAwD;AAGxD,6FAA2F;AAC3F,iGAQ4D;AAI5D;IAcI;;;OAGG;IACH,yCAAY,MAAuB,EAAE,kBAA0B;QAA1B,mCAAA,EAAA,0BAA0B;QAC3D,IAAI,CAAC,+BAA+B,CAAC,QAAQ,EAAE;YAC3C,+BAA+B,CAAC,QAAQ,GAAG,IAAI,CAAC;SACnD;QAED,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;QAC5B,+BAA+B,CAAC,6BAA6B,GAAG,EAAE,CAAC;QACnE,+BAA+B,CAAC,0BAA0B,GAAG,EAAE,CAAC;QAChE,+BAA+B,CAAC,4BAA4B,GAAG,EAAE,CAAC;QAClE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,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;IAEM,iDAAO,GAAd;QACI,+BAA+B,CAAC,QAAQ,GAAG,IAAI,CAAC;QAChD,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IACL,sCAAC;AAAD,CAAC,AA7QD,IA6QC;AAED,iBAAS,+BAA+B,CAAC","sourcesContent":["import TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\n\r\nimport { AggregatedMetric } from \"../Declarations/Metrics/AggregatedMetric\";\r\nimport { AggregatedMetricCounter } from \"../Declarations/Metrics/AggregatedMetricCounters\";\r\nimport {\r\n MetricBaseDimensions,\r\n MetricDependencyDimensions,\r\n MetricExceptionDimensions,\r\n MetricRequestDimensions,\r\n MetricTraceDimensions,\r\n PreaggregatedMetricPropertyNames,\r\n MetricDimensionTypeKeys\r\n} from \"../Declarations/Metrics/AggregatedMetricDimensions\";\r\nimport * as Contracts from \"../Declarations/Contracts\";\r\n\r\n\r\nclass AutoCollectPreAggregatedMetrics {\r\n\r\n public static INSTANCE: AutoCollectPreAggregatedMetrics;\r\n private _collectionInterval: number;\r\n private _client: TelemetryClient;\r\n private _handle: NodeJS.Timer;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n\r\n private static _dependencyCountersCollection: Array;\r\n private static _requestCountersCollection: Array;\r\n private static _exceptionCountersCollection: Array;\r\n private static _traceCountersCollection: Array;\r\n\r\n /**\r\n * @param client - Telemetry Client\r\n * @param collectionInterval - Metric collection interval in ms\r\n */\r\n constructor(client: TelemetryClient, collectionInterval = 60000) {\r\n if (!AutoCollectPreAggregatedMetrics.INSTANCE) {\r\n AutoCollectPreAggregatedMetrics.INSTANCE = this;\r\n }\r\n\r\n this._isInitialized = false;\r\n AutoCollectPreAggregatedMetrics._dependencyCountersCollection = [];\r\n AutoCollectPreAggregatedMetrics._requestCountersCollection = [];\r\n AutoCollectPreAggregatedMetrics._exceptionCountersCollection = [];\r\n AutoCollectPreAggregatedMetrics._traceCountersCollection = [];\r\n this._client = client;\r\n this._collectionInterval = collectionInterval;\r\n }\r\n\r\n public enable(isEnabled: boolean, collectionInterval?: number) {\r\n this._isEnabled = isEnabled;\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._isInitialized = true;\r\n }\r\n\r\n if (isEnabled) {\r\n if (!this._handle) {\r\n this._collectionInterval = collectionInterval || this._collectionInterval;\r\n this._handle = setInterval(() => this.trackPreAggregatedMetrics(), this._collectionInterval);\r\n this._handle.unref(); // Allow the app to terminate even while this loop is going on\r\n }\r\n } else {\r\n if (this._handle) {\r\n clearInterval(this._handle);\r\n this._handle = undefined;\r\n }\r\n }\r\n }\r\n\r\n public static countException(dimensions: MetricExceptionDimensions) {\r\n if (!AutoCollectPreAggregatedMetrics.isEnabled()) {\r\n return;\r\n }\r\n let counter: AggregatedMetricCounter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._exceptionCountersCollection);\r\n counter.totalCount++;\r\n }\r\n\r\n public static countTrace(dimensions: MetricTraceDimensions) {\r\n if (!AutoCollectPreAggregatedMetrics.isEnabled()) {\r\n return;\r\n }\r\n let counter: AggregatedMetricCounter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._traceCountersCollection);\r\n counter.totalCount++;\r\n }\r\n\r\n public static countRequest(duration: number | string, dimensions: MetricRequestDimensions) {\r\n if (!AutoCollectPreAggregatedMetrics.isEnabled()) {\r\n return;\r\n }\r\n let durationMs: number;\r\n let counter: AggregatedMetricCounter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._requestCountersCollection);\r\n if (typeof duration === \"string\") {\r\n // dependency duration is passed in as \"00:00:00.123\" by autocollectors\r\n durationMs = +new Date(\"1970-01-01T\" + duration + \"Z\"); // convert to num ms, returns NaN if wrong\r\n } else if (typeof duration === \"number\") {\r\n durationMs = duration;\r\n } else {\r\n return;\r\n }\r\n counter.intervalExecutionTime += durationMs;\r\n counter.totalCount++;\r\n }\r\n\r\n public static countDependency(duration: number | string, dimensions: MetricDependencyDimensions) {\r\n if (!AutoCollectPreAggregatedMetrics.isEnabled()) {\r\n return;\r\n }\r\n let counter: AggregatedMetricCounter = AutoCollectPreAggregatedMetrics._getAggregatedCounter(dimensions, this._dependencyCountersCollection);\r\n let durationMs: number;\r\n if (typeof duration === \"string\") {\r\n // dependency duration is passed in as \"00:00:00.123\" by autocollectors\r\n durationMs = +new Date(\"1970-01-01T\" + duration + \"Z\"); // convert to num ms, returns NaN if wrong\r\n } else if (typeof duration === \"number\") {\r\n durationMs = duration;\r\n } else {\r\n return;\r\n }\r\n counter.intervalExecutionTime += durationMs;\r\n counter.totalCount++;\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public static isEnabled() {\r\n return AutoCollectPreAggregatedMetrics.INSTANCE && AutoCollectPreAggregatedMetrics.INSTANCE._isEnabled;\r\n }\r\n\r\n public trackPreAggregatedMetrics() {\r\n this._trackRequestMetrics();\r\n this._trackDependencyMetrics();\r\n this._trackExceptionMetrics();\r\n this._trackTraceMetrics();\r\n }\r\n\r\n private static _getAggregatedCounter(dimensions: MetricBaseDimensions, counterCollection: Array): AggregatedMetricCounter {\r\n let notMatch = false;\r\n // Check if counter with specified dimensions is available\r\n for (let i = 0; i < counterCollection.length; i++) {\r\n // Same object\r\n if (dimensions === counterCollection[i].dimensions) {\r\n return counterCollection[i];\r\n }\r\n // Diferent number of keys skip\r\n if (Object.keys(dimensions).length !== Object.keys(counterCollection[i].dimensions).length) {\r\n continue;\r\n }\r\n // Check dimension values\r\n for (let dim in dimensions) {\r\n if ((dimensions)[dim] != (counterCollection[i].dimensions)[dim]) {\r\n notMatch = true;\r\n break;\r\n }\r\n }\r\n if (!notMatch) { // Found\r\n return counterCollection[i];\r\n }\r\n notMatch = false;\r\n }\r\n // Create a new one if not found\r\n let newCounter = new AggregatedMetricCounter(dimensions);\r\n counterCollection.push(newCounter);\r\n return newCounter;\r\n }\r\n\r\n private _trackRequestMetrics() {\r\n for (let i = 0; i < AutoCollectPreAggregatedMetrics._requestCountersCollection.length; i++) {\r\n var currentCounter = AutoCollectPreAggregatedMetrics._requestCountersCollection[i];\r\n currentCounter.time = +new Date;\r\n var intervalRequests = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0;\r\n var elapsedMs = currentCounter.time - currentCounter.lastTime;\r\n var averageRequestExecutionTime = ((currentCounter.intervalExecutionTime - currentCounter.lastIntervalExecutionTime) / intervalRequests) || 0;\r\n currentCounter.lastIntervalExecutionTime = currentCounter.intervalExecutionTime; // reset\r\n if (elapsedMs > 0 && intervalRequests > 0) {\r\n this._trackPreAggregatedMetric({\r\n name: \"Server response time\",\r\n dimensions: currentCounter.dimensions,\r\n value: averageRequestExecutionTime,\r\n count: intervalRequests,\r\n aggregationInterval: elapsedMs,\r\n metricType: Constants.MetricId.REQUESTS_DURATION\r\n });\r\n }\r\n // Set last counters\r\n currentCounter.lastTotalCount = currentCounter.totalCount;\r\n currentCounter.lastTime = currentCounter.time;\r\n }\r\n }\r\n\r\n private _trackDependencyMetrics() {\r\n for (let i = 0; i < AutoCollectPreAggregatedMetrics._dependencyCountersCollection.length; i++) {\r\n var currentCounter = AutoCollectPreAggregatedMetrics._dependencyCountersCollection[i];\r\n currentCounter.time = +new Date;\r\n var intervalDependencies = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0;\r\n var elapsedMs = currentCounter.time - currentCounter.lastTime;\r\n var averageDependencyExecutionTime = ((currentCounter.intervalExecutionTime - currentCounter.lastIntervalExecutionTime) / intervalDependencies) || 0;\r\n currentCounter.lastIntervalExecutionTime = currentCounter.intervalExecutionTime; // reset\r\n if (elapsedMs > 0 && intervalDependencies > 0) {\r\n this._trackPreAggregatedMetric({\r\n name: \"Dependency duration\",\r\n dimensions: currentCounter.dimensions,\r\n value: averageDependencyExecutionTime,\r\n count: intervalDependencies,\r\n aggregationInterval: elapsedMs,\r\n metricType: Constants.MetricId.DEPENDENCIES_DURATION\r\n });\r\n }\r\n // Set last counters\r\n currentCounter.lastTotalCount = currentCounter.totalCount;\r\n currentCounter.lastTime = currentCounter.time;\r\n }\r\n }\r\n\r\n private _trackExceptionMetrics() {\r\n for (let i = 0; i < AutoCollectPreAggregatedMetrics._exceptionCountersCollection.length; i++) {\r\n var currentCounter = AutoCollectPreAggregatedMetrics._exceptionCountersCollection[i];\r\n currentCounter.time = +new Date;\r\n var intervalExceptions = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0;\r\n var elapsedMs = currentCounter.time - currentCounter.lastTime;\r\n if (elapsedMs > 0 && intervalExceptions > 0) {\r\n this._trackPreAggregatedMetric({\r\n name: \"Exceptions\",\r\n dimensions: currentCounter.dimensions,\r\n value: intervalExceptions,\r\n count: intervalExceptions,\r\n aggregationInterval: elapsedMs,\r\n metricType: Constants.MetricId.EXCEPTIONS_COUNT\r\n });\r\n }\r\n // Set last counters\r\n currentCounter.lastTotalCount = currentCounter.totalCount;\r\n currentCounter.lastTime = currentCounter.time;\r\n }\r\n }\r\n\r\n private _trackTraceMetrics() {\r\n for (let i = 0; i < AutoCollectPreAggregatedMetrics._traceCountersCollection.length; i++) {\r\n var currentCounter = AutoCollectPreAggregatedMetrics._traceCountersCollection[i];\r\n currentCounter.time = +new Date;\r\n var intervalTraces = (currentCounter.totalCount - currentCounter.lastTotalCount) || 0;\r\n var elapsedMs = currentCounter.time - currentCounter.lastTime;\r\n if (elapsedMs > 0 && intervalTraces > 0) {\r\n this._trackPreAggregatedMetric({\r\n name: \"Traces\",\r\n dimensions: currentCounter.dimensions,\r\n value: intervalTraces,\r\n count: intervalTraces,\r\n aggregationInterval: elapsedMs,\r\n metricType: Constants.MetricId.TRACES_COUNT\r\n });\r\n }\r\n // Set last counters\r\n currentCounter.lastTotalCount = currentCounter.totalCount;\r\n currentCounter.lastTime = currentCounter.time;\r\n }\r\n }\r\n\r\n private _trackPreAggregatedMetric(metric: AggregatedMetric) {\r\n // Build metric properties\r\n let metricProperties: any = {};\r\n for (let dim in metric.dimensions) {\r\n metricProperties[PreaggregatedMetricPropertyNames[dim as MetricDimensionTypeKeys]] = metric.dimensions[dim];\r\n }\r\n metricProperties = {\r\n ...metricProperties,\r\n \"_MS.MetricId\": metric.metricType,\r\n \"_MS.AggregationIntervalMs\": String(metric.aggregationInterval),\r\n \"_MS.IsAutocollected\": \"True\"\r\n };\r\n\r\n let telemetry: Contracts.MetricTelemetry = {\r\n name: metric.name,\r\n value: metric.value,\r\n count: metric.count,\r\n properties: metricProperties,\r\n kind: \"Aggregation\"\r\n };\r\n this._client.trackMetric(telemetry);\r\n }\r\n\r\n public dispose() {\r\n AutoCollectPreAggregatedMetrics.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\nexport = AutoCollectPreAggregatedMetrics;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/RequestParser.d.ts b/node_modules/applicationinsights/out/AutoCollection/RequestParser.d.ts new file mode 100644 index 0000000..6821155 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/RequestParser.d.ts @@ -0,0 +1,22 @@ +/** + * Base class for helpers that read data from HTTP request/response objects and convert them + * into the telemetry contract objects. + */ +declare abstract class RequestParser { + protected method: string; + protected url: string; + protected startTime: number; + protected duration: number; + protected statusCode: number; + protected properties: { + [key: string]: string; + }; + /** + * Gets a url parsed out from request options + */ + getUrl(): string; + protected RequestParser(): void; + protected _setStatus(status: number, error: Error | string): void; + protected _isSuccess(): boolean; +} +export = RequestParser; diff --git a/node_modules/applicationinsights/out/AutoCollection/RequestParser.js b/node_modules/applicationinsights/out/AutoCollection/RequestParser.js new file mode 100644 index 0000000..cc17c78 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/RequestParser.js @@ -0,0 +1,44 @@ +"use strict"; +/** + * Base class for helpers that read data from HTTP request/response objects and convert them + * into the telemetry contract objects. + */ +var RequestParser = /** @class */ (function () { + function RequestParser() { + } + /** + * Gets a url parsed out from request options + */ + RequestParser.prototype.getUrl = function () { + return this.url; + }; + RequestParser.prototype.RequestParser = function () { + this.startTime = +new Date(); + }; + RequestParser.prototype._setStatus = function (status, error) { + var endTime = +new Date(); + this.duration = endTime - this.startTime; + this.statusCode = status; + var properties = this.properties || {}; + if (error) { + if (typeof error === "string") { + properties["error"] = error; + } + else if (error instanceof Error) { + properties["error"] = error.message; + } + else if (typeof error === "object") { + for (var key in error) { + properties[key] = error[key] && error[key].toString && error[key].toString(); + } + } + } + this.properties = properties; + }; + RequestParser.prototype._isSuccess = function () { + return (0 < this.statusCode) && (this.statusCode < 400); + }; + return RequestParser; +}()); +module.exports = RequestParser; +//# sourceMappingURL=RequestParser.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/RequestParser.js.map b/node_modules/applicationinsights/out/AutoCollection/RequestParser.js.map new file mode 100644 index 0000000..33f8362 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/RequestParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RequestParser.js","sourceRoot":"","sources":["../../AutoCollection/RequestParser.ts"],"names":[],"mappings":";AAAA;;;GAGG;AACH;IAAA;IA2CA,CAAC;IAnCG;;OAEG;IACI,8BAAM,GAAb;QACI,OAAO,IAAI,CAAC,GAAG,CAAC;IACpB,CAAC;IAES,qCAAa,GAAvB;QACI,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC;IACjC,CAAC;IAES,kCAAU,GAApB,UAAqB,MAAc,EAAE,KAAqB;QACtD,IAAI,OAAO,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC;QACzC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC;QAEzB,IAAI,UAAU,GAA4B,IAAI,CAAC,UAAU,IAAI,EAAE,CAAC;QAChE,IAAI,KAAK,EAAE;YACP,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;gBAC3B,UAAU,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC;aAC/B;iBAAM,IAAI,KAAK,YAAY,KAAK,EAAE;gBAC/B,UAAU,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC;aACvC;iBAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;gBAClC,KAAK,IAAI,GAAG,IAAS,KAAK,EAAE;oBACxB,UAAU,CAAC,GAAG,CAAC,GAAS,KAAM,CAAC,GAAG,CAAC,IAAU,KAAM,CAAC,GAAG,CAAC,CAAC,QAAQ,IAAU,KAAM,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC;iBACrG;aACJ;SACJ;QAED,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IACjC,CAAC;IAES,kCAAU,GAApB;QACI,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,CAAC;IAC5D,CAAC;IACL,oBAAC;AAAD,CAAC,AA3CD,IA2CC;AAED,iBAAS,aAAa,CAAC","sourcesContent":["/**\r\n * Base class for helpers that read data from HTTP request/response objects and convert them\r\n * into the telemetry contract objects.\r\n */\r\nabstract class RequestParser {\r\n protected method: string;\r\n protected url: string;\r\n protected startTime: number;\r\n protected duration: number;\r\n protected statusCode: number;\r\n protected properties: { [key: string]: string };\r\n\r\n /**\r\n * Gets a url parsed out from request options\r\n */\r\n public getUrl(): string {\r\n return this.url;\r\n }\r\n\r\n protected RequestParser() {\r\n this.startTime = +new Date();\r\n }\r\n\r\n protected _setStatus(status: number, error: Error | string) {\r\n let endTime = +new Date();\r\n this.duration = endTime - this.startTime;\r\n this.statusCode = status;\r\n\r\n let properties: {[key: string]: string} = this.properties || {};\r\n if (error) {\r\n if (typeof error === \"string\") {\r\n properties[\"error\"] = error;\r\n } else if (error instanceof Error) {\r\n properties[\"error\"] = error.message;\r\n } else if (typeof error === \"object\") {\r\n for (var key in error) {\r\n properties[key] = (error)[key] && (error)[key].toString && (error)[key].toString();\r\n }\r\n }\r\n }\r\n\r\n this.properties = properties;\r\n }\r\n\r\n protected _isSuccess() {\r\n return (0 < this.statusCode) && (this.statusCode < 400);\r\n }\r\n}\r\n\r\nexport = RequestParser;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Statsbeat.d.ts b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.d.ts new file mode 100644 index 0000000..d46c2d4 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.d.ts @@ -0,0 +1,56 @@ +import Constants = require("../Declarations/Constants"); +import Config = require("../Library/Config"); +import Context = require("../Library/Context"); +declare class Statsbeat { + static NON_EU_CONNECTION_STRING: string; + static EU_CONNECTION_STRING: string; + static STATS_COLLECTION_SHORT_INTERVAL: number; + static STATS_COLLECTION_LONG_INTERVAL: number; + private static TAG; + private _networkStatsbeatCollection; + private _sender; + private _context; + private _handle; + private _longHandle; + private _isEnabled; + private _isInitialized; + private _config; + private _statsbeatConfig; + private _isVM; + private _statbeatMetrics; + private _resourceProvider; + private _resourceIdentifier; + private _sdkVersion; + private _runtimeVersion; + private _os; + private _language; + private _cikey; + private _attach; + private _feature; + private _instrumentation; + constructor(config: Config, context?: Context); + enable(isEnabled: boolean): void; + isInitialized(): boolean; + isEnabled(): boolean; + setCodelessAttach(): void; + addFeature(feature: Constants.StatsbeatFeature): void; + removeFeature(feature: Constants.StatsbeatFeature): void; + addInstrumentation(instrumentation: Constants.StatsbeatInstrumentation): void; + removeInstrumentation(instrumentation: Constants.StatsbeatInstrumentation): void; + countRequest(endpoint: number, host: string, duration: number, success: boolean, statusCode?: number): void; + countException(endpoint: number, host: string, exceptionType: Error): void; + countThrottle(endpoint: number, host: string, statusCode: number): void; + countRetry(endpoint: number, host: string, statusCode: number): void; + trackShortIntervalStatsbeats(): Promise; + trackLongIntervalStatsbeats(): Promise; + private _getNetworkStatsbeatCounter; + private _trackRequestDuration; + private _getShortHost; + private _trackRequestsCount; + private _sendStatsbeats; + private _getCustomProperties; + private _getResourceProvider; + private _shutdownStatsbeat; + private _getConnectionString; +} +export = Statsbeat; diff --git a/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js new file mode 100644 index 0000000..d0d0ffa --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js @@ -0,0 +1,501 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var os = require("os"); +var EnvelopeFactory = require("../Library/EnvelopeFactory"); +var Logging = require("../Library/Logging"); +var Sender = require("../Library/Sender"); +var Constants = require("../Declarations/Constants"); +var Contracts = require("../Declarations/Contracts"); +var Vm = require("../Library/AzureVirtualMachine"); +var Config = require("../Library/Config"); +var Context = require("../Library/Context"); +var Network = require("./NetworkStatsbeat"); +var Util = require("../Library/Util"); +var STATSBEAT_LANGUAGE = "node"; +var Statsbeat = /** @class */ (function () { + function Statsbeat(config, context) { + this._attach = Constants.StatsbeatAttach.sdk; // Default is SDK + this._feature = Constants.StatsbeatFeature.NONE; + this._instrumentation = Constants.StatsbeatInstrumentation.NONE; + this._isInitialized = false; + this._statbeatMetrics = []; + this._networkStatsbeatCollection = []; + this._config = config; + this._context = context || new Context(); + var statsbeatConnectionString = this._getConnectionString(config); + this._statsbeatConfig = new Config(statsbeatConnectionString); + this._statsbeatConfig.samplingPercentage = 100; // Do not sample + this._sender = new Sender(this._statsbeatConfig, null, null, null, null, true, this._shutdownStatsbeat.bind(this)); + } + Statsbeat.prototype.enable = function (isEnabled) { + var _this = this; + this._isEnabled = isEnabled; + if (this._isEnabled && !this._isInitialized) { + this._getCustomProperties(); + this._isInitialized = true; + } + if (isEnabled) { + if (!this._handle) { + this._handle = setInterval(function () { + _this.trackShortIntervalStatsbeats(); + }, Statsbeat.STATS_COLLECTION_SHORT_INTERVAL); + this._handle.unref(); // Allow the app to terminate even while this loop is going on + } + if (!this._longHandle) { + // On first enablement + this.trackLongIntervalStatsbeats(); + this._longHandle = setInterval(function () { + _this.trackLongIntervalStatsbeats(); + }, Statsbeat.STATS_COLLECTION_LONG_INTERVAL); + this._longHandle.unref(); // Allow the app to terminate even while this loop is going on + } + } + else { + if (this._handle) { + clearInterval(this._handle); + this._handle = null; + } + if (this._longHandle) { + clearInterval(this._longHandle); + this._longHandle = null; + } + } + }; + Statsbeat.prototype.isInitialized = function () { + return this._isInitialized; + }; + Statsbeat.prototype.isEnabled = function () { + return this._isEnabled; + }; + Statsbeat.prototype.setCodelessAttach = function () { + this._attach = Constants.StatsbeatAttach.codeless; + }; + Statsbeat.prototype.addFeature = function (feature) { + this._feature |= feature; + }; + Statsbeat.prototype.removeFeature = function (feature) { + this._feature &= ~feature; + }; + Statsbeat.prototype.addInstrumentation = function (instrumentation) { + this._instrumentation |= instrumentation; + }; + Statsbeat.prototype.removeInstrumentation = function (instrumentation) { + this._instrumentation &= ~instrumentation; + }; + Statsbeat.prototype.countRequest = function (endpoint, host, duration, success, statusCode) { + if (!this.isEnabled()) { + return; + } + var counter = this._getNetworkStatsbeatCounter(endpoint, host); + counter.totalRequestCount++; + counter.intervalRequestExecutionTime += duration; + if (success === false) { + if (!statusCode) { + return; + } + var currentStatusCounter = counter.totalFailedRequestCount.find(function (statusCounter) { return statusCode === statusCounter.statusCode; }); + if (currentStatusCounter) { + currentStatusCounter.count++; + } + else { + counter.totalFailedRequestCount.push({ statusCode: statusCode, count: 1 }); + } + } + else { + counter.totalSuccesfulRequestCount++; + } + }; + Statsbeat.prototype.countException = function (endpoint, host, exceptionType) { + if (!this.isEnabled()) { + return; + } + var counter = this._getNetworkStatsbeatCounter(endpoint, host); + var currentErrorCounter = counter.exceptionCount.find(function (exceptionCounter) { return exceptionType.name === exceptionCounter.exceptionType; }); + if (currentErrorCounter) { + currentErrorCounter.count++; + } + else { + counter.exceptionCount.push({ exceptionType: exceptionType.name, count: 1 }); + } + }; + Statsbeat.prototype.countThrottle = function (endpoint, host, statusCode) { + if (!this.isEnabled()) { + return; + } + var counter = this._getNetworkStatsbeatCounter(endpoint, host); + var currentStatusCounter = counter.throttleCount.find(function (statusCounter) { return statusCode === statusCounter.statusCode; }); + if (currentStatusCounter) { + currentStatusCounter.count++; + } + else { + counter.throttleCount.push({ statusCode: statusCode, count: 1 }); + } + }; + Statsbeat.prototype.countRetry = function (endpoint, host, statusCode) { + if (!this.isEnabled()) { + return; + } + var counter = this._getNetworkStatsbeatCounter(endpoint, host); + var currentStatusCounter = counter.retryCount.find(function (statusCounter) { return statusCode === statusCounter.statusCode; }); + if (currentStatusCounter) { + currentStatusCounter.count++; + } + else { + counter.retryCount.push({ statusCode: statusCode, count: 1 }); + } + }; + Statsbeat.prototype.trackShortIntervalStatsbeats = function () { + return __awaiter(this, void 0, void 0, function () { + var networkProperties, error_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, this._getResourceProvider()]; + case 1: + _a.sent(); + networkProperties = { + "os": this._os, + "rp": this._resourceProvider, + "cikey": this._cikey, + "runtimeVersion": this._runtimeVersion, + "language": this._language, + "version": this._sdkVersion, + "attach": this._attach + }; + this._trackRequestDuration(networkProperties); + this._trackRequestsCount(networkProperties); + return [4 /*yield*/, this._sendStatsbeats()]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + error_1 = _a.sent(); + Logging.info(Statsbeat.TAG, "Failed to send Statsbeat metrics: " + Util.dumpObj(error_1)); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + Statsbeat.prototype.trackLongIntervalStatsbeats = function () { + return __awaiter(this, void 0, void 0, function () { + var commonProperties, attachProperties, instrumentationProperties, featureProperties, error_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, this._getResourceProvider()]; + case 1: + _a.sent(); + commonProperties = { + "os": this._os, + "rp": this._resourceProvider, + "cikey": this._cikey, + "runtimeVersion": this._runtimeVersion, + "language": this._language, + "version": this._sdkVersion, + "attach": this._attach + }; + attachProperties = Object.assign({ + "rpId": this._resourceIdentifier + }, commonProperties); + this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.ATTACH, value: 1, properties: attachProperties }); + if (this._instrumentation != Constants.StatsbeatInstrumentation.NONE) { // Only send if there are some instrumentations enabled + instrumentationProperties = Object.assign({ "feature": this._instrumentation, "type": Constants.StatsbeatFeatureType.Instrumentation }, commonProperties); + this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.FEATURE, value: 1, properties: instrumentationProperties }); + } + if (this._feature != Constants.StatsbeatFeature.NONE) { // Only send if there are some features enabled + featureProperties = Object.assign({ "feature": this._feature, "type": Constants.StatsbeatFeatureType.Feature }, commonProperties); + this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.FEATURE, value: 1, properties: featureProperties }); + } + return [4 /*yield*/, this._sendStatsbeats()]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + error_2 = _a.sent(); + Logging.info(Statsbeat.TAG, "Failed to send Statsbeat metrics: " + Util.dumpObj(error_2)); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + Statsbeat.prototype._getNetworkStatsbeatCounter = function (endpoint, host) { + var shortHost = this._getShortHost(host); + // Check if counter is available + for (var i = 0; i < this._networkStatsbeatCollection.length; i++) { + // Same object + if (endpoint === this._networkStatsbeatCollection[i].endpoint && + shortHost === this._networkStatsbeatCollection[i].host) { + return this._networkStatsbeatCollection[i]; + } + } + // Create a new one if not found + var newCounter = new Network.NetworkStatsbeat(endpoint, shortHost); + this._networkStatsbeatCollection.push(newCounter); + return newCounter; + }; + Statsbeat.prototype._trackRequestDuration = function (commonProperties) { + for (var i = 0; i < this._networkStatsbeatCollection.length; i++) { + var currentCounter = this._networkStatsbeatCollection[i]; + currentCounter.time = +new Date; + var intervalRequests = (currentCounter.totalRequestCount - currentCounter.lastRequestCount) || 0; + var totalRequestExecutionTime = currentCounter.intervalRequestExecutionTime - currentCounter.lastIntervalRequestExecutionTime; + var averageRequestExecutionTime = totalRequestExecutionTime > 0 ? (totalRequestExecutionTime / intervalRequests) || 0 : 0; + currentCounter.lastIntervalRequestExecutionTime = currentCounter.intervalRequestExecutionTime; // reset + if (intervalRequests > 0) { + // Add extra properties + var properties = Object.assign({ + "endpoint": this._networkStatsbeatCollection[i].endpoint, + "host": this._networkStatsbeatCollection[i].host + }, commonProperties); + this._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.REQUEST_DURATION, + value: averageRequestExecutionTime, + properties: properties + }); + } + // Set last counters + currentCounter.lastRequestCount = currentCounter.totalRequestCount; + currentCounter.lastTime = currentCounter.time; + } + }; + Statsbeat.prototype._getShortHost = function (originalHost) { + var shortHost = originalHost; + try { + var hostRegex = new RegExp(/^https?:\/\/(?:www\.)?([^\/.-]+)/); + var res = hostRegex.exec(originalHost); + if (res != null && res.length > 1) { + shortHost = res[1]; + } + shortHost = shortHost.replace(".in.applicationinsights.azure.com", ""); + } + catch (error) { + // Ignore error + } + return shortHost; + }; + Statsbeat.prototype._trackRequestsCount = function (commonProperties) { + var _this = this; + var _loop_1 = function (i) { + currentCounter = this_1._networkStatsbeatCollection[i]; + var properties = Object.assign({ "endpoint": currentCounter.endpoint, "host": currentCounter.host }, commonProperties); + if (currentCounter.totalSuccesfulRequestCount > 0) { + this_1._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.REQUEST_SUCCESS, + value: currentCounter.totalSuccesfulRequestCount, + properties: properties + }); + currentCounter.totalSuccesfulRequestCount = 0; //Reset + } + if (currentCounter.totalFailedRequestCount.length > 0) { + currentCounter.totalFailedRequestCount.forEach(function (currentCounter) { + properties = Object.assign(__assign(__assign({}, properties), { "statusCode": currentCounter.statusCode })); + _this._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.REQUEST_FAILURE, + value: currentCounter.count, + properties: properties + }); + }); + currentCounter.totalFailedRequestCount = []; //Reset + } + if (currentCounter.retryCount.length > 0) { + currentCounter.retryCount.forEach(function (currentCounter) { + properties = Object.assign(__assign(__assign({}, properties), { "statusCode": currentCounter.statusCode })); + _this._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.RETRY_COUNT, + value: currentCounter.count, + properties: properties + }); + }); + currentCounter.retryCount = []; //Reset + } + if (currentCounter.throttleCount.length > 0) { + currentCounter.throttleCount.forEach(function (currentCounter) { + properties = Object.assign(__assign(__assign({}, properties), { "statusCode": currentCounter.statusCode })); + _this._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.THROTTLE_COUNT, + value: currentCounter.count, + properties: properties + }); + }); + currentCounter.throttleCount = []; //Reset + } + if (currentCounter.exceptionCount.length > 0) { + currentCounter.exceptionCount.forEach(function (currentCounter) { + properties = Object.assign(__assign(__assign({}, properties), { "exceptionType": currentCounter.exceptionType })); + _this._statbeatMetrics.push({ + name: Constants.StatsbeatCounter.EXCEPTION_COUNT, + value: currentCounter.count, + properties: properties + }); + }); + currentCounter.exceptionCount = []; //Reset + } + }; + var this_1 = this, currentCounter; + for (var i = 0; i < this._networkStatsbeatCollection.length; i++) { + _loop_1(i); + } + }; + Statsbeat.prototype._sendStatsbeats = function () { + return __awaiter(this, void 0, void 0, function () { + var envelopes, i, statsbeat, envelope; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + envelopes = []; + for (i = 0; i < this._statbeatMetrics.length; i++) { + statsbeat = { + name: this._statbeatMetrics[i].name, + value: this._statbeatMetrics[i].value, + properties: this._statbeatMetrics[i].properties + }; + envelope = EnvelopeFactory.createEnvelope(statsbeat, Contracts.TelemetryType.Metric, null, this._context, this._statsbeatConfig); + envelope.name = Constants.StatsbeatTelemetryName; + envelopes.push(envelope); + } + this._statbeatMetrics = []; + return [4 /*yield*/, this._sender.send(envelopes)]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + Statsbeat.prototype._getCustomProperties = function () { + this._language = STATSBEAT_LANGUAGE; + this._cikey = this._config.instrumentationKey; + this._sdkVersion = Context.sdkVersion; // "node" or "node-nativeperf" + this._os = os.type(); + this._runtimeVersion = process.version; + }; + Statsbeat.prototype._getResourceProvider = function () { + var _this = this; + return new Promise(function (resolve, reject) { + // Check resource provider + var waiting = false; + _this._resourceProvider = Constants.StatsbeatResourceProvider.unknown; + _this._resourceIdentifier = Constants.StatsbeatResourceProvider.unknown; + if (process.env.WEBSITE_SITE_NAME) { // Web apps + _this._resourceProvider = Constants.StatsbeatResourceProvider.appsvc; + _this._resourceIdentifier = process.env.WEBSITE_SITE_NAME; + if (process.env.WEBSITE_HOME_STAMPNAME) { + _this._resourceIdentifier += "/" + process.env.WEBSITE_HOME_STAMPNAME; + } + } + else if (process.env.FUNCTIONS_WORKER_RUNTIME) { // Function apps + _this._resourceProvider = Constants.StatsbeatResourceProvider.functions; + if (process.env.WEBSITE_HOSTNAME) { + _this._resourceIdentifier = process.env.WEBSITE_HOSTNAME; + } + } + else if (_this._config) { + if (_this._isVM === undefined || _this._isVM == true) { + waiting = true; + Vm.AzureVirtualMachine.getAzureComputeMetadata(_this._config, function (vmInfo) { + _this._isVM = vmInfo.isVM; + if (_this._isVM) { + _this._resourceProvider = Constants.StatsbeatResourceProvider.vm; + _this._resourceIdentifier = vmInfo.id + "/" + vmInfo.subscriptionId; + // Override OS as VM info have higher precedence + if (vmInfo.osType) { + _this._os = vmInfo.osType; + } + } + resolve(); + }); + } + else { + _this._resourceProvider = Constants.StatsbeatResourceProvider.unknown; + } + } + if (!waiting) { + resolve(); + } + }); + }; + Statsbeat.prototype._shutdownStatsbeat = function () { + this.enable(false); // Disable Statsbeat as is it failed 3 times cosnecutively during initialization, is possible SDK is running in private or restricted network + }; + Statsbeat.prototype._getConnectionString = function (config) { + var currentEndpoint = config.endpointUrl; + var euEndpoints = [ + "westeurope", + "northeurope", + "francecentral", + "francesouth", + "germanywestcentral", + "norwayeast", + "norwaywest", + "swedencentral", + "switzerlandnorth", + "switzerlandwest", + "uksouth", + "ukwest" + ]; + for (var i = 0; i < euEndpoints.length; i++) { + if (currentEndpoint.indexOf(euEndpoints[i]) > -1) { + return Statsbeat.EU_CONNECTION_STRING; + } + } + return Statsbeat.NON_EU_CONNECTION_STRING; + }; + Statsbeat.NON_EU_CONNECTION_STRING = "InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com"; + Statsbeat.EU_CONNECTION_STRING = "InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com"; + Statsbeat.STATS_COLLECTION_SHORT_INTERVAL = 900000; // 15 minutes + Statsbeat.STATS_COLLECTION_LONG_INTERVAL = 86400000; // 1 day + Statsbeat.TAG = "Statsbeat"; + return Statsbeat; +}()); +module.exports = Statsbeat; +//# sourceMappingURL=Statsbeat.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js.map b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js.map new file mode 100644 index 0000000..1a574dc --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/Statsbeat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Statsbeat.js","sourceRoot":"","sources":["../../AutoCollection/Statsbeat.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uBAA0B;AAC1B,4DAA+D;AAC/D,4CAA+C;AAC/C,0CAA6C;AAC7C,qDAAwD;AACxD,qDAAwD;AACxD,mDAAsD;AACtD,0CAA6C;AAC7C,4CAA+C;AAC/C,4CAA+C;AAC/C,sCAAyC;AAEzC,IAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;IAiCI,mB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,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACzC,IAAI,eAAe,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE;gBAC9C,OAAO,SAAS,CAAC,oBAAoB,CAAC;aACzC;SACJ;QACD,OAAO,SAAS,CAAC,wBAAwB,CAAC;IAC9C,CAAC;IAjba,kCAAwB,GAAG,6HAA6H,CAAC;IACzJ,8BAAoB,GAAG,iIAAiI,CAAC;IACzJ,yCAA+B,GAAW,MAAM,CAAC,CAAC,aAAa;IAC/D,wCAA8B,GAAW,QAAQ,CAAC,CAAC,QAAQ;IAE1D,aAAG,GAAG,WAAW,CAAC;IA6arC,gBAAC;CAAA,AApbD,IAobC;AAED,iBAAS,SAAS,CAAC","sourcesContent":["import os = require(\"os\");\r\nimport EnvelopeFactory = require(\"../Library/EnvelopeFactory\");\r\nimport Logging = require(\"../Library/Logging\");\r\nimport Sender = require(\"../Library/Sender\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport Vm = require(\"../Library/AzureVirtualMachine\");\r\nimport Config = require(\"../Library/Config\");\r\nimport Context = require(\"../Library/Context\");\r\nimport Network = require(\"./NetworkStatsbeat\");\r\nimport Util = require(\"../Library/Util\");\r\n\r\nconst STATSBEAT_LANGUAGE = \"node\";\r\n\r\nclass Statsbeat {\r\n\r\n public static NON_EU_CONNECTION_STRING = \"InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com\";\r\n public static EU_CONNECTION_STRING = \"InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com\";\r\n public static STATS_COLLECTION_SHORT_INTERVAL: number = 900000; // 15 minutes\r\n public static STATS_COLLECTION_LONG_INTERVAL: number = 86400000; // 1 day\r\n\r\n private static TAG = \"Statsbeat\";\r\n\r\n private _networkStatsbeatCollection: Array;\r\n private _sender: Sender;\r\n private _context: Context;\r\n private _handle: NodeJS.Timer | null;\r\n private _longHandle: NodeJS.Timer | null;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _config: Config;\r\n private _statsbeatConfig: Config;\r\n private _isVM: boolean | undefined;\r\n private _statbeatMetrics: Array<{ name: string; value: number, properties: {} }>;\r\n\r\n // Custom dimensions\r\n private _resourceProvider: string;\r\n private _resourceIdentifier: string;\r\n private _sdkVersion: string;\r\n private _runtimeVersion: string;\r\n private _os: string;\r\n private _language: string;\r\n private _cikey: string;\r\n private _attach: string = Constants.StatsbeatAttach.sdk; // Default is SDK\r\n private _feature: number = Constants.StatsbeatFeature.NONE;\r\n private _instrumentation: number = Constants.StatsbeatInstrumentation.NONE;\r\n\r\n constructor(config: Config, context?: Context) {\r\n this._isInitialized = false;\r\n this._statbeatMetrics = [];\r\n this._networkStatsbeatCollection = [];\r\n this._config = config;\r\n this._context = context || new Context();\r\n let statsbeatConnectionString = this._getConnectionString(config);\r\n this._statsbeatConfig = new Config(statsbeatConnectionString);\r\n this._statsbeatConfig.samplingPercentage = 100; // Do not sample\r\n this._sender = new Sender(this._statsbeatConfig, null, null, null, null, true, this._shutdownStatsbeat.bind(this));\r\n }\r\n\r\n public enable(isEnabled: boolean) {\r\n this._isEnabled = isEnabled;\r\n if (this._isEnabled && !this._isInitialized) {\r\n this._getCustomProperties();\r\n this._isInitialized = true;\r\n }\r\n if (isEnabled) {\r\n if (!this._handle) {\r\n this._handle = setInterval(() => {\r\n this.trackShortIntervalStatsbeats();\r\n }, Statsbeat.STATS_COLLECTION_SHORT_INTERVAL);\r\n this._handle.unref(); // Allow the app to terminate even while this loop is going on\r\n }\r\n if (!this._longHandle) {\r\n // On first enablement\r\n this.trackLongIntervalStatsbeats();\r\n this._longHandle = setInterval(() => {\r\n this.trackLongIntervalStatsbeats();\r\n }, Statsbeat.STATS_COLLECTION_LONG_INTERVAL);\r\n this._longHandle.unref(); // Allow the app to terminate even while this loop is going on\r\n }\r\n } else {\r\n if (this._handle) {\r\n clearInterval(this._handle);\r\n this._handle = null;\r\n }\r\n if (this._longHandle) {\r\n clearInterval(this._longHandle);\r\n this._longHandle = null;\r\n }\r\n }\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n public isEnabled() {\r\n return this._isEnabled;\r\n }\r\n\r\n public setCodelessAttach() {\r\n this._attach = Constants.StatsbeatAttach.codeless;\r\n }\r\n\r\n public addFeature(feature: Constants.StatsbeatFeature) {\r\n this._feature |= feature;\r\n }\r\n\r\n public removeFeature(feature: Constants.StatsbeatFeature) {\r\n this._feature &= ~feature;\r\n }\r\n\r\n public addInstrumentation(instrumentation: Constants.StatsbeatInstrumentation) {\r\n this._instrumentation |= instrumentation;\r\n }\r\n\r\n public removeInstrumentation(instrumentation: Constants.StatsbeatInstrumentation) {\r\n this._instrumentation &= ~instrumentation;\r\n }\r\n\r\n public countRequest(endpoint: number, host: string, duration: number, success: boolean, statusCode?: number) {\r\n if (!this.isEnabled()) {\r\n return;\r\n }\r\n let counter: Network.NetworkStatsbeat = this._getNetworkStatsbeatCounter(endpoint, host);\r\n counter.totalRequestCount++;\r\n counter.intervalRequestExecutionTime += duration;\r\n if (success === false) {\r\n if (!statusCode) {\r\n return;\r\n }\r\n let currentStatusCounter = counter.totalFailedRequestCount.find((statusCounter) => statusCode === statusCounter.statusCode);\r\n if (currentStatusCounter) {\r\n currentStatusCounter.count++;\r\n } else {\r\n counter.totalFailedRequestCount.push({ statusCode: statusCode, count: 1 });\r\n }\r\n }\r\n else {\r\n counter.totalSuccesfulRequestCount++;\r\n }\r\n }\r\n\r\n public countException(endpoint: number, host: string, exceptionType: Error) {\r\n if (!this.isEnabled()) {\r\n return;\r\n }\r\n let counter: Network.NetworkStatsbeat = this._getNetworkStatsbeatCounter(endpoint, host);\r\n let currentErrorCounter = counter.exceptionCount.find((exceptionCounter) => exceptionType.name === exceptionCounter.exceptionType);\r\n if (currentErrorCounter) {\r\n currentErrorCounter.count++;\r\n } else {\r\n counter.exceptionCount.push({ exceptionType: exceptionType.name, count: 1 });\r\n }\r\n }\r\n\r\n public countThrottle(endpoint: number, host: string, statusCode: number) {\r\n if (!this.isEnabled()) {\r\n return;\r\n }\r\n let counter: Network.NetworkStatsbeat = this._getNetworkStatsbeatCounter(endpoint, host);\r\n let currentStatusCounter = counter.throttleCount.find((statusCounter) => statusCode === statusCounter.statusCode);\r\n if (currentStatusCounter) {\r\n currentStatusCounter.count++;\r\n } else {\r\n counter.throttleCount.push({ statusCode: statusCode, count: 1 });\r\n }\r\n }\r\n\r\n public countRetry(endpoint: number, host: string, statusCode: number) {\r\n if (!this.isEnabled()) {\r\n return;\r\n }\r\n let counter: Network.NetworkStatsbeat = this._getNetworkStatsbeatCounter(endpoint, host);\r\n let currentStatusCounter = counter.retryCount.find((statusCounter) => statusCode === statusCounter.statusCode);\r\n if (currentStatusCounter) {\r\n currentStatusCounter.count++;\r\n } else {\r\n counter.retryCount.push({ statusCode: statusCode, count: 1 });\r\n }\r\n }\r\n\r\n public async trackShortIntervalStatsbeats() {\r\n try {\r\n await this._getResourceProvider();\r\n let networkProperties = {\r\n \"os\": this._os,\r\n \"rp\": this._resourceProvider,\r\n \"cikey\": this._cikey,\r\n \"runtimeVersion\": this._runtimeVersion,\r\n \"language\": this._language,\r\n \"version\": this._sdkVersion,\r\n \"attach\": this._attach\r\n }\r\n this._trackRequestDuration(networkProperties);\r\n this._trackRequestsCount(networkProperties);\r\n await this._sendStatsbeats();\r\n }\r\n catch (error) {\r\n Logging.info(Statsbeat.TAG, \"Failed to send Statsbeat metrics: \" + Util.dumpObj(error));\r\n }\r\n }\r\n\r\n public async trackLongIntervalStatsbeats() {\r\n try {\r\n await this._getResourceProvider();\r\n let commonProperties = {\r\n \"os\": this._os,\r\n \"rp\": this._resourceProvider,\r\n \"cikey\": this._cikey,\r\n \"runtimeVersion\": this._runtimeVersion,\r\n \"language\": this._language,\r\n \"version\": this._sdkVersion,\r\n \"attach\": this._attach\r\n };\r\n let attachProperties = Object.assign({\r\n \"rpId\": this._resourceIdentifier\r\n }, commonProperties);\r\n this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.ATTACH, value: 1, properties: attachProperties });\r\n if (this._instrumentation != Constants.StatsbeatInstrumentation.NONE) {// Only send if there are some instrumentations enabled\r\n let instrumentationProperties = Object.assign({ \"feature\": this._instrumentation, \"type\": Constants.StatsbeatFeatureType.Instrumentation }, commonProperties);\r\n this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.FEATURE, value: 1, properties: instrumentationProperties });\r\n }\r\n if (this._feature != Constants.StatsbeatFeature.NONE) {// Only send if there are some features enabled\r\n let featureProperties = Object.assign({ \"feature\": this._feature, \"type\": Constants.StatsbeatFeatureType.Feature }, commonProperties);\r\n this._statbeatMetrics.push({ name: Constants.StatsbeatCounter.FEATURE, value: 1, properties: featureProperties });\r\n }\r\n await this._sendStatsbeats();\r\n }\r\n catch (error) {\r\n Logging.info(Statsbeat.TAG, \"Failed to send Statsbeat metrics: \" + Util.dumpObj(error));\r\n }\r\n }\r\n\r\n private _getNetworkStatsbeatCounter(endpoint: number, host: string): Network.NetworkStatsbeat {\r\n let shortHost = this._getShortHost(host);\r\n // Check if counter is available\r\n for (let i = 0; i < this._networkStatsbeatCollection.length; i++) {\r\n // Same object\r\n if (endpoint === this._networkStatsbeatCollection[i].endpoint &&\r\n shortHost === this._networkStatsbeatCollection[i].host) {\r\n return this._networkStatsbeatCollection[i];\r\n }\r\n }\r\n // Create a new one if not found\r\n let newCounter = new Network.NetworkStatsbeat(endpoint, shortHost);\r\n this._networkStatsbeatCollection.push(newCounter);\r\n return newCounter;\r\n }\r\n\r\n private _trackRequestDuration(commonProperties: {}) {\r\n for (let i = 0; i < this._networkStatsbeatCollection.length; i++) {\r\n let currentCounter = this._networkStatsbeatCollection[i];\r\n currentCounter.time = +new Date;\r\n let intervalRequests = (currentCounter.totalRequestCount - currentCounter.lastRequestCount) || 0;\r\n let totalRequestExecutionTime = currentCounter.intervalRequestExecutionTime - currentCounter.lastIntervalRequestExecutionTime;\r\n let averageRequestExecutionTime = totalRequestExecutionTime > 0 ? (totalRequestExecutionTime / intervalRequests) || 0 : 0;\r\n currentCounter.lastIntervalRequestExecutionTime = currentCounter.intervalRequestExecutionTime; // reset\r\n if (intervalRequests > 0) {\r\n // Add extra properties\r\n let properties = Object.assign(\r\n {\r\n \"endpoint\": this._networkStatsbeatCollection[i].endpoint,\r\n \"host\": this._networkStatsbeatCollection[i].host\r\n },\r\n commonProperties\r\n );\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.REQUEST_DURATION,\r\n value: averageRequestExecutionTime,\r\n properties: properties\r\n });\r\n }\r\n // Set last counters\r\n currentCounter.lastRequestCount = currentCounter.totalRequestCount;\r\n currentCounter.lastTime = currentCounter.time;\r\n }\r\n }\r\n\r\n private _getShortHost(originalHost: string) {\r\n let shortHost = originalHost;\r\n try {\r\n let hostRegex = new RegExp(/^https?:\\/\\/(?:www\\.)?([^\\/.-]+)/);\r\n let res = hostRegex.exec(originalHost);\r\n if (res != null && res.length > 1) {\r\n shortHost = res[1];\r\n }\r\n shortHost = shortHost.replace(\".in.applicationinsights.azure.com\", \"\");\r\n }\r\n catch (error) {\r\n // Ignore error\r\n }\r\n return shortHost;\r\n }\r\n\r\n private _trackRequestsCount(commonProperties: {}) {\r\n for (let i = 0; i < this._networkStatsbeatCollection.length; i++) {\r\n var currentCounter = this._networkStatsbeatCollection[i];\r\n let properties = Object.assign(\r\n { \"endpoint\": currentCounter.endpoint, \"host\": currentCounter.host },\r\n commonProperties\r\n );\r\n if (currentCounter.totalSuccesfulRequestCount > 0) {\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.REQUEST_SUCCESS,\r\n value: currentCounter.totalSuccesfulRequestCount,\r\n properties: properties\r\n });\r\n currentCounter.totalSuccesfulRequestCount = 0; //Reset\r\n }\r\n if (currentCounter.totalFailedRequestCount.length > 0) {\r\n currentCounter.totalFailedRequestCount.forEach((currentCounter) => {\r\n properties = Object.assign({ ...properties, \"statusCode\": currentCounter.statusCode });\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.REQUEST_FAILURE,\r\n value: currentCounter.count,\r\n properties: properties\r\n });\r\n });\r\n currentCounter.totalFailedRequestCount = []; //Reset\r\n }\r\n if (currentCounter.retryCount.length > 0) {\r\n currentCounter.retryCount.forEach((currentCounter) => {\r\n properties = Object.assign({ ...properties, \"statusCode\": currentCounter.statusCode });\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.RETRY_COUNT,\r\n value: currentCounter.count,\r\n properties: properties\r\n });\r\n });\r\n currentCounter.retryCount = []; //Reset\r\n }\r\n if (currentCounter.throttleCount.length > 0) {\r\n currentCounter.throttleCount.forEach((currentCounter) => {\r\n properties = Object.assign({ ...properties, \"statusCode\": currentCounter.statusCode });\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.THROTTLE_COUNT,\r\n value: currentCounter.count,\r\n properties: properties\r\n });\r\n });\r\n currentCounter.throttleCount = []; //Reset\r\n }\r\n if (currentCounter.exceptionCount.length > 0) {\r\n currentCounter.exceptionCount.forEach((currentCounter) => {\r\n properties = Object.assign({ ...properties, \"exceptionType\": currentCounter.exceptionType });\r\n this._statbeatMetrics.push({\r\n name: Constants.StatsbeatCounter.EXCEPTION_COUNT,\r\n value: currentCounter.count,\r\n properties: properties\r\n });\r\n });\r\n currentCounter.exceptionCount = []; //Reset\r\n }\r\n }\r\n }\r\n\r\n private async _sendStatsbeats() {\r\n let envelopes: Array = [];\r\n for (let i = 0; i < this._statbeatMetrics.length; i++) {\r\n let statsbeat: Contracts.MetricTelemetry = {\r\n name: this._statbeatMetrics[i].name,\r\n value: this._statbeatMetrics[i].value,\r\n properties: this._statbeatMetrics[i].properties\r\n };\r\n let envelope = EnvelopeFactory.createEnvelope(statsbeat, Contracts.TelemetryType.Metric, null, this._context, this._statsbeatConfig);\r\n envelope.name = Constants.StatsbeatTelemetryName;\r\n envelopes.push(envelope);\r\n }\r\n this._statbeatMetrics = [];\r\n await this._sender.send(envelopes);\r\n }\r\n\r\n private _getCustomProperties() {\r\n this._language = STATSBEAT_LANGUAGE;\r\n this._cikey = this._config.instrumentationKey;\r\n this._sdkVersion = Context.sdkVersion; // \"node\" or \"node-nativeperf\"\r\n this._os = os.type();\r\n this._runtimeVersion = process.version;\r\n }\r\n\r\n private _getResourceProvider(): Promise {\r\n return new Promise((resolve, reject) => {\r\n // Check resource provider\r\n let waiting: boolean = false;\r\n this._resourceProvider = Constants.StatsbeatResourceProvider.unknown;\r\n this._resourceIdentifier = Constants.StatsbeatResourceProvider.unknown;\r\n if (process.env.WEBSITE_SITE_NAME) { // Web apps\r\n this._resourceProvider = Constants.StatsbeatResourceProvider.appsvc;\r\n this._resourceIdentifier = process.env.WEBSITE_SITE_NAME;\r\n if (process.env.WEBSITE_HOME_STAMPNAME) {\r\n this._resourceIdentifier += \"/\" + process.env.WEBSITE_HOME_STAMPNAME;\r\n }\r\n } else if (process.env.FUNCTIONS_WORKER_RUNTIME) { // Function apps\r\n this._resourceProvider = Constants.StatsbeatResourceProvider.functions;\r\n if (process.env.WEBSITE_HOSTNAME) {\r\n this._resourceIdentifier = process.env.WEBSITE_HOSTNAME;\r\n }\r\n } else if (this._config) {\r\n if (this._isVM === undefined || this._isVM == true) {\r\n waiting = true;\r\n Vm.AzureVirtualMachine.getAzureComputeMetadata(this._config, (vmInfo) => {\r\n this._isVM = vmInfo.isVM;\r\n if (this._isVM) {\r\n this._resourceProvider = Constants.StatsbeatResourceProvider.vm;\r\n this._resourceIdentifier = vmInfo.id + \"/\" + vmInfo.subscriptionId;\r\n // Override OS as VM info have higher precedence\r\n if (vmInfo.osType) {\r\n this._os = vmInfo.osType;\r\n }\r\n }\r\n resolve();\r\n });\r\n } else {\r\n this._resourceProvider = Constants.StatsbeatResourceProvider.unknown;\r\n }\r\n }\r\n if (!waiting) {\r\n resolve();\r\n }\r\n });\r\n }\r\n\r\n private _shutdownStatsbeat() {\r\n this.enable(false);// Disable Statsbeat as is it failed 3 times cosnecutively during initialization, is possible SDK is running in private or restricted network\r\n }\r\n\r\n private _getConnectionString(config: Config): string {\r\n let currentEndpoint = config.endpointUrl;\r\n let euEndpoints = [\r\n \"westeurope\",\r\n \"northeurope\",\r\n \"francecentral\",\r\n \"francesouth\",\r\n \"germanywestcentral\",\r\n \"norwayeast\",\r\n \"norwaywest\",\r\n \"swedencentral\",\r\n \"switzerlandnorth\",\r\n \"switzerlandwest\",\r\n \"uksouth\",\r\n \"ukwest\"\r\n ];\r\n for (let i = 0; i < euEndpoints.length; i++) {\r\n if (currentEndpoint.indexOf(euEndpoints[i]) > -1) {\r\n return Statsbeat.EU_CONNECTION_STRING;\r\n }\r\n }\r\n return Statsbeat.NON_EU_CONNECTION_STRING;\r\n }\r\n}\r\n\r\nexport = Statsbeat;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/WebSnippet.d.ts b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.d.ts new file mode 100644 index 0000000..f0cdee2 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.d.ts @@ -0,0 +1,35 @@ +/// +import http = require("http"); +import TelemetryClient = require("../Library/TelemetryClient"); +import snippetInjectionHelper = require("../Library/SnippetInjectionHelper"); +declare class WebSnippet { + static INSTANCE: WebSnippet; + private static _snippet; + private static _aiUrl; + private static _aiDeprecatedUrl; + private _isEnabled; + private _isInitialized; + private _isIkeyValid; + private _statsbeat; + private _webInstrumentationIkey; + private _clientWebInstrumentationConfig; + private _clientWebInstrumentationSrc; + constructor(client: TelemetryClient); + enable(isEnabled: boolean, webInstrumentationConnectionString?: string): void; + isInitialized(): boolean; + private _getWebSnippetIkey; + private _getWebInstrumentationReplacedStr; + private _getClientWebInstrumentationConfigStr; + private _initialize; + /** + * Validate response and try to inject Web snippet + */ + ValidateInjection(response: http.ServerResponse, input: string | Buffer): boolean; + /** + * Inject Web snippet + */ + InjectWebSnippet(response: http.ServerResponse, input: string | Buffer, encodeType?: snippetInjectionHelper.contentEncodingMethod, bufferEncodeType?: string): string | Buffer; + private _getInjectedCompressBuffer; + dispose(): void; +} +export = WebSnippet; diff --git a/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js new file mode 100644 index 0000000..ad3cd81 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js @@ -0,0 +1,362 @@ +"use strict"; +var http = require("http"); +var https = require("https"); +var zlib = require("zlib"); +var Logging = require("../Library/Logging"); +var snippetInjectionHelper = require("../Library/SnippetInjectionHelper"); +var prefixHelper = require("../Library/PrefixHelper"); +var Constants = require("../Declarations/Constants"); +var ConnectionStringParser = require("../Library/ConnectionStringParser"); +var applicationinsights_web_snippet_1 = require("@microsoft/applicationinsights-web-snippet"); +var WebSnippet = /** @class */ (function () { + function WebSnippet(client) { + var _a; + this._isIkeyValid = true; + if (!!WebSnippet.INSTANCE) { + throw new Error("Web snippet injection should be configured from the applicationInsights object"); + } + WebSnippet.INSTANCE = this; + // AI URL used to validate if snippet already included + WebSnippet._aiUrl = Constants.WEB_INSTRUMENTATION_DEFAULT_SOURCE; + WebSnippet._aiDeprecatedUrl = Constants.WEB_INSTRUMENTATION_DEPRECATED_SOURCE; + var clientWebIkey = this._getWebSnippetIkey((_a = client.config) === null || _a === void 0 ? void 0 : _a.webInstrumentationConnectionString); + this._webInstrumentationIkey = clientWebIkey || client.config.instrumentationKey; + this._clientWebInstrumentationConfig = client.config.webInstrumentationConfig; + this._clientWebInstrumentationSrc = client.config.webInstrumentationSrc; + this._statsbeat = client.getStatsbeat(); + } + WebSnippet.prototype.enable = function (isEnabled, webInstrumentationConnectionString) { + this._isEnabled = isEnabled; + this._webInstrumentationIkey = this._getWebSnippetIkey(webInstrumentationConnectionString) || this._webInstrumentationIkey; + WebSnippet._snippet = this._getWebInstrumentationReplacedStr(); + if (this._isEnabled && !this._isInitialized && this._isIkeyValid) { + if (this._statsbeat) { + this._statsbeat.addFeature(Constants.StatsbeatFeature.WEB_SNIPPET); + } + this._initialize(); + } + else if (!this._isEnabled) { + if (this._statsbeat) { + this._statsbeat.removeFeature(Constants.StatsbeatFeature.WEB_SNIPPET); + } + } + }; + WebSnippet.prototype.isInitialized = function () { + return this._isInitialized; + }; + WebSnippet.prototype._getWebSnippetIkey = function (connectionString) { + var iKey = null; + try { + var csCode = ConnectionStringParser.parse(connectionString); + var iKeyCode = csCode.instrumentationkey || ""; + if (!ConnectionStringParser.isIkeyValid(iKeyCode)) { + this._isIkeyValid = false; + Logging.info("Invalid web Instrumentation connection string, web Instrumentation is not enabled."); + } + else { + this._isIkeyValid = true; + iKey = iKeyCode; + } + } + catch (err) { + Logging.info("get web snippet ikey error: " + err); + } + return iKey; + }; + WebSnippet.prototype._getWebInstrumentationReplacedStr = function () { + var configStr = this._getClientWebInstrumentationConfigStr(this._clientWebInstrumentationConfig); + var osStr = prefixHelper.getOsPrefix(); + var rpStr = prefixHelper.getResourceProvider(); + var snippetReplacedStr = this._webInstrumentationIkey + "\",\r\n" + configStr + " disableIkeyDeprecationMessage: true,\r\n sdkExtension: \"" + rpStr + osStr + "d_n_"; + var replacedSnippet = applicationinsights_web_snippet_1.webSnippet.replace("INSTRUMENTATION_KEY", snippetReplacedStr); + if (this._clientWebInstrumentationSrc) { + return replacedSnippet.replace(Constants.WEB_INSTRUMENTATION_DEFAULT_SOURCE + ".2.min.js", this._clientWebInstrumentationSrc); + } + return replacedSnippet; + }; + // Do not use string replace here, because double quote should be kept. + // we want to transfer all values of config to the web snippet in the following way: + // cfg: { + // config1: "config1 string value", + // config2: true, + // config3: 1, + // ... + //}}); + WebSnippet.prototype._getClientWebInstrumentationConfigStr = function (config) { + var configStr = ""; + try { + if (config != undefined && config.length > 0) { + config.forEach(function (item) { + var key = item.name; + if (key === undefined) + return; + var val = item.value; + var entry = ""; + // NOTE: users should convert object/function to string themselves + // Type "function" and "object" will be skipped! + switch (typeof val) { + case "function": + break; + case "object": + break; + case "string": + entry = " " + key + ": \"" + val + "\",\r\n"; + configStr += entry; + break; + default: + entry = " " + key + ": " + val + ",\r\n"; + configStr += entry; + break; + } + }); + } + } + catch (e) { + // if has any errors here, web Instrumentation will be disabled. + this._isEnabled = false; + Logging.info("Parse client web instrumentation error. Web Instrumentation is disabled"); + } + return configStr; + }; + WebSnippet.prototype._initialize = function () { + this._isInitialized = true; + var originalHttpServer = http.createServer; + var originalHttpsServer = https.createServer; + var isEnabled = this._isEnabled; + http.createServer = function (requestListener) { + var originalRequestListener = requestListener; + if (originalRequestListener) { + requestListener = function (request, response) { + // Patch response write method + var originalResponseWrite = response.write; + var isGetRequest = request.method == "GET"; + response.write = function wrap(a, b, c) { + //only patch GET request + try { + if (isEnabled && isGetRequest) { + var headers = snippetInjectionHelper.getContentEncodingFromHeaders(response); + var writeBufferType = undefined; + if (typeof b === "string") { + writeBufferType = b; + } + if (headers === null || headers === undefined) { + if (WebSnippet.INSTANCE.ValidateInjection(response, a)) { + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, writeBufferType); + } + } + else if (headers.length) { + var encodeType = headers[0]; + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType); + } + } + } + catch (err) { + Logging.warn("Inject snippet error: " + err); + } + return originalResponseWrite.apply(response, arguments); + }; + // Patch response end method for cases when HTML is added there + var originalResponseEnd = response.end; + response.end = function wrap(a, b, c) { + if (isEnabled && isGetRequest) { + try { + if (isEnabled && isGetRequest) { + var headers = snippetInjectionHelper.getContentEncodingFromHeaders(response); + var endBufferType = undefined; + if (typeof b === "string") { + endBufferType = b; + } + if (headers === null || headers === undefined) { + if (WebSnippet.INSTANCE.ValidateInjection(response, a)) { + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, endBufferType); + } + } + else if (headers.length) { + var encodeType = headers[0]; + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType); + } + } + } + catch (err) { + Logging.warn("Inject snipet error: " + err); + } + } + return originalResponseEnd.apply(response, arguments); + }; + return originalRequestListener(request, response); + }; + } + return originalHttpServer(requestListener); + }; + https.createServer = function (options, httpsRequestListener) { + var originalHttpsRequestListener = httpsRequestListener; + if (originalHttpsRequestListener) { + httpsRequestListener = function (req, res) { + var isGetHttpsRequest = req.method == "GET"; + var originalHttpsResponseWrite = res.write; + var originalHttpsResponseEnd = res.end; + res.write = function wrap(a, b, c) { + try { + if (isEnabled && isGetHttpsRequest) { + var headers = snippetInjectionHelper.getContentEncodingFromHeaders(res); + var writeBufferType = undefined; + if (typeof b === "string") { + writeBufferType = b; + } + if (headers === null || headers === undefined) { + if (WebSnippet.INSTANCE.ValidateInjection(res, a)) { + arguments[0] = this.InjectWebSnippet(res, a, undefined, writeBufferType); + } + } + else if (headers.length) { + var encodeType = headers[0]; + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType); + } + } + } + catch (err) { + Logging.warn("Inject snippet error: " + err); + } + return originalHttpsResponseWrite.apply(res, arguments); + }; + res.end = function wrap(a, b, c) { + try { + if (isEnabled && isGetHttpsRequest) { + var headers = snippetInjectionHelper.getContentEncodingFromHeaders(res); + var endBufferType = undefined; + if (typeof b === "string") { + endBufferType = b; + } + if (headers === null || headers === undefined) { + if (WebSnippet.INSTANCE.ValidateInjection(res, a)) { + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, undefined, endBufferType); + } + } + else if (headers.length) { + var encodeType = headers[0]; + arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType); + } + } + } + catch (err) { + Logging.warn("Inject snippet error: " + err); + } + return originalHttpsResponseEnd.apply(res, arguments); + }; + return originalHttpsRequestListener(req, res); + }; + return originalHttpsServer(options, httpsRequestListener); + } + }; + }; + /** + * Validate response and try to inject Web snippet + */ + WebSnippet.prototype.ValidateInjection = function (response, input) { + try { + if (!response || !input || response.statusCode != 200) + return false; + var isContentHtml = snippetInjectionHelper.isContentTypeHeaderHtml(response); + if (!isContentHtml) + return false; + var inputStr = input.slice().toString(); + if (inputStr.indexOf("") >= 0 && inputStr.indexOf("") >= 0) { + // Check if snippet not already present looking for AI Web SDK URL + if (inputStr.indexOf(WebSnippet._aiUrl) < 0 && inputStr.indexOf(WebSnippet._aiDeprecatedUrl) < 0) { + return true; + } + } + } + catch (err) { + Logging.info("validate injections error: " + err); + } + return false; + }; + /** + * Inject Web snippet + */ + WebSnippet.prototype.InjectWebSnippet = function (response, input, encodeType, bufferEncodeType) { + try { + var isCompressedBuffer = !!encodeType; + if (!isCompressedBuffer) { + var html = input.toString(); + var index = html.indexOf(""); + if (index < 0) + return input; + var newHtml = snippetInjectionHelper.insertSnippetByIndex(index, html, WebSnippet._snippet); + if (typeof input === "string") { + response.removeHeader("Content-Length"); + input = newHtml; + response.setHeader("Content-Length", Buffer.byteLength(input)); + } + else if (Buffer.isBuffer(input)) { + var bufferType = bufferEncodeType ? bufferEncodeType : "utf8"; + var isValidBufferType = snippetInjectionHelper.isBufferType(input, bufferType); + if (isValidBufferType) { + response.removeHeader("Content-Length"); + var encodedString = Buffer.from(newHtml).toString(bufferType); + input = Buffer.from(encodedString, bufferType); + response.setHeader("Content-Length", input.length); + } + } + } + else { + response.removeHeader("Content-Length"); + input = this._getInjectedCompressBuffer(response, input, encodeType); + response.setHeader("Content-Length", input.length); + } + } + catch (ex) { + Logging.warn("Failed to inject web snippet and change content-lenght headers. Exception:" + ex); + } + return input; + }; + //*********************** + // should NOT use sync functions here. But currently cannot get async functions to work + // because reponse.write return boolean + // and also this function do not support partial compression as well + // need more investigation + WebSnippet.prototype._getInjectedCompressBuffer = function (response, input, encodeType) { + try { + switch (encodeType) { + case snippetInjectionHelper.contentEncodingMethod.GZIP: + var gunzipBuffer = zlib.gunzipSync(input); + if (this.ValidateInjection(response, gunzipBuffer)) { + var injectedGunzipBuffer = this.InjectWebSnippet(response, gunzipBuffer); + input = zlib.gzipSync(injectedGunzipBuffer); + } + break; + case snippetInjectionHelper.contentEncodingMethod.DEFLATE: + var inflateBuffer = zlib.inflateSync(input); + if (this.ValidateInjection(response, inflateBuffer)) { + var injectedInflateBuffer = this.InjectWebSnippet(response, inflateBuffer); + input = zlib.deflateSync(injectedInflateBuffer); + } + break; + case snippetInjectionHelper.contentEncodingMethod.BR: + var BrotliDecompressSync = snippetInjectionHelper.getBrotliDecompressSync(zlib); + var BrotliCompressSync = snippetInjectionHelper.getBrotliCompressSync(zlib); + if (BrotliDecompressSync && BrotliCompressSync) { + var decompressBuffer = BrotliDecompressSync(input); + if (this.ValidateInjection(response, decompressBuffer)) { + var injectedDecompressBuffer = this.InjectWebSnippet(response, decompressBuffer); + input = BrotliCompressSync(injectedDecompressBuffer); + } + break; + } + } + } + catch (err) { + Logging.info("get web injection compress buffer error: " + err); + } + return input; + }; + WebSnippet.prototype.dispose = function () { + WebSnippet.INSTANCE = null; + this.enable(false); + this._isInitialized = false; + }; + return WebSnippet; +}()); +module.exports = WebSnippet; +//# sourceMappingURL=WebSnippet.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js.map b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js.map new file mode 100644 index 0000000..55480ef --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/WebSnippet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"WebSnippet.js","sourceRoot":"","sources":["../../AutoCollection/WebSnippet.ts"],"names":[],"mappings":";AAAA,2BAA8B;AAC9B,6BAAgC;AAChC,2BAA8B;AAE9B,4CAA+C;AAE/C,0EAA6E;AAC7E,sDAAyD;AAEzD,qDAAwD;AACxD,0EAA6E;AAC7E,8FAAsE;AAItE;IAeI,oBAAY,MAAuB;;QAN3B,iBAAY,GAAY,IAAI,CAAC;QAOjC,IAAI,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE;YACvB,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GAAG,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;wBAC3E,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,qBAAqB,CAAC,CAAC;qBAClD;oBACD,MAAM;gBACX,KAAK,sBAAsB,CAAC,qBAAqB,CAAC,EAAE;oBAChD,IAAI,oBAAoB,GAAG,sBAAsB,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;oBAChF,IAAI,kBAAkB,GAAG,sBAAsB,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;oBAC5E,IAAI,oBAAoB,IAAI,kBAAkB,EAAE;wBAC5C,IAAI,gBAAgB,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;wBACnD,IAAI,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAC,gBAAgB,CAAC,EAAE;4BACnD,IAAI,wBAAwB,GAAG,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC;4BACjF,KAAK,GAAG,kBAAkB,CAAC,wBAAwB,CAAC,CAAC;yBACvD;wBACD,MAAM;qBACV;aACR;SAEJ;QAAC,OAAO,GAAG,EAAE;YACV,OAAO,CAAC,IAAI,CAAC,2CAA2C,GAAG,GAAG,CAAC,CAAC;SACnE;QAED,OAAO,KAAK,CAAC;IACjB,CAAC;IAEM,4BAAO,GAAd;QACI,UAAU,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAChC,CAAC;IACL,iBAAC;AAAD,CAAC,AAjXD,IAiXC;AAED,iBAAS,UAAU,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport zlib = require(\"zlib\");\r\n\r\nimport Logging = require(\"../Library/Logging\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport snippetInjectionHelper = require(\"../Library/SnippetInjectionHelper\");\r\nimport prefixHelper = require(\"../Library/PrefixHelper\");\r\nimport Statsbeat = require(\"./Statsbeat\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport ConnectionStringParser = require(\"../Library/ConnectionStringParser\");\r\nimport {webSnippet} from \"@microsoft/applicationinsights-web-snippet\";\r\nimport {IWebInstrumentationConfig} from \"../Declarations/Interfaces\";\r\n\r\n\r\nclass WebSnippet {\r\n\r\n public static INSTANCE: WebSnippet;\r\n\r\n private static _snippet: string;\r\n private static _aiUrl: string;\r\n private static _aiDeprecatedUrl: string;\r\n private _isEnabled: boolean;\r\n private _isInitialized: boolean;\r\n private _isIkeyValid: boolean = true;\r\n private _statsbeat: Statsbeat;\r\n private _webInstrumentationIkey: string;\r\n private _clientWebInstrumentationConfig: IWebInstrumentationConfig[];\r\n private _clientWebInstrumentationSrc: string;\r\n\r\n constructor(client: TelemetryClient) {\r\n if (!!WebSnippet.INSTANCE) {\r\n throw new Error(\"Web snippet injection should be configured from the applicationInsights object\");\r\n }\r\n\r\n WebSnippet.INSTANCE = this;\r\n // AI URL used to validate if snippet already included\r\n WebSnippet._aiUrl = Constants.WEB_INSTRUMENTATION_DEFAULT_SOURCE;\r\n WebSnippet._aiDeprecatedUrl = Constants.WEB_INSTRUMENTATION_DEPRECATED_SOURCE;\r\n\r\n let clientWebIkey = this._getWebSnippetIkey(client.config?.webInstrumentationConnectionString);\r\n this._webInstrumentationIkey = clientWebIkey || client.config.instrumentationKey;\r\n this._clientWebInstrumentationConfig = client.config.webInstrumentationConfig;\r\n this._clientWebInstrumentationSrc = client.config.webInstrumentationSrc;\r\n\r\n this._statsbeat = client.getStatsbeat();\r\n }\r\n\r\n public enable(isEnabled: boolean, webInstrumentationConnectionString?: string ) {\r\n this._isEnabled = isEnabled;\r\n this._webInstrumentationIkey = this._getWebSnippetIkey(webInstrumentationConnectionString) || this._webInstrumentationIkey;\r\n WebSnippet._snippet = this._getWebInstrumentationReplacedStr();\r\n\r\n if (this._isEnabled && !this._isInitialized && this._isIkeyValid) {\r\n if (this._statsbeat) {\r\n this._statsbeat.addFeature(Constants.StatsbeatFeature.WEB_SNIPPET);\r\n }\r\n this._initialize();\r\n } else if (!this._isEnabled) {\r\n if (this._statsbeat) {\r\n this._statsbeat.removeFeature(Constants.StatsbeatFeature.WEB_SNIPPET);\r\n }\r\n }\r\n }\r\n\r\n public isInitialized() {\r\n return this._isInitialized;\r\n }\r\n\r\n private _getWebSnippetIkey(connectionString: string) {\r\n let iKey = null;\r\n try {\r\n const csCode = ConnectionStringParser.parse(connectionString);\r\n const iKeyCode = csCode.instrumentationkey || \"\";\r\n if (!ConnectionStringParser.isIkeyValid(iKeyCode)) {\r\n this._isIkeyValid = false;\r\n Logging.info(\"Invalid web Instrumentation connection string, web Instrumentation is not enabled.\");\r\n } else {\r\n this._isIkeyValid = true;\r\n iKey = iKeyCode;\r\n }\r\n } catch (err) {\r\n Logging.info(\"get web snippet ikey error: \" + err);\r\n }\r\n return iKey;\r\n }\r\n\r\n private _getWebInstrumentationReplacedStr() {\r\n let configStr = this._getClientWebInstrumentationConfigStr(this._clientWebInstrumentationConfig);\r\n let osStr = prefixHelper.getOsPrefix();\r\n let rpStr = prefixHelper.getResourceProvider();\r\n let snippetReplacedStr = `${this._webInstrumentationIkey}\\\",\\r\\n${configStr} disableIkeyDeprecationMessage: true,\\r\\n sdkExtension: \\\"${rpStr}${osStr}d_n_`;\r\n let replacedSnippet = webSnippet.replace(\"INSTRUMENTATION_KEY\", snippetReplacedStr);\r\n if (this._clientWebInstrumentationSrc) {\r\n return replacedSnippet.replace(`${Constants.WEB_INSTRUMENTATION_DEFAULT_SOURCE}.2.min.js`,this._clientWebInstrumentationSrc);\r\n }\r\n return replacedSnippet;\r\n }\r\n\r\n // Do not use string replace here, because double quote should be kept.\r\n // we want to transfer all values of config to the web snippet in the following way:\r\n // cfg: {\r\n // config1: \"config1 string value\",\r\n // config2: true,\r\n // config3: 1,\r\n // ...\r\n //}});\r\n private _getClientWebInstrumentationConfigStr(config: IWebInstrumentationConfig[]) {\r\n let configStr = \"\";\r\n try {\r\n if (config != undefined && config.length > 0) {\r\n config.forEach((item) =>{\r\n let key = item.name;\r\n if (key === undefined) return;\r\n let val = item.value;\r\n let entry = \"\";\r\n // NOTE: users should convert object/function to string themselves\r\n // Type \"function\" and \"object\" will be skipped!\r\n switch(typeof val) {\r\n case \"function\":\r\n break;\r\n case \"object\":\r\n break;\r\n case \"string\":\r\n entry = ` ${key}: \\\"${val}\\\",\\r\\n`;\r\n configStr += entry;\r\n break;\r\n default:\r\n entry = ` ${key}: ${val},\\r\\n`;\r\n configStr += entry;\r\n break;\r\n }\r\n \r\n });\r\n }\r\n\r\n } catch (e) {\r\n // if has any errors here, web Instrumentation will be disabled.\r\n this._isEnabled = false;\r\n Logging.info(\"Parse client web instrumentation error. Web Instrumentation is disabled\");\r\n }\r\n return configStr;\r\n }\r\n\r\n private _initialize() {\r\n this._isInitialized = true;\r\n const originalHttpServer = http.createServer;\r\n const originalHttpsServer = https.createServer;\r\n var isEnabled = this._isEnabled;\r\n\r\n http.createServer = (requestListener?: (request: http.IncomingMessage, response: http.ServerResponse) => void) => {\r\n const originalRequestListener = requestListener;\r\n if (originalRequestListener) {\r\n requestListener = (request: http.IncomingMessage, response: http.ServerResponse) => {\r\n // Patch response write method\r\n let originalResponseWrite = response.write;\r\n let isGetRequest = request.method == \"GET\";\r\n response.write = function wrap(a: Buffer | string, b?: Function | string, c?: Function | string) {\r\n //only patch GET request\r\n try {\r\n if (isEnabled && isGetRequest) {\r\n let headers = snippetInjectionHelper.getContentEncodingFromHeaders(response);\r\n let writeBufferType = undefined;\r\n if (typeof b === \"string\") {\r\n writeBufferType = b;\r\n }\r\n if (headers === null || headers === undefined) {\r\n if (WebSnippet.INSTANCE.ValidateInjection(response, a)) {\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, writeBufferType);\r\n }\r\n } else if (headers.length) {\r\n let encodeType = headers[0];\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType);\r\n }\r\n }\r\n } catch (err) {\r\n Logging.warn(\"Inject snippet error: \"+ err);\r\n }\r\n return originalResponseWrite.apply(response, arguments);\r\n }\r\n\r\n // Patch response end method for cases when HTML is added there\r\n let originalResponseEnd = response.end;\r\n\r\n response.end = function wrap(a?: Buffer | string | any, b?: Function | string, c?: Function) {\r\n if (isEnabled && isGetRequest) {\r\n try {\r\n if (isEnabled && isGetRequest) {\r\n let headers = snippetInjectionHelper.getContentEncodingFromHeaders(response);\r\n let endBufferType = undefined;\r\n if (typeof b === \"string\") {\r\n endBufferType = b;\r\n }\r\n if (headers === null || headers === undefined) {\r\n if (WebSnippet.INSTANCE.ValidateInjection(response, a)) {\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, endBufferType);\r\n }\r\n } else if (headers.length) {\r\n let encodeType = headers[0];\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType);\r\n }\r\n }\r\n } catch (err) {\r\n Logging.warn(\"Inject snipet error: \"+ err);\r\n }\r\n }\r\n return originalResponseEnd.apply(response, arguments);\r\n }\r\n\r\n return originalRequestListener(request, response);\r\n }\r\n }\r\n return originalHttpServer(requestListener);\r\n }\r\n\r\n https.createServer = function(options,httpsRequestListener) {\r\n const originalHttpsRequestListener = httpsRequestListener;\r\n if (originalHttpsRequestListener) {\r\n httpsRequestListener = function (req, res) {\r\n let isGetHttpsRequest = req.method == \"GET\";\r\n let originalHttpsResponseWrite = res.write;\r\n let originalHttpsResponseEnd = res.end;\r\n res.write = function wrap(a: Buffer | string | any, b?:Function | string, c?: Function) {\r\n try {\r\n if (isEnabled && isGetHttpsRequest) {\r\n let headers = snippetInjectionHelper.getContentEncodingFromHeaders(res);\r\n let writeBufferType = undefined;\r\n if (typeof b === \"string\") {\r\n writeBufferType = b;\r\n }\r\n if (headers === null || headers === undefined) {\r\n if (WebSnippet.INSTANCE.ValidateInjection(res, a)) {\r\n arguments[0] = this.InjectWebSnippet(res, a, undefined, writeBufferType);\r\n }\r\n } else if (headers.length) {\r\n let encodeType = headers[0];\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType);\r\n }\r\n }\r\n } catch (err) {\r\n Logging.warn(\"Inject snippet error: \"+ err);\r\n }\r\n return originalHttpsResponseWrite.apply(res,arguments);\r\n }\r\n\r\n res.end = function wrap(a: Buffer | string | any, b?:Function | string, c?: Function) {\r\n try {\r\n if (isEnabled && isGetHttpsRequest) {\r\n let headers = snippetInjectionHelper.getContentEncodingFromHeaders(res);\r\n let endBufferType = undefined;\r\n if (typeof b === \"string\") {\r\n endBufferType = b;\r\n }\r\n if (headers === null || headers === undefined) {\r\n if (WebSnippet.INSTANCE.ValidateInjection(res, a)) {\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, undefined, endBufferType);\r\n }\r\n } else if (headers.length) {\r\n let encodeType = headers[0];\r\n arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType);\r\n }\r\n }\r\n } catch (err) {\r\n Logging.warn(\"Inject snippet error: \"+ err);\r\n }\r\n return originalHttpsResponseEnd.apply(res,arguments);\r\n\r\n }\r\n return originalHttpsRequestListener(req,res);\r\n }\r\n return originalHttpsServer(options, httpsRequestListener);\r\n\r\n }\r\n \r\n }\r\n\r\n }\r\n\r\n /**\r\n * Validate response and try to inject Web snippet\r\n */\r\n public ValidateInjection(response: http.ServerResponse, input: string | Buffer): boolean {\r\n try {\r\n if (!response || !input || response.statusCode != 200) return false;\r\n let isContentHtml = snippetInjectionHelper.isContentTypeHeaderHtml(response);\r\n if (!isContentHtml) return false;\r\n let inputStr = input.slice().toString();\r\n if (inputStr.indexOf(\"\") >= 0 && inputStr.indexOf(\"\") >= 0) {\r\n // Check if snippet not already present looking for AI Web SDK URL\r\n if (inputStr.indexOf(WebSnippet._aiUrl) < 0 && inputStr.indexOf(WebSnippet._aiDeprecatedUrl) < 0) {\r\n return true;\r\n }\r\n }\r\n } catch (err) {\r\n Logging.info(\"validate injections error: \" + err);\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Inject Web snippet\r\n */\r\n public InjectWebSnippet(response: http.ServerResponse, input: string | Buffer, encodeType?: snippetInjectionHelper.contentEncodingMethod, bufferEncodeType?: string ): string | Buffer {\r\n try {\r\n let isCompressedBuffer = !!encodeType;\r\n if (!isCompressedBuffer) {\r\n let html = input.toString();\r\n let index = html.indexOf(\"\");\r\n if (index < 0) return input;\r\n\r\n let newHtml = snippetInjectionHelper.insertSnippetByIndex(index,html,WebSnippet._snippet);\r\n if (typeof input === \"string\") {\r\n response.removeHeader(\"Content-Length\");\r\n input = newHtml;\r\n response.setHeader(\"Content-Length\", Buffer.byteLength(input));\r\n } else if (Buffer.isBuffer(input)) {\r\n let bufferType = bufferEncodeType? bufferEncodeType:\"utf8\";\r\n let isValidBufferType = snippetInjectionHelper.isBufferType(input, bufferType);\r\n if (isValidBufferType) {\r\n response.removeHeader(\"Content-Length\");\r\n let encodedString = Buffer.from(newHtml).toString(bufferType);\r\n input = Buffer.from(encodedString,bufferType);\r\n response.setHeader(\"Content-Length\", input.length);\r\n }\r\n }\r\n } else {\r\n response.removeHeader(\"Content-Length\");\r\n input = this._getInjectedCompressBuffer(response,input as Buffer,encodeType);\r\n response.setHeader(\"Content-Length\", input.length);\r\n }\r\n }\r\n catch (ex) {\r\n Logging.warn(\"Failed to inject web snippet and change content-lenght headers. Exception:\" + ex);\r\n }\r\n return input;\r\n }\r\n\r\n //***********************\r\n // should NOT use sync functions here. But currently cannot get async functions to work\r\n // because reponse.write return boolean\r\n // and also this function do not support partial compression as well\r\n // need more investigation\r\n private _getInjectedCompressBuffer(response: http.ServerResponse, input: Buffer, encodeType: snippetInjectionHelper.contentEncodingMethod): Buffer {\r\n try {\r\n switch (encodeType) {\r\n case snippetInjectionHelper.contentEncodingMethod.GZIP:\r\n let gunzipBuffer = zlib.gunzipSync(input);\r\n if (this.ValidateInjection(response,gunzipBuffer)) {\r\n let injectedGunzipBuffer = this.InjectWebSnippet(response, gunzipBuffer);\r\n input = zlib.gzipSync(injectedGunzipBuffer);\r\n }\r\n break;\r\n case snippetInjectionHelper.contentEncodingMethod.DEFLATE:\r\n let inflateBuffer = zlib.inflateSync(input);\r\n if (this.ValidateInjection(response,inflateBuffer)) {\r\n let injectedInflateBuffer = this.InjectWebSnippet(response, inflateBuffer);\r\n input = zlib.deflateSync(injectedInflateBuffer);\r\n }\r\n break;\r\n case snippetInjectionHelper.contentEncodingMethod.BR:\r\n let BrotliDecompressSync = snippetInjectionHelper.getBrotliDecompressSync(zlib);\r\n let BrotliCompressSync = snippetInjectionHelper.getBrotliCompressSync(zlib);\r\n if (BrotliDecompressSync && BrotliCompressSync) {\r\n let decompressBuffer = BrotliDecompressSync(input);\r\n if (this.ValidateInjection(response,decompressBuffer)) {\r\n let injectedDecompressBuffer = this.InjectWebSnippet(response, decompressBuffer);\r\n input = BrotliCompressSync(injectedDecompressBuffer);\r\n }\r\n break;\r\n }\r\n }\r\n\r\n } catch (err) {\r\n Logging.info(\"get web injection compress buffer error: \" + err);\r\n }\r\n \r\n return input;\r\n }\r\n\r\n public dispose() {\r\n WebSnippet.INSTANCE = null;\r\n this.enable(false);\r\n this._isInitialized = false;\r\n }\r\n}\r\n\r\nexport = WebSnippet;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.d.ts new file mode 100644 index 0000000..2e88940 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.d.ts @@ -0,0 +1,8 @@ +import { ReadableSpan } from "@opentelemetry/sdk-trace-base"; +import { DependencyTelemetry, Identified, RequestTelemetry } from "../../../Declarations/Contracts"; +/** + * Implementation of Mapping to Azure Monitor + * + * https://gist.github.com/lmolkova/e4215c0f44a49ef824983382762e6b92#file-z_azure_monitor_exporter_mapping-md + */ +export declare const parseEventHubSpan: (span: ReadableSpan, telemetry: (DependencyTelemetry | RequestTelemetry) & Identified) => void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js new file mode 100644 index 0000000..71c0c3a --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js @@ -0,0 +1,67 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseEventHubSpan = void 0; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for details. +var api_1 = require("@opentelemetry/api"); +var core_1 = require("@opentelemetry/core"); +var semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +var Constants_1 = require("../../../Declarations/Constants"); +/** + * Average span.links[].attributes.enqueuedTime + */ +var getTimeSinceEnqueued = function (span) { + var countEnqueueDiffs = 0; + var sumEnqueueDiffs = 0; + var startTimeMs = core_1.hrTimeToMilliseconds(span.startTime); + span.links.forEach(function (_a) { + var attributes = _a.attributes; + var enqueuedTime = attributes === null || attributes === void 0 ? void 0 : attributes[Constants_1.ENQUEUED_TIME]; + if (enqueuedTime) { + countEnqueueDiffs += 1; + sumEnqueueDiffs += startTimeMs - (parseFloat(enqueuedTime.toString()) || 0); + } + }); + return Math.max(sumEnqueueDiffs / (countEnqueueDiffs || 1), 0); +}; +/** + * Implementation of Mapping to Azure Monitor + * + * https://gist.github.com/lmolkova/e4215c0f44a49ef824983382762e6b92#file-z_azure_monitor_exporter_mapping-md + */ +var parseEventHubSpan = function (span, telemetry) { + var _a; + var namespace = span.attributes[Constants_1.AzNamespace]; + var peerAddress = (span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_NAME] || + span.attributes["peer.address"] || + "unknown").replace(/\/$/g, ""); // remove trailing "/" + var messageBusDestination = (span.attributes[Constants_1.MessageBusDestination] || "unknown"); + switch (span.kind) { + case api_1.SpanKind.CLIENT: + telemetry.dependencyTypeName = namespace; + telemetry.target = peerAddress + "/" + messageBusDestination; + break; + case api_1.SpanKind.PRODUCER: + telemetry.dependencyTypeName = Constants_1.DependencyTypeName.QueueMessage + " | " + namespace; + telemetry.target = peerAddress + "/" + messageBusDestination; + break; + case api_1.SpanKind.CONSUMER: + telemetry.source = peerAddress + "/" + messageBusDestination; + telemetry.measurements = __assign(__assign({}, telemetry.measurements), (_a = {}, _a[Constants_1.TIME_SINCE_ENQUEUED] = getTimeSinceEnqueued(span), _a)); + break; + default: // no op + } +}; +exports.parseEventHubSpan = parseEventHubSpan; +//# sourceMappingURL=EventHub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js.map new file mode 100644 index 0000000..9f50f5d --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/Azure/EventHub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EventHub.js","sourceRoot":"","sources":["../../../../AutoCollection/diagnostic-channel/Azure/EventHub.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,4DAA4D;AAC5D,oFAAoF;AACpF,0CAA8C;AAC9C,4CAA2D;AAC3D,4EAAyE;AAGzE,6DAOyC;AAGzC;;GAEG;AACH,IAAM,oBAAoB,GAAG,UAAC,IAAkB;IAC5C,IAAI,iBAAiB,GAAG,CAAC,CAAC;IAC1B,IAAI,eAAe,GAAG,CAAC,CAAC;IACxB,IAAM,WAAW,GAAG,2BAAoB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAEzD,IAA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AAC;YACpF,MAAM;QACV,KAAK,cAAQ,CAAC,QAAQ;YACC,SAAU,CAAC,MAAM,GAAM,WAAW,SAAI,qBAAuB,CAAC;YAC9D,SAAU,CAAC,YAAY,yBAChB,SAAU,CAAC,YAAY,gBAC5C,+BAAmB,IAAG,oBAAoB,CAAC,IAAI,CAAC,MACpD,CAAC;YACF,MAAM;QACV,QAAQ,CAAC,QAAQ;KACpB;AACL,CAAC,CAAC;AAzBW,QAAA,iBAAiB,qBAyB5B","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport { SpanKind } from \"@opentelemetry/api\";\r\nimport { hrTimeToMilliseconds } from \"@opentelemetry/core\";\r\nimport { SemanticAttributes } from \"@opentelemetry/semantic-conventions\";\r\nimport { ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\r\n\r\nimport {\r\n TIME_SINCE_ENQUEUED,\r\n ENQUEUED_TIME,\r\n AzNamespace,\r\n MessageBusDestination,\r\n MicrosoftEventHub,\r\n DependencyTypeName\r\n} from \"../../../Declarations/Constants\";\r\nimport { DependencyTelemetry, Identified, RequestTelemetry } from \"../../../Declarations/Contracts\";\r\n\r\n/**\r\n * Average span.links[].attributes.enqueuedTime\r\n */\r\nconst getTimeSinceEnqueued = (span: ReadableSpan) => {\r\n let countEnqueueDiffs = 0;\r\n let sumEnqueueDiffs = 0;\r\n const startTimeMs = hrTimeToMilliseconds(span.startTime);\r\n\r\n span.links.forEach(({ attributes }) => {\r\n const enqueuedTime = attributes?.[ENQUEUED_TIME] as string | number;\r\n if (enqueuedTime) {\r\n countEnqueueDiffs += 1;\r\n sumEnqueueDiffs += startTimeMs - (parseFloat(enqueuedTime.toString()) || 0);\r\n }\r\n });\r\n\r\n return Math.max(sumEnqueueDiffs / (countEnqueueDiffs || 1), 0);\r\n};\r\n\r\n/**\r\n * Implementation of Mapping to Azure Monitor\r\n *\r\n * https://gist.github.com/lmolkova/e4215c0f44a49ef824983382762e6b92#file-z_azure_monitor_exporter_mapping-md\r\n */\r\nexport const parseEventHubSpan = (span: ReadableSpan, telemetry: (DependencyTelemetry | RequestTelemetry) & Identified): void => {\r\n const namespace = span.attributes[AzNamespace] as typeof MicrosoftEventHub;\r\n const peerAddress = ((span.attributes[SemanticAttributes.NET_PEER_NAME] ||\r\n span.attributes[\"peer.address\"] ||\r\n \"unknown\") as string).replace(/\\/$/g, \"\"); // remove trailing \"/\"\r\n const messageBusDestination = (span.attributes[MessageBusDestination] || \"unknown\") as string;\r\n\r\n switch (span.kind) {\r\n case SpanKind.CLIENT:\r\n (telemetry).dependencyTypeName = namespace;\r\n (telemetry).target = `${peerAddress}/${messageBusDestination}`;\r\n break;\r\n case SpanKind.PRODUCER:\r\n (telemetry).dependencyTypeName = `${DependencyTypeName.QueueMessage} | ${namespace}`;\r\n (telemetry).target = `${peerAddress}/${messageBusDestination}`;\r\n break;\r\n case SpanKind.CONSUMER:\r\n (telemetry).source = `${peerAddress}/${messageBusDestination}`;\r\n (telemetry).measurements = {\r\n ...(telemetry).measurements,\r\n [TIME_SINCE_ENQUEUED]: getTimeSinceEnqueued(span)\r\n };\r\n break;\r\n default: // no op\r\n }\r\n};"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.d.ts new file mode 100644 index 0000000..c0bc346 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.d.ts @@ -0,0 +1,3 @@ +import { ReadableSpan } from "@opentelemetry/sdk-trace-base"; +import * as Contracts from "../../Declarations/Contracts"; +export declare function spanToTelemetryContract(span: ReadableSpan): (Contracts.DependencyTelemetry | Contracts.RequestTelemetry) & Contracts.Identified; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.js new file mode 100644 index 0000000..828006f --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/SpanParser.js @@ -0,0 +1,287 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.spanToTelemetryContract = void 0; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for details. +var url_1 = require("url"); +var api_1 = require("@opentelemetry/api"); +var semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); +var Constants = require("../../Declarations/Constants"); +var EventHub_1 = require("./Azure/EventHub"); +var Util = require("../../Library/Util"); +function createPropertiesFromSpan(span) { + var properties = {}; + for (var _i = 0, _a = Object.keys(span.attributes); _i < _a.length; _i++) { + var key = _a[_i]; + if (!(key.startsWith("http.") || + key.startsWith("rpc.") || + key.startsWith("db.") || + key.startsWith("peer.") || + key.startsWith("net."))) { + properties[key] = span.attributes[key]; + } + } + var links = span.links.map(function (link) { return ({ + operation_Id: link.context.traceId, + id: link.context.spanId + }); }); + if (links.length > 0) { + properties["_MS.links"] = Util.stringify(links); + } + return properties; +} +function isSqlDB(dbSystem) { + return (dbSystem === semantic_conventions_1.DbSystemValues.DB2 || + dbSystem === semantic_conventions_1.DbSystemValues.DERBY || + dbSystem === semantic_conventions_1.DbSystemValues.MARIADB || + dbSystem === semantic_conventions_1.DbSystemValues.MSSQL || + dbSystem === semantic_conventions_1.DbSystemValues.ORACLE || + dbSystem === semantic_conventions_1.DbSystemValues.SQLITE || + dbSystem === semantic_conventions_1.DbSystemValues.OTHER_SQL || + dbSystem === semantic_conventions_1.DbSystemValues.HSQLDB || + dbSystem === semantic_conventions_1.DbSystemValues.H2); +} +function getUrl(span) { + var httpMethod = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_METHOD]; + if (httpMethod) { + var httpUrl = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_URL]; + if (httpUrl) { + return String(httpUrl); + } + else { + var httpScheme = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_SCHEME]; + var httpTarget = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_TARGET]; + if (httpScheme && httpTarget) { + var httpHost = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_HOST]; + if (httpHost) { + return httpScheme + "://" + httpHost + httpTarget; + } + else { + var netPeerPort = span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_PORT]; + if (netPeerPort) { + var netPeerName = span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_NAME]; + if (netPeerName) { + return httpScheme + "://" + netPeerName + ":" + netPeerPort + httpTarget; + } + else { + var netPeerIp = span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_IP]; + if (netPeerIp) { + return httpScheme + "://" + netPeerIp + ":" + netPeerPort + httpTarget; + } + } + } + } + } + } + } + return ""; +} +function getDependencyTarget(span) { + var peerService = span.attributes[semantic_conventions_1.SemanticAttributes.PEER_SERVICE]; + var httpHost = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_HOST]; + var httpUrl = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_URL]; + var netPeerName = span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_NAME]; + var netPeerIp = span.attributes[semantic_conventions_1.SemanticAttributes.NET_PEER_IP]; + if (peerService) { + return String(peerService); + } + else if (httpHost) { + return String(httpHost); + } + else if (httpUrl) { + return String(httpUrl); + } + else if (netPeerName) { + return String(netPeerName); + } + else if (netPeerIp) { + return String(netPeerIp); + } + return ""; +} +function createDependencyData(span) { + var remoteDependency = { + name: span.name, + success: span.status.code != api_1.SpanStatusCode.ERROR, + resultCode: "0", + duration: 0, + data: "", + dependencyTypeName: "" + }; + if (span.kind === api_1.SpanKind.PRODUCER) { + remoteDependency.dependencyTypeName = Constants.DependencyTypeName.QueueMessage; + } + if (span.kind === api_1.SpanKind.INTERNAL && span.parentSpanId) { + remoteDependency.dependencyTypeName = Constants.DependencyTypeName.InProc; + } + var httpMethod = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_METHOD]; + var dbSystem = span.attributes[semantic_conventions_1.SemanticAttributes.DB_SYSTEM]; + var rpcSystem = span.attributes[semantic_conventions_1.SemanticAttributes.RPC_SYSTEM]; + // HTTP Dependency + if (httpMethod) { + remoteDependency.dependencyTypeName = Constants.DependencyTypeName.Http; + var httpUrl = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_URL]; + if (httpUrl) { + var pathName = ""; + try { + var dependencyUrl = new url_1.URL(String(httpUrl)); + pathName = dependencyUrl.pathname; + } + catch (ex) { + // Ignore error + } + remoteDependency.name = httpMethod + " " + pathName; + } + remoteDependency.data = getUrl(span); + var httpStatusCode = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_STATUS_CODE]; + if (httpStatusCode) { + remoteDependency.resultCode = String(httpStatusCode); + } + var target = getDependencyTarget(span); + if (target) { + try { + // Remove default port + var portRegex = new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/); + var res = portRegex.exec(target); + if (res != null) { + var protocol = res[1]; + var port = res[3]; + if ((protocol == "https" && port == ":443") || (protocol == "http" && port == ":80")) { + // Drop port + target = res[1] + res[2] + res[4]; + } + } + } + catch (error) { + // Ignore error + } + remoteDependency.target = "" + target; + } + } + // DB Dependency + else if (dbSystem) { + // TODO: Remove special logic when Azure UX supports OpenTelemetry dbSystem + if (String(dbSystem) === semantic_conventions_1.DbSystemValues.MYSQL) { + remoteDependency.dependencyTypeName = "mysql"; + } + else if (String(dbSystem) === semantic_conventions_1.DbSystemValues.POSTGRESQL) { + remoteDependency.dependencyTypeName = "postgresql"; + } + else if (String(dbSystem) === semantic_conventions_1.DbSystemValues.MONGODB) { + remoteDependency.dependencyTypeName = "mongodb"; + } + else if (String(dbSystem) === semantic_conventions_1.DbSystemValues.REDIS) { + remoteDependency.dependencyTypeName = "redis"; + } + else if (isSqlDB(String(dbSystem))) { + remoteDependency.dependencyTypeName = "SQL"; + } + else { + remoteDependency.dependencyTypeName = String(dbSystem); + } + var dbStatement = span.attributes[semantic_conventions_1.SemanticAttributes.DB_STATEMENT]; + var dbOperation = span.attributes[semantic_conventions_1.SemanticAttributes.DB_OPERATION]; + if (dbStatement) { + remoteDependency.data = String(dbStatement); + } + else if (dbOperation) { + remoteDependency.data = String(dbOperation); + } + var target = getDependencyTarget(span); + var dbName = span.attributes[semantic_conventions_1.SemanticAttributes.DB_NAME]; + if (target) { + remoteDependency.target = dbName ? target + "|" + dbName : "" + target; + } + else { + remoteDependency.target = dbName ? "" + dbName : "" + dbSystem; + } + } + // grpc Dependency + else if (rpcSystem) { + remoteDependency.dependencyTypeName = Constants.DependencyTypeName.Grpc; + var grpcStatusCode = span.attributes[semantic_conventions_1.SemanticAttributes.RPC_GRPC_STATUS_CODE]; + if (grpcStatusCode) { + remoteDependency.resultCode = String(grpcStatusCode); + } + var target = getDependencyTarget(span); + if (target) { + remoteDependency.target = "" + target; + } + else if (rpcSystem) { + remoteDependency.target = String(rpcSystem); + } + } + return remoteDependency; +} +function createRequestData(span) { + var requestData = { + name: span.name, + success: span.status.code != api_1.SpanStatusCode.ERROR, + resultCode: "0", + duration: 0, + url: "", + source: undefined + }; + var httpMethod = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_METHOD]; + var grpcStatusCode = span.attributes[semantic_conventions_1.SemanticAttributes.RPC_GRPC_STATUS_CODE]; + if (httpMethod) { + // Try to get request name for server spans + if (span.kind == api_1.SpanKind.SERVER) { + var httpRoute = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_ROUTE]; + var httpUrl = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_URL]; + if (httpRoute) { + requestData.name = httpMethod + " " + httpRoute; + } + else if (httpUrl) { + try { + var url = new url_1.URL(String(httpUrl)); + requestData.name = httpMethod + " " + url.pathname; + } + catch (ex) { + // Ignore error + } + } + } + requestData.url = getUrl(span); + var httpStatusCode = span.attributes[semantic_conventions_1.SemanticAttributes.HTTP_STATUS_CODE]; + if (httpStatusCode) { + requestData.resultCode = String(httpStatusCode); + } + } + else if (grpcStatusCode) { + requestData.resultCode = String(grpcStatusCode); + } + return requestData; +} +function spanToTelemetryContract(span) { + var telemetry; + switch (span.kind) { + case api_1.SpanKind.CLIENT: + case api_1.SpanKind.PRODUCER: + case api_1.SpanKind.INTERNAL: + telemetry = createDependencyData(span); + break; + case api_1.SpanKind.SERVER: + case api_1.SpanKind.CONSUMER: + telemetry = createRequestData(span); + break; + } + var spanContext = span.spanContext ? span.spanContext() : span.context(); // context is available in OT API = span.links.map((link: Link) => ({\r\n operation_Id: link.context.traceId,\r\n id: link.context.spanId\r\n }));\r\n if (links.length > 0) {\r\n properties[\"_MS.links\"] = Util.stringify(links);\r\n }\r\n return properties;\r\n}\r\n\r\nfunction isSqlDB(dbSystem: string) {\r\n return (\r\n dbSystem === DbSystemValues.DB2 ||\r\n dbSystem === DbSystemValues.DERBY ||\r\n dbSystem === DbSystemValues.MARIADB ||\r\n dbSystem === DbSystemValues.MSSQL ||\r\n dbSystem === DbSystemValues.ORACLE ||\r\n dbSystem === DbSystemValues.SQLITE ||\r\n dbSystem === DbSystemValues.OTHER_SQL ||\r\n dbSystem === DbSystemValues.HSQLDB ||\r\n dbSystem === DbSystemValues.H2\r\n );\r\n}\r\n\r\nfunction getUrl(span: ReadableSpan): string {\r\n const httpMethod = span.attributes[SemanticAttributes.HTTP_METHOD];\r\n if (httpMethod) {\r\n const httpUrl = span.attributes[SemanticAttributes.HTTP_URL];\r\n if (httpUrl) {\r\n return String(httpUrl);\r\n } else {\r\n const httpScheme = span.attributes[SemanticAttributes.HTTP_SCHEME];\r\n const httpTarget = span.attributes[SemanticAttributes.HTTP_TARGET];\r\n if (httpScheme && httpTarget) {\r\n const httpHost = span.attributes[SemanticAttributes.HTTP_HOST];\r\n if (httpHost) {\r\n return `${httpScheme}://${httpHost}${httpTarget}`;\r\n } else {\r\n const netPeerPort = span.attributes[SemanticAttributes.NET_PEER_PORT];\r\n if (netPeerPort) {\r\n const netPeerName = span.attributes[SemanticAttributes.NET_PEER_NAME];\r\n if (netPeerName) {\r\n return `${httpScheme}://${netPeerName}:${netPeerPort}${httpTarget}`;\r\n } else {\r\n const netPeerIp = span.attributes[SemanticAttributes.NET_PEER_IP];\r\n if (netPeerIp) {\r\n return `${httpScheme}://${netPeerIp}:${netPeerPort}${httpTarget}`;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return \"\";\r\n}\r\n\r\nfunction getDependencyTarget(span: ReadableSpan): string {\r\n const peerService = span.attributes[SemanticAttributes.PEER_SERVICE];\r\n const httpHost = span.attributes[SemanticAttributes.HTTP_HOST];\r\n const httpUrl = span.attributes[SemanticAttributes.HTTP_URL];\r\n const netPeerName = span.attributes[SemanticAttributes.NET_PEER_NAME];\r\n const netPeerIp = span.attributes[SemanticAttributes.NET_PEER_IP];\r\n if (peerService) {\r\n return String(peerService);\r\n } else if (httpHost) {\r\n return String(httpHost);\r\n } else if (httpUrl) {\r\n return String(httpUrl);\r\n } else if (netPeerName) {\r\n return String(netPeerName);\r\n } else if (netPeerIp) {\r\n return String(netPeerIp);\r\n }\r\n return \"\";\r\n}\r\n\r\nfunction createDependencyData(span: ReadableSpan): Contracts.DependencyTelemetry {\r\n const remoteDependency: Contracts.DependencyTelemetry = {\r\n name: span.name,\r\n success: span.status.code != SpanStatusCode.ERROR,\r\n resultCode: \"0\",\r\n duration: 0,\r\n data: \"\",\r\n dependencyTypeName: \"\"\r\n };\r\n if (span.kind === SpanKind.PRODUCER) {\r\n remoteDependency.dependencyTypeName = Constants.DependencyTypeName.QueueMessage;\r\n }\r\n if (span.kind === SpanKind.INTERNAL && span.parentSpanId) {\r\n remoteDependency.dependencyTypeName = Constants.DependencyTypeName.InProc;\r\n }\r\n\r\n const httpMethod = span.attributes[SemanticAttributes.HTTP_METHOD];\r\n const dbSystem = span.attributes[SemanticAttributes.DB_SYSTEM];\r\n const rpcSystem = span.attributes[SemanticAttributes.RPC_SYSTEM];\r\n // HTTP Dependency\r\n if (httpMethod) {\r\n remoteDependency.dependencyTypeName = Constants.DependencyTypeName.Http;\r\n const httpUrl = span.attributes[SemanticAttributes.HTTP_URL];\r\n if (httpUrl) {\r\n var pathName = \"\";\r\n try {\r\n let dependencyUrl = new URL(String(httpUrl));\r\n pathName = dependencyUrl.pathname;\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n remoteDependency.name = `${httpMethod} ${pathName}`;\r\n }\r\n remoteDependency.data = getUrl(span);\r\n const httpStatusCode = span.attributes[SemanticAttributes.HTTP_STATUS_CODE];\r\n if (httpStatusCode) {\r\n remoteDependency.resultCode = String(httpStatusCode);\r\n }\r\n let target = getDependencyTarget(span);\r\n if (target) {\r\n try {\r\n // Remove default port\r\n let portRegex = new RegExp(/(https?)(:\\/\\/.*)(:\\d+)(\\S*)/);\r\n let res = portRegex.exec(target);\r\n if (res != null) {\r\n let protocol = res[1];\r\n let port = res[3];\r\n if ((protocol == \"https\" && port == \":443\") || (protocol == \"http\" && port == \":80\")) {\r\n // Drop port\r\n target = res[1] + res[2] + res[4];\r\n }\r\n }\r\n } catch (error) {\r\n // Ignore error\r\n }\r\n remoteDependency.target = `${target}`;\r\n }\r\n }\r\n // DB Dependency\r\n else if (dbSystem) {\r\n // TODO: Remove special logic when Azure UX supports OpenTelemetry dbSystem\r\n if (String(dbSystem) === DbSystemValues.MYSQL) {\r\n remoteDependency.dependencyTypeName = \"mysql\";\r\n } else if (String(dbSystem) === DbSystemValues.POSTGRESQL) {\r\n remoteDependency.dependencyTypeName = \"postgresql\";\r\n } else if (String(dbSystem) === DbSystemValues.MONGODB) {\r\n remoteDependency.dependencyTypeName = \"mongodb\";\r\n } else if (String(dbSystem) === DbSystemValues.REDIS) {\r\n remoteDependency.dependencyTypeName = \"redis\";\r\n } else if (isSqlDB(String(dbSystem))) {\r\n remoteDependency.dependencyTypeName = \"SQL\";\r\n } else {\r\n remoteDependency.dependencyTypeName = String(dbSystem);\r\n }\r\n const dbStatement = span.attributes[SemanticAttributes.DB_STATEMENT];\r\n const dbOperation = span.attributes[SemanticAttributes.DB_OPERATION];\r\n if (dbStatement) {\r\n remoteDependency.data = String(dbStatement);\r\n }\r\n else if (dbOperation) {\r\n remoteDependency.data = String(dbOperation);\r\n }\r\n let target = getDependencyTarget(span);\r\n const dbName = span.attributes[SemanticAttributes.DB_NAME];\r\n if (target) {\r\n remoteDependency.target = dbName ? `${target}|${dbName}` : `${target}`;\r\n } else {\r\n remoteDependency.target = dbName ? `${dbName}` : `${dbSystem}`;\r\n }\r\n }\r\n // grpc Dependency\r\n else if (rpcSystem) {\r\n remoteDependency.dependencyTypeName = Constants.DependencyTypeName.Grpc;\r\n const grpcStatusCode = span.attributes[SemanticAttributes.RPC_GRPC_STATUS_CODE];\r\n if (grpcStatusCode) {\r\n remoteDependency.resultCode = String(grpcStatusCode);\r\n }\r\n let target = getDependencyTarget(span);\r\n if (target) {\r\n remoteDependency.target = `${target}`;\r\n } else if (rpcSystem) {\r\n remoteDependency.target = String(rpcSystem);\r\n }\r\n }\r\n return remoteDependency;\r\n}\r\n\r\nfunction createRequestData(span: ReadableSpan): Contracts.RequestTelemetry {\r\n const requestData: Contracts.RequestTelemetry = {\r\n name: span.name,\r\n success: span.status.code != SpanStatusCode.ERROR,\r\n resultCode: \"0\",\r\n duration: 0,\r\n url: \"\",\r\n source: undefined\r\n };\r\n const httpMethod = span.attributes[SemanticAttributes.HTTP_METHOD];\r\n const grpcStatusCode = span.attributes[SemanticAttributes.RPC_GRPC_STATUS_CODE];\r\n if (httpMethod) {\r\n // Try to get request name for server spans\r\n if (span.kind == SpanKind.SERVER) {\r\n const httpRoute = span.attributes[SemanticAttributes.HTTP_ROUTE];\r\n const httpUrl = span.attributes[SemanticAttributes.HTTP_URL];\r\n if (httpRoute) {\r\n requestData.name = `${httpMethod as string} ${httpRoute as string}`;\r\n }\r\n else if (httpUrl) {\r\n try {\r\n let url = new URL(String(httpUrl));\r\n requestData.name = `${httpMethod} ${url.pathname}`;\r\n }\r\n catch (ex) {\r\n // Ignore error\r\n }\r\n }\r\n }\r\n requestData.url = getUrl(span);\r\n const httpStatusCode = span.attributes[SemanticAttributes.HTTP_STATUS_CODE];\r\n if (httpStatusCode) {\r\n requestData.resultCode = String(httpStatusCode);\r\n }\r\n } else if (grpcStatusCode) {\r\n requestData.resultCode = String(grpcStatusCode);\r\n }\r\n return requestData;\r\n}\r\n\r\nexport function spanToTelemetryContract(span: ReadableSpan): (Contracts.DependencyTelemetry | Contracts.RequestTelemetry) & Contracts.Identified {\r\n let telemetry: (Contracts.DependencyTelemetry | Contracts.RequestTelemetry) & Contracts.Identified;\r\n switch (span.kind) {\r\n case SpanKind.CLIENT:\r\n case SpanKind.PRODUCER:\r\n case SpanKind.INTERNAL:\r\n telemetry = createDependencyData(span);\r\n break;\r\n case SpanKind.SERVER:\r\n case SpanKind.CONSUMER:\r\n telemetry = createRequestData(span);\r\n break;\r\n }\r\n\r\n const spanContext = span.spanContext ? span.spanContext() : (span).context(); // context is available in OT API telemetry).dependencyTypeName = `${Constants.DependencyTypeName.InProc} | ${span.attributes[Constants.AzNamespace]}`\r\n }\r\n if (span.attributes[Constants.AzNamespace] === Constants.MicrosoftEventHub) {\r\n parseEventHubSpan(span, telemetry);\r\n }\r\n }\r\n return telemetry;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.d.ts new file mode 100644 index 0000000..74ef60a --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.d.ts @@ -0,0 +1,5 @@ +import { Span } from "@opentelemetry/sdk-trace-base"; +import TelemetryClient = require("../../Library/TelemetryClient"); +import { IStandardEvent } from "diagnostic-channel"; +export declare const subscriber: (event: IStandardEvent) => void; +export declare function enable(enabled: boolean, client: TelemetryClient): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js new file mode 100644 index 0000000..fe8f5f4 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enable = exports.subscriber = void 0; +var api_1 = require("@opentelemetry/api"); +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var SpanParser = require("./SpanParser"); +var AsyncHooksScopeManager_1 = require("../AsyncHooksScopeManager"); +var clients = []; +var subscriber = function (event) { + try { + var span_1 = event.data; + var telemetry_1 = SpanParser.spanToTelemetryContract(span_1); + AsyncHooksScopeManager_1.AsyncScopeManager.with(span_1, function () { + clients.forEach(function (client) { + if (span_1.kind === api_1.SpanKind.SERVER || span_1.kind === api_1.SpanKind.CONSUMER) { + client.trackRequest(telemetry_1); + } + else if (span_1.kind === api_1.SpanKind.CLIENT || span_1.kind === api_1.SpanKind.INTERNAL || span_1.kind === api_1.SpanKind.PRODUCER) { + client.trackDependency(telemetry_1); + } + }); + }); + } + catch (err) { + { /** ignore errors */ } + } +}; +exports.subscriber = subscriber; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("azure-coretracing", exports.subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.AZURE_CORE_TRACING); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("azure-coretracing", exports.subscriber); + } + } +} +exports.enable = enable; +//# sourceMappingURL=azure-coretracing.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js.map new file mode 100644 index 0000000..f3adb16 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/azure-coretracing.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"azure-coretracing.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/azure-coretracing.sub.ts"],"names":[],"mappings":";;;AAGA,0CAA8C;AAG9C,0DAAwE;AACxE,yDAAyE;AAEzE,yCAA2C;AAC3C,oEAA8D;AAG9D,IAAI,OAAO,GAAsB,EAAE,CAAC;AAE7B,IAAM,UAAU,GAAG,UAAC,KAA2B;IAClD,IAAI;QACA,IAAM,MAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QACxB,IAAM,WAAS,GAAG,UAAU,CAAC,uBAAuB,CAAC,MAAI,CAAC,CAAC;QAC3D,0CAAiB,CAAC,IAAI,CAAC,MAAI,EAAE;YACzB,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;gBACnB,IAAI,MAAI,CAAC,IAAI,KAAK,cAAQ,CAAC,MAAM,IAAI,MAAI,CAAC,IAAI,KAAK,cAAQ,CAAC,QAAQ,EAAE;oBAClE,MAAM,CAAC,YAAY,CAAmB,WAAS,CAAC,CAAC;iBACpD;qBAAM,IAAI,MAAI,CAAC,IAAI,KAAK,cAAQ,CAAC,MAAM,IAAI,MAAI,CAAC,IAAI,KAAK,cAAQ,CAAC,QAAQ,IAAI,MAAI,CAAC,IAAI,KAAK,cAAQ,CAAC,QAAQ,EAAE;oBAC5G,MAAM,CAAC,eAAe,CAAsB,WAAS,CAAC,CAAC;iBAC1D;YACL,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;IACD,OAAO,GAAG,EAAE;QAAE,EAAE,oBAAoB,EAAE;KAAE;AAC5C,CAAC,CAAC;AAfW,QAAA,UAAU,cAerB;AAEF,SAAgB,MAAM,CAAC,OAAgB,EAAE,MAAuB;IAC5D,IAAI,OAAO,EAAE;QACT,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QACjD,IAAI,WAAW,EAAE;YACb,OAAO;SACV;QACD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,SAAS,CAAM,mBAAmB,EAAE,kBAAU,EAAE,+BAAU,EAAE,UAAC,MAAM,EAAE,OAAO;gBAChF,IAAI,SAAS,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;gBACtC,IAAI,SAAS,EAAE;oBACX,SAAS,CAAC,kBAAkB,CAAC,oCAAwB,CAAC,kBAAkB,CAAC,CAAC;iBAC7E;YACL,CAAC,CAAC,CAAC;SAEN;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACxB;SAAM;QACH,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,kBAAU,CAAC,CAAC;SACxD;KACJ;AACL,CAAC;AAtBD,wBAsBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport { Span } from \"@opentelemetry/sdk-trace-base\";\r\nimport { SpanKind } from \"@opentelemetry/api\";\r\n\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport * as SpanParser from \"./SpanParser\";\r\nimport { AsyncScopeManager } from \"../AsyncHooksScopeManager\";\r\nimport { DependencyTelemetry, RequestTelemetry } from \"../../Declarations/Contracts\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nexport const subscriber = (event: IStandardEvent) => {\r\n try {\r\n const span = event.data;\r\n const telemetry = SpanParser.spanToTelemetryContract(span);\r\n AsyncScopeManager.with(span, () => {\r\n clients.forEach((client) => {\r\n if (span.kind === SpanKind.SERVER || span.kind === SpanKind.CONSUMER) {\r\n client.trackRequest(telemetry);\r\n } else if (span.kind === SpanKind.CLIENT || span.kind === SpanKind.INTERNAL || span.kind === SpanKind.PRODUCER) {\r\n client.trackDependency(telemetry);\r\n }\r\n });\r\n });\r\n }\r\n catch (err) { { /** ignore errors */ } }\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"azure-coretracing\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.AZURE_CORE_TRACING);\r\n }\r\n });\r\n\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"azure-coretracing\", subscriber);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.d.ts new file mode 100644 index 0000000..f659f39 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.d.ts @@ -0,0 +1,3 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +export declare function enable(enabled: boolean, client: TelemetryClient): void; +export declare function dispose(): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js new file mode 100644 index 0000000..0d0a694 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dispose = exports.enable = void 0; +var Contracts_1 = require("../../Declarations/Contracts"); +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +// Mapping from bunyan levels defined at https://github.com/trentm/node-bunyan/blob/master/lib/bunyan.js#L256 +var bunyanToAILevelMap = { + 10: Contracts_1.SeverityLevel.Verbose, + 20: Contracts_1.SeverityLevel.Verbose, + 30: Contracts_1.SeverityLevel.Information, + 40: Contracts_1.SeverityLevel.Warning, + 50: Contracts_1.SeverityLevel.Error, + 60: Contracts_1.SeverityLevel.Critical +}; +var subscriber = function (event) { + var message = event.data.result; + clients.forEach(function (client) { + try { + // Try to parse message as Bunyan log is JSON + var log = JSON.parse(message); + if (log.err) { + var bunyanError = new Error(log.err.message); + bunyanError.name = log.err.name; + bunyanError.stack = log.err.stack; + client.trackException({ exception: bunyanError }); + return; + } + } + catch (err) { + // Ignore error + } + var AIlevel = bunyanToAILevelMap[event.data.level]; + client.trackTrace({ message: message, severity: AIlevel }); + }); +}; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("bunyan", subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.BUNYAN); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("bunyan", subscriber); + } + } +} +exports.enable = enable; +function dispose() { + diagnostic_channel_1.channel.unsubscribe("bunyan", subscriber); + clients = []; +} +exports.dispose = dispose; +//# sourceMappingURL=bunyan.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js.map new file mode 100644 index 0000000..0d291ef --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/bunyan.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bunyan.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/bunyan.sub.ts"],"names":[],"mappings":";;;AAGA,0DAA6D;AAC7D,0DAAwE;AAExE,yDAAyE;AAIzE,IAAI,OAAO,GAAsB,EAAE,CAAC;AAEpC,6GAA6G;AAC7G,IAAM,kBAAkB,GAA8B;IAClD,EAAE,EAAE,yBAAa,CAAC,OAAO;IACzB,EAAE,EAAE,yBAAa,CAAC,OAAO;IACzB,EAAE,EAAE,yBAAa,CAAC,WAAW;IAC7B,EAAE,EAAE,yBAAa,CAAC,OAAO;IACzB,EAAE,EAAE,yBAAa,CAAC,KAAK;IACvB,EAAE,EAAE,yBAAa,CAAC,QAAQ;CAC7B,CAAC;AAEF,IAAM,UAAU,GAAG,UAAC,KAAyC;IACzD,IAAI,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,MAAgB,CAAC;IAC1C,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;QACnB,IAAI;YACA,6CAA6C;YAC7C,IAAI,GAAG,GAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACnC,IAAI,GAAG,CAAC,GAAG,EAAE;gBACT,IAAI,WAAW,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAC7C,WAAW,CAAC,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC;gBAChC,WAAW,CAAC,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC;gBAClC,MAAM,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC,CAAC;gBAClD,OAAO;aACV;SACJ;QACD,OA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CAAC;AAHD,0BAGC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { SeverityLevel } from \"../../Declarations/Contracts\";\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\n\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { bunyan } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\n// Mapping from bunyan levels defined at https://github.com/trentm/node-bunyan/blob/master/lib/bunyan.js#L256\r\nconst bunyanToAILevelMap: { [key: number]: number } = {\r\n 10: SeverityLevel.Verbose,\r\n 20: SeverityLevel.Verbose,\r\n 30: SeverityLevel.Information,\r\n 40: SeverityLevel.Warning,\r\n 50: SeverityLevel.Error,\r\n 60: SeverityLevel.Critical\r\n};\r\n\r\nconst subscriber = (event: IStandardEvent) => {\r\n let message = event.data.result as string;\r\n clients.forEach((client) => {\r\n try {\r\n // Try to parse message as Bunyan log is JSON\r\n let log: any = JSON.parse(message);\r\n if (log.err) {\r\n let bunyanError = new Error(log.err.message);\r\n bunyanError.name = log.err.name;\r\n bunyanError.stack = log.err.stack;\r\n client.trackException({ exception: bunyanError });\r\n return;\r\n }\r\n }\r\n catch (err) {\r\n // Ignore error\r\n }\r\n const AIlevel = bunyanToAILevelMap[event.data.level];\r\n client.trackTrace({ message: message, severity: AIlevel });\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"bunyan\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.BUNYAN);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"bunyan\", subscriber);\r\n }\r\n }\r\n}\r\n\r\nexport function dispose() {\r\n channel.unsubscribe(\"bunyan\", subscriber);\r\n clients = [];\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.d.ts new file mode 100644 index 0000000..f659f39 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.d.ts @@ -0,0 +1,3 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +export declare function enable(enabled: boolean, client: TelemetryClient): void; +export declare function dispose(): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js new file mode 100644 index 0000000..0a52f7f --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dispose = exports.enable = void 0; +var Contracts_1 = require("../../Declarations/Contracts"); +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var subscriber = function (event) { + var message = event.data.message; + clients.forEach(function (client) { + if (message instanceof Error) { + client.trackException({ exception: message }); + } + else { + // Message can have a trailing newline + if (message.lastIndexOf("\n") == message.length - 1) { + message = message.substring(0, message.length - 1); + } + client.trackTrace({ message: message, severity: (event.data.stderr ? Contracts_1.SeverityLevel.Warning : Contracts_1.SeverityLevel.Information) }); + } + }); +}; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("console", subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.CONSOLE); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("console", subscriber); + } + } +} +exports.enable = enable; +function dispose() { + diagnostic_channel_1.channel.unsubscribe("console", subscriber); + clients = []; +} +exports.dispose = dispose; +//# sourceMappingURL=console.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js.map new file mode 100644 index 0000000..d84bfa8 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/console.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"console.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/console.sub.ts"],"names":[],"mappings":";;;AAGA,0DAA6D;AAC7D,0DAAwE;AAExE,yDAAyE;AAIzE,IAAI,OAAO,GAAsB,EAAE,CAAC;AAEpC,IAAM,UAAU,GAAG,UAAC,KAA8C;IAC9D,IAAI,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,OAAyB,CAAC;IACnD,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;QACnB,IAAI,OAAO,YAAY,KAAK,EAAE;YAC1B,MAAM,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;SACjD;aAAM;YACH,sCAAsC;YACtC,IAAI,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;gBACjD,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;aACtD;YACD,MAAM,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,yBAAa,CAAC,OAAO,CAAC,CAAC,CAAC,yBAAa,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;SAC9H;IACL,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,SAAgB,MAAM,CAAC,OAAgB,EAAE,MAAuB;IAC5D,IAAI,OAAO,EAAE;QACT,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QACjD,IAAI,WAAW,EAAE;YACb,OAAO;SACV;QACD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,SAAS,CAA0B,SAAS,EAAE,UAAU,EAAE,+BAAU,EAAE,UAAC,MAAM,EAAE,OAAO;gBAC1F,IAAI,SAAS,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;gBACtC,IAAI,SAAS,EAAE;oBACX,SAAS,CAAC,kBAAkB,CAAC,oCAAwB,CAAC,OAAO,CAAC,CAAC;iBAClE;YACL,CAAC,CAAC,CAAC;SACN;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACxB;SAAM;QACH,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;SAC9C;KACJ;AACL,CAAC;AArBD,wBAqBC;AAED,SAAgB,OAAO;IACnB,4BAAO,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAC3C,OAAO,GAAG,EAAE,CAAC;AACjB,CAAC;AAHD,0BAGC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { SeverityLevel } from \"../../Declarations/Contracts\";\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\n\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { console as consolePub } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nconst subscriber = (event: IStandardEvent) => {\r\n let message = event.data.message as Error | string;\r\n clients.forEach((client) => {\r\n if (message instanceof Error) {\r\n client.trackException({ exception: message });\r\n } else {\r\n // Message can have a trailing newline\r\n if (message.lastIndexOf(\"\\n\") == message.length - 1) {\r\n message = message.substring(0, message.length - 1);\r\n }\r\n client.trackTrace({ message: message, severity: (event.data.stderr ? SeverityLevel.Warning : SeverityLevel.Information) });\r\n }\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"console\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.CONSOLE);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"console\", subscriber);\r\n }\r\n }\r\n}\r\n\r\nexport function dispose() {\r\n channel.unsubscribe(\"console\", subscriber);\r\n clients = [];\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.d.ts new file mode 100644 index 0000000..6f2185d --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.d.ts @@ -0,0 +1,2 @@ +export declare const IsInitialized: boolean; +export declare function registerContextPreservation(cb: (cb: Function) => Function): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js new file mode 100644 index 0000000..161423b --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js @@ -0,0 +1,47 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for details. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.registerContextPreservation = exports.IsInitialized = void 0; +var Logging = require("../../Library/Logging"); +var JsonConfig_1 = require("../../Library/JsonConfig"); +exports.IsInitialized = !JsonConfig_1.JsonConfig.getInstance().noDiagnosticChannel; +var TAG = "DiagnosticChannel"; +if (exports.IsInitialized) { + var publishers = require("diagnostic-channel-publishers"); + var individualOptOuts = JsonConfig_1.JsonConfig.getInstance().noPatchModules; + var unpatchedModules = individualOptOuts.split(","); + var modules = { + bunyan: publishers.bunyan, + console: publishers.console, + mongodb: publishers.mongodb, + mongodbCore: publishers.mongodbCore, + mysql: publishers.mysql, + redis: publishers.redis, + pg: publishers.pg, + pgPool: publishers.pgPool, + winston: publishers.winston, + azuresdk: publishers.azuresdk + }; + for (var mod in modules) { + if (unpatchedModules.indexOf(mod) === -1) { + modules[mod].enable(); + Logging.info(TAG, "Subscribed to " + mod + " events"); + } + } + if (unpatchedModules.length > 0) { + Logging.info(TAG, "Some modules will not be patched", unpatchedModules); + } +} +else { + Logging.info(TAG, "Not subscribing to dependency autocollection because APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL was set"); +} +function registerContextPreservation(cb) { + if (!exports.IsInitialized) { + return; + } + var diagChannel = require("diagnostic-channel"); + diagChannel.channel.addContextPreservation(cb); +} +exports.registerContextPreservation = registerContextPreservation; +//# sourceMappingURL=initialization.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js.map new file mode 100644 index 0000000..79e9dbb --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/initialization.js.map @@ -0,0 +1 @@ +{"version":3,"file":"initialization.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/initialization.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,oFAAoF;;;AAOpF,+CAAkD;AAClD,uDAAsD;AAEzC,QAAA,aAAa,GAAG,CAAC,uBAAU,CAAC,WAAW,EAAE,CAAC,mBAAmB,CAAC;AAC3E,IAAM,GAAG,GAAG,mBAAmB,CAAC;AAEhC,IAAI,qBAAa,EAAE;IACf,IAAM,UAAU,GAAiC,OAAO,CAAC,+BAA+B,CAAC,CAAC;IAC1F,IAAM,iBAAiB,GAAW,uBAAU,CAAC,WAAW,EAAE,CAAC,cAAc,CAAC;IAC1E,IAAM,gBAAgB,GAAG,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACtD,IAAM,OAAO,GAA0B;QACnC,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,WAAW,EAAE,UAAU,CAAC,WAAW;QACnC,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,EAAE,EAAE,UAAU,CAAC,EAAE;QACjB,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,QAAQ,EAAE,UAAU,CAAC,QAAQ;KAChC,CAAC;IACF,KAAK,IAAM,GAAG,IAAI,OAAO,EAAE;QACvB,IAAI,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;YACtC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;YACtB,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,mBAAiB,GAAG,YAAS,CAAC,CAAC;SACpD;KACJ;IACD,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;QAC7B,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,kCAAkC,EAAE,gBAAgB,CAAC,CAAC;KAC3E;CACJ;KAAM;IACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,yGAAyG,CAAC,CAAC;CAChI;AAED,SAAgB,2BAA2B,CAAC,EAA8B;IACtE,IAAI,CAAC,qBAAa,EAAE;QAChB,OAAO;KACV;IACD,IAAM,WAAW,GAAI,OAAO,CAAC,oBAAoB,CAAwB,CAAC;IAC1E,WAAW,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAAC;AACnD,CAAC;AAND,kEAMC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\n\r\n// Don't reference modules from these directly. Use only for types.\r\n// This is to avoid requiring the actual module if the NO_DIAGNOSTIC_CHANNEL env is present\r\nimport * as DiagChannelPublishers from \"diagnostic-channel-publishers\";\r\nimport * as DiagChannel from \"diagnostic-channel\";\r\nimport { AsyncScopeManager } from \"../AsyncHooksScopeManager\";\r\nimport Logging = require(\"../../Library/Logging\");\r\nimport { JsonConfig } from \"../../Library/JsonConfig\";\r\n\r\nexport const IsInitialized = !JsonConfig.getInstance().noDiagnosticChannel;\r\nconst TAG = \"DiagnosticChannel\";\r\n\r\nif (IsInitialized) {\r\n const publishers: typeof DiagChannelPublishers = require(\"diagnostic-channel-publishers\");\r\n const individualOptOuts: string = JsonConfig.getInstance().noPatchModules;\r\n const unpatchedModules = individualOptOuts.split(\",\");\r\n const modules: {[key: string] : any} = {\r\n bunyan: publishers.bunyan,\r\n console: publishers.console,\r\n mongodb: publishers.mongodb,\r\n mongodbCore: publishers.mongodbCore,\r\n mysql: publishers.mysql,\r\n redis: publishers.redis,\r\n pg: publishers.pg,\r\n pgPool: publishers.pgPool,\r\n winston: publishers.winston,\r\n azuresdk: publishers.azuresdk\r\n };\r\n for (const mod in modules) {\r\n if (unpatchedModules.indexOf(mod) === -1) {\r\n modules[mod].enable();\r\n Logging.info(TAG, `Subscribed to ${mod} events`);\r\n }\r\n }\r\n if (unpatchedModules.length > 0) {\r\n Logging.info(TAG, \"Some modules will not be patched\", unpatchedModules);\r\n }\r\n} else {\r\n Logging.info(TAG, \"Not subscribing to dependency autocollection because APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL was set\");\r\n}\r\n\r\nexport function registerContextPreservation(cb: (cb: Function) => Function) {\r\n if (!IsInitialized) {\r\n return;\r\n }\r\n const diagChannel = (require(\"diagnostic-channel\") as typeof DiagChannel);\r\n diagChannel.channel.addContextPreservation(cb);\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.d.ts new file mode 100644 index 0000000..b4237a3 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.d.ts @@ -0,0 +1,5 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +import { IStandardEvent } from "diagnostic-channel"; +import { mongodb } from "diagnostic-channel-publishers"; +export declare const subscriber: (event: IStandardEvent) => void; +export declare function enable(enabled: boolean, client: TelemetryClient): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js new file mode 100644 index 0000000..6af97e4 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enable = exports.subscriber = void 0; +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var subscriber = function (event) { + if (event.data.event.commandName === "ismaster") { + // suppress noisy ismaster commands + return; + } + clients.forEach(function (client) { + var dbName = (event.data.startedData && event.data.startedData.databaseName) || "Unknown database"; + client.trackDependency({ + target: dbName, + data: event.data.event.commandName, + name: event.data.event.commandName, + duration: event.data.event.duration, + success: event.data.succeeded, + /* TODO: transmit result code from mongo */ + resultCode: event.data.succeeded ? "0" : "1", + time: event.data.startedData.time, + dependencyTypeName: "mongodb" + }); + }); +}; +exports.subscriber = subscriber; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("mongodb", exports.subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.MONGODB); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("mongodb", exports.subscriber); + } + } +} +exports.enable = enable; +//# sourceMappingURL=mongodb.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js.map new file mode 100644 index 0000000..d1b9a63 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mongodb.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/mongodb.sub.ts"],"names":[],"mappings":";;;AAGA,0DAAwE;AACxE,yDAAyE;AAIzE,IAAI,OAAO,GAAsB,EAAE,CAAC;AAE7B,IAAM,UAAU,GAAG,UAAC,KAAyC;IAChE,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,KAAK,UAAU,EAAE;QAC7C,mCAAmC;QACnC,OAAO;KACV;IACD,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;QAC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AC,CAAC;SACN;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACxB;SAAM;QACH,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,SAAS,EAAE,kBAAU,CAAC,CAAC;SAC9C;KACJ;AACL,CAAC;AArBD,wBAqBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { mongodb } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nexport const subscriber = (event: IStandardEvent) => {\r\n if (event.data.event.commandName === \"ismaster\") {\r\n // suppress noisy ismaster commands\r\n return;\r\n }\r\n clients.forEach((client) => {\r\n const dbName = (event.data.startedData && event.data.startedData.databaseName) || \"Unknown database\";\r\n client.trackDependency(\r\n {\r\n target: dbName,\r\n data: event.data.event.commandName,\r\n name: event.data.event.commandName,\r\n duration: event.data.event.duration,\r\n success: event.data.succeeded,\r\n /* TODO: transmit result code from mongo */\r\n resultCode: event.data.succeeded ? \"0\" : \"1\",\r\n time: event.data.startedData.time,\r\n dependencyTypeName: \"mongodb\"\r\n });\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"mongodb\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.MONGODB);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"mongodb\", subscriber);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.d.ts new file mode 100644 index 0000000..dd6afe3 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.d.ts @@ -0,0 +1,5 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +import { IStandardEvent } from "diagnostic-channel"; +import { mysql } from "diagnostic-channel-publishers"; +export declare const subscriber: (event: IStandardEvent) => void; +export declare function enable(enabled: boolean, client: TelemetryClient): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js new file mode 100644 index 0000000..92f7e5a --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enable = exports.subscriber = void 0; +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var subscriber = function (event) { + clients.forEach(function (client) { + var queryObj = event.data.query || {}; + var sqlString = queryObj.sql || "Unknown query"; + var success = !event.data.err; + var connection = queryObj._connection || {}; + var connectionConfig = connection.config || {}; + var dbName = connectionConfig.socketPath ? connectionConfig.socketPath : (connectionConfig.host || "localhost") + ":" + connectionConfig.port; + client.trackDependency({ + target: dbName, + data: sqlString, + name: sqlString, + duration: event.data.duration, + success: success, + /* TODO: transmit result code from mysql */ + resultCode: success ? "0" : "1", + time: event.data.time, + dependencyTypeName: "mysql" + }); + }); +}; +exports.subscriber = subscriber; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("mysql", exports.subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.MYSQL); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("mysql", exports.subscriber); + } + } +} +exports.enable = enable; +//# sourceMappingURL=mysql.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js.map new file mode 100644 index 0000000..13a1b32 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/mysql.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mysql.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/mysql.sub.ts"],"names":[],"mappings":";;;AAGA,0DAAwE;AACxE,yDAAuE;AAIvE,IAAI,OAAO,GAAsB,EAAE,CAAC;AAE7B,IAAM,UAAU,GAAG,UAAC,KAAuC;IAC9D,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;QACnB,IAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;QACxC,IAAM,SAAS,GAAG,QAAQ,CAAC,GAAG,IAAI,eAAe,CAAC;QAClD,IAAM,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC;QAEhC,IAAM,UAAU,GAAG,QAAQ,CAAC,WAAW,IAAI,EAAE,CAAC;QAC9C,IAAM,gBAAgB,GAAG,UAAU,CAAC,MAAM,IAAI,EAAE,CAAC;QACjD,IAAM,MAAM,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC,CA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CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAU,CAAC,CAAC;SAC5C;KACJ;AACL,CAAC;AArBD,wBAqBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport {channel, IStandardEvent, trueFilter} from \"diagnostic-channel\";\r\n\r\nimport {mysql} from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nexport const subscriber = (event: IStandardEvent) => {\r\n clients.forEach((client) => {\r\n const queryObj = event.data.query || {};\r\n const sqlString = queryObj.sql || \"Unknown query\";\r\n const success = !event.data.err;\r\n\r\n const connection = queryObj._connection || {};\r\n const connectionConfig = connection.config || {};\r\n const dbName = connectionConfig.socketPath ? connectionConfig.socketPath : `${connectionConfig.host || \"localhost\"}:${connectionConfig.port}`;\r\n client.trackDependency(\r\n {\r\n target: dbName,\r\n data: sqlString,\r\n name: sqlString,\r\n duration: event.data.duration,\r\n success: success,\r\n /* TODO: transmit result code from mysql */\r\n resultCode: success? \"0\": \"1\",\r\n time: event.data.time,\r\n dependencyTypeName: \"mysql\"\r\n });\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"mysql\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.MYSQL);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"mysql\", subscriber);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.d.ts new file mode 100644 index 0000000..484b316 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.d.ts @@ -0,0 +1,5 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +import { IStandardEvent } from "diagnostic-channel"; +import { pg } from "diagnostic-channel-publishers"; +export declare const subscriber: (event: IStandardEvent) => void; +export declare function enable(enabled: boolean, client: TelemetryClient): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js new file mode 100644 index 0000000..414eb35 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enable = exports.subscriber = void 0; +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var subscriber = function (event) { + clients.forEach(function (client) { + var q = event.data.query; + var sql = (q.preparable && q.preparable.text) || q.plan || q.text || "unknown query"; + var success = !event.data.error; + var conn = event.data.database.host + ":" + event.data.database.port; + client.trackDependency({ + target: conn, + data: sql, + name: sql, + duration: event.data.duration, + success: success, + resultCode: success ? "0" : "1", + time: event.data.time, + dependencyTypeName: "postgres" + }); + }); +}; +exports.subscriber = subscriber; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("postgres", exports.subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.POSTGRES); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("postgres", exports.subscriber); + } + } +} +exports.enable = enable; +//# sourceMappingURL=postgres.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js.map new file mode 100644 index 0000000..7818209 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/postgres.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"postgres.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/postgres.sub.ts"],"names":[],"mappings":";;;AAGA,0DAAwE;AACxE,yDAAyE;AAIzE,IAAI,OAAO,GAAsB,EAAE,CAAC;AAE7B,IAAM,UAAU,GAAG,UAAC,KAAuC;IAC9D,OAAO,CAAC,OAAO,CAAC,UAAC,MAAM;QACnB,IAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;QAC3B,IAAM,GAAG,GAAG,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,eAAe,CAAC;QACvF,IAAM,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;QAClC,IAAM,IAAI,GAAM,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAM,CAAC;QACvE,MAAM,CAAC,eAAe,CAAC;YACnB,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,GAAG;YACT,IAAI,EAAE,GAAG;YACT,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;YAC7B,OAAO,EAAE,OAAO;YAChB,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;YAC/B,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI;YACrB,kBAAkB,EAAE,UAAU;SACjC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAjBW,QAAA,UAAU,cAiBrB;AAEF,SAAgB,MAAM,CAAC,OAAgB,EAAE,MAAuB;IAC5D,IAAI,OAAO,EAAE;QACT,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QACjD,IAAI,WAAW,EAAE;YACb,OAAO;SACV;QACD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,SAAS,CAAmB,UAAU,EAAE,kBAAU,EAAE,+BAAU,EAAE,UAAC,MAAM,EAAE,OAAO;gBACpF,IAAI,SAAS,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;gBACtC,IAAI,SAAS,EAAE;oBACX,SAAS,CAAC,kBAAkB,CAAC,oCAAwB,CAAC,QAAQ,CAAC,CAAC;iBACnE;YACL,CAAC,CAAC,CAAC;SACN;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACxB;SAAM;QACH,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,UAAU,EAAE,kBAAU,CAAC,CAAC;SAC/C;KACJ;AACL,CAAC;AArBD,wBAqBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { pg } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nexport const subscriber = (event: IStandardEvent) => {\r\n clients.forEach((client) => {\r\n const q = event.data.query;\r\n const sql = (q.preparable && q.preparable.text) || q.plan || q.text || \"unknown query\";\r\n const success = !event.data.error;\r\n const conn = `${event.data.database.host}:${event.data.database.port}`;\r\n client.trackDependency({\r\n target: conn,\r\n data: sql,\r\n name: sql,\r\n duration: event.data.duration,\r\n success: success,\r\n resultCode: success ? \"0\" : \"1\",\r\n time: event.data.time,\r\n dependencyTypeName: \"postgres\"\r\n });\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"postgres\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.POSTGRES);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"postgres\", subscriber);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.d.ts new file mode 100644 index 0000000..c6f2d7e --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.d.ts @@ -0,0 +1,5 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +import { IStandardEvent } from "diagnostic-channel"; +import { redis } from "diagnostic-channel-publishers"; +export declare const subscriber: (event: IStandardEvent) => void; +export declare function enable(enabled: boolean, client: TelemetryClient): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js new file mode 100644 index 0000000..9728974 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enable = exports.subscriber = void 0; +var Constants_1 = require("../../Declarations/Constants"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var subscriber = function (event) { + clients.forEach(function (client) { + if (event.data.commandObj.command === "info") { + // We don't want to report 'info', it's irrelevant + return; + } + client.trackDependency({ + target: event.data.address, + name: event.data.commandObj.command, + data: event.data.commandObj.command, + duration: event.data.duration, + success: !event.data.err, + /* TODO: transmit result code from redis */ + resultCode: event.data.err ? "1" : "0", + time: event.data.time, + dependencyTypeName: "redis" + }); + }); +}; +exports.subscriber = subscriber; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("redis", exports.subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.REDIS); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("redis", exports.subscriber); + } + } +} +exports.enable = enable; +//# sourceMappingURL=redis.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js.map new file mode 100644 index 0000000..2b760ff --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/redis.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"redis.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/redis.sub.ts"],"names":[],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AAM,CAAC,YAAY,EAAE,CAAC;gBACtC,IAAI,SAAS,EAAE;oBACX,SAAS,CAAC,kBAAkB,CAAC,oCAAwB,CAAC,KAAK,CAAC,CAAC;iBAChE;YACL,CAAC,CAAC,CAAC;SACN;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;KACxB;SAAM;QACH,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,IAAI,MAAM,EAAX,CAAW,CAAC,CAAC;QAC7C,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAU,CAAC,CAAC;SAC5C;KACJ;AACL,CAAC;AArBD,wBAqBC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { redis } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nexport const subscriber = (event: IStandardEvent) => {\r\n clients.forEach((client) => {\r\n if (event.data.commandObj.command === \"info\") {\r\n // We don't want to report 'info', it's irrelevant\r\n return;\r\n }\r\n client.trackDependency(\r\n {\r\n target: event.data.address,\r\n name: event.data.commandObj.command,\r\n data: event.data.commandObj.command,\r\n duration: event.data.duration,\r\n success: !event.data.err,\r\n /* TODO: transmit result code from redis */\r\n resultCode: event.data.err ? \"1\" : \"0\",\r\n time: event.data.time,\r\n dependencyTypeName: \"redis\"\r\n });\r\n\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"redis\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.REDIS);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"redis\", subscriber);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.d.ts b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.d.ts new file mode 100644 index 0000000..f659f39 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.d.ts @@ -0,0 +1,3 @@ +import TelemetryClient = require("../../Library/TelemetryClient"); +export declare function enable(enabled: boolean, client: TelemetryClient): void; +export declare function dispose(): void; diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js new file mode 100644 index 0000000..36878fb --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dispose = exports.enable = void 0; +var Constants_1 = require("../../Declarations/Constants"); +var Contracts_1 = require("../../Declarations/Contracts"); +var diagnostic_channel_1 = require("diagnostic-channel"); +var clients = []; +var winstonToAILevelMap = { + syslog: function (og) { + var map = { + emerg: Contracts_1.SeverityLevel.Critical, + alert: Contracts_1.SeverityLevel.Critical, + crit: Contracts_1.SeverityLevel.Critical, + error: Contracts_1.SeverityLevel.Error, + warning: Contracts_1.SeverityLevel.Warning, + notice: Contracts_1.SeverityLevel.Information, + info: Contracts_1.SeverityLevel.Information, + debug: Contracts_1.SeverityLevel.Verbose + }; + return map[og] === undefined ? Contracts_1.SeverityLevel.Information : map[og]; + }, + npm: function (og) { + var map = { + error: Contracts_1.SeverityLevel.Error, + warn: Contracts_1.SeverityLevel.Warning, + info: Contracts_1.SeverityLevel.Information, + verbose: Contracts_1.SeverityLevel.Verbose, + debug: Contracts_1.SeverityLevel.Verbose, + silly: Contracts_1.SeverityLevel.Verbose + }; + return map[og] === undefined ? Contracts_1.SeverityLevel.Information : map[og]; + }, + unknown: function (og) { + return Contracts_1.SeverityLevel.Information; + } +}; +var subscriber = function (event) { + var message = event.data.message; + clients.forEach(function (client) { + if (message instanceof Error) { + client.trackException({ + exception: message, + properties: event.data.meta + }); + } + else { + var AIlevel = winstonToAILevelMap[event.data.levelKind](event.data.level); + client.trackTrace({ + message: message, + severity: AIlevel, + properties: event.data.meta + }); + } + }); +}; +function enable(enabled, client) { + if (enabled) { + var clientFound = clients.find(function (c) { return c == client; }); + if (clientFound) { + return; + } + if (clients.length === 0) { + diagnostic_channel_1.channel.subscribe("winston", subscriber, diagnostic_channel_1.trueFilter, function (module, version) { + var statsbeat = client.getStatsbeat(); + if (statsbeat) { + statsbeat.addInstrumentation(Constants_1.StatsbeatInstrumentation.WINSTON); + } + }); + } + clients.push(client); + } + else { + clients = clients.filter(function (c) { return c != client; }); + if (clients.length === 0) { + diagnostic_channel_1.channel.unsubscribe("winston", subscriber); + } + } +} +exports.enable = enable; +function dispose() { + diagnostic_channel_1.channel.unsubscribe("winston", subscriber); + clients = []; +} +exports.dispose = dispose; +//# sourceMappingURL=winston.sub.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js.map b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js.map new file mode 100644 index 0000000..11d0035 --- /dev/null +++ b/node_modules/applicationinsights/out/AutoCollection/diagnostic-channel/winston.sub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"winston.sub.js","sourceRoot":"","sources":["../../../AutoCollection/diagnostic-channel/winston.sub.ts"],"names":[],"mappings":";;;AAGA,0DAAwE;AACxE,0DAA6D;AAE7D,yDAAyE;AAIzE,I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AI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,4BAAO,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;SAC9C;KACJ;AACL,CAAC;AArBD,wBAqBC;AAED,SAAgB,OAAO;IACnB,4BAAO,CAAC,WAAW,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAC3C,OAAO,GAAG,EAAE,CAAC;AACjB,CAAC;AAHD,0BAGC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license. See LICENSE file in the project root for details.\r\nimport TelemetryClient = require(\"../../Library/TelemetryClient\");\r\nimport { StatsbeatInstrumentation } from \"../../Declarations/Constants\";\r\nimport { SeverityLevel } from \"../../Declarations/Contracts\";\r\n\r\nimport { channel, IStandardEvent, trueFilter } from \"diagnostic-channel\";\r\n\r\nimport { winston } from \"diagnostic-channel-publishers\";\r\n\r\nlet clients: TelemetryClient[] = [];\r\n\r\nconst winstonToAILevelMap: { [key: string]: (og: string) => number } = {\r\n syslog(og: string) {\r\n const map: { [key: string]: number } = {\r\n emerg: SeverityLevel.Critical,\r\n alert: SeverityLevel.Critical,\r\n crit: SeverityLevel.Critical,\r\n error: SeverityLevel.Error,\r\n warning: SeverityLevel.Warning,\r\n notice: SeverityLevel.Information,\r\n info: SeverityLevel.Information,\r\n debug: SeverityLevel.Verbose\r\n };\r\n\r\n return map[og] === undefined ? SeverityLevel.Information : map[og];\r\n },\r\n npm(og: string) {\r\n const map: { [key: string]: number } = {\r\n error: SeverityLevel.Error,\r\n warn: SeverityLevel.Warning,\r\n info: SeverityLevel.Information,\r\n verbose: SeverityLevel.Verbose,\r\n debug: SeverityLevel.Verbose,\r\n silly: SeverityLevel.Verbose\r\n };\r\n\r\n return map[og] === undefined ? SeverityLevel.Information : map[og];\r\n },\r\n unknown(og: string) {\r\n return SeverityLevel.Information;\r\n }\r\n};\r\n\r\nconst subscriber = (event: IStandardEvent) => {\r\n const message = event.data.message as Error | string;\r\n clients.forEach((client) => {\r\n if (message instanceof Error) {\r\n client.trackException({\r\n exception: message,\r\n properties: event.data.meta\r\n });\r\n } else {\r\n const AIlevel = winstonToAILevelMap[event.data.levelKind](event.data.level);\r\n client.trackTrace({\r\n message: message,\r\n severity: AIlevel,\r\n properties: event.data.meta\r\n });\r\n }\r\n });\r\n};\r\n\r\nexport function enable(enabled: boolean, client: TelemetryClient) {\r\n if (enabled) {\r\n let clientFound = clients.find(c => c == client);\r\n if (clientFound) {\r\n return;\r\n }\r\n if (clients.length === 0) {\r\n channel.subscribe(\"winston\", subscriber, trueFilter, (module, version) => {\r\n let statsbeat = client.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.addInstrumentation(StatsbeatInstrumentation.WINSTON);\r\n }\r\n });\r\n }\r\n clients.push(client);\r\n } else {\r\n clients = clients.filter((c) => c != client);\r\n if (clients.length === 0) {\r\n channel.unsubscribe(\"winston\", subscriber);\r\n }\r\n }\r\n}\r\n\r\nexport function dispose() {\r\n channel.unsubscribe(\"winston\", subscriber);\r\n clients = [];\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/DataModel.d.ts b/node_modules/applicationinsights/out/Bootstrap/DataModel.d.ts new file mode 100644 index 0000000..daf9de1 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DataModel.d.ts @@ -0,0 +1,47 @@ +export interface AgentLogger { + log(message?: any, ...optional: any[]): void; + error(message?: any, ...optional: any[]): void; +} +export declare const DiagnosticMessageId: { + attachSuccessful: string; + sdkExists: string; + missingIkey: string; + setupAlreadyCalled: string; + prefixFailed: string; + aadEnabled: string; + unknownError: string; +}; +export declare const enum SeverityLevel { + ERROR = "ERROR", + WARN = "WARN", + INFO = "INFO" +} +export interface DiagnosticLog { + /** + * UTC + */ + time?: string; + /** + * Log severity, INFO, WARN, ERROR + */ + level?: SeverityLevel; + /** + * The logger writing this message. Usually the fully-qualified class or package name + */ + logger?: string; + /** + * The log message + */ + message: string; + /** + * Exception (as string) + */ + exception?: string; + /** + * Any custom data related to the error/application/operation. Each field should have a string value + * Examples: operation, siteName, ikey, extensionVersion, sdkVersion, subscriptionId + */ + properties: { + [key: string]: string; + }; +} diff --git a/node_modules/applicationinsights/out/Bootstrap/DataModel.js b/node_modules/applicationinsights/out/Bootstrap/DataModel.js new file mode 100644 index 0000000..047abae --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DataModel.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagnosticMessageId = void 0; +exports.DiagnosticMessageId = { + "attachSuccessful": "3000", + "sdkExists": "3001", + "missingIkey": "3002", + "setupAlreadyCalled": "3003", + "prefixFailed": "3004", + "aadEnabled": "3005", + "unknownError": "3006" +}; +//# sourceMappingURL=DataModel.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/DataModel.js.map b/node_modules/applicationinsights/out/Bootstrap/DataModel.js.map new file mode 100644 index 0000000..847cf85 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DataModel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DataModel.js","sourceRoot":"","sources":["../../Bootstrap/DataModel.ts"],"names":[],"mappings":";;;AAKa,QAAA,mBAAmB,GAAG;IAC/B,kBAAkB,EAAE,MAAM;IAC1B,WAAW,EAAE,MAAM;IACnB,aAAa,EAAE,MAAM;IACrB,oBAAoB,EAAE,MAAM;IAC5B,cAAc,EAAE,MAAM;IACtB,YAAY,EAAE,MAAM;IACpB,cAAc,EAAE,MAAM;CACzB,CAAA","sourcesContent":["export interface AgentLogger {\r\n log(message?: any, ...optional: any[]): void;\r\n error(message?: any, ...optional: any[]): void;\r\n}\r\n\r\nexport const DiagnosticMessageId = {\r\n \"attachSuccessful\": \"3000\",\r\n \"sdkExists\": \"3001\",\r\n \"missingIkey\": \"3002\",\r\n \"setupAlreadyCalled\": \"3003\",\r\n \"prefixFailed\": \"3004\",\r\n \"aadEnabled\": \"3005\",\r\n \"unknownError\": \"3006\"\r\n}\r\n\r\nexport const enum SeverityLevel {\r\n ERROR = \"ERROR\",\r\n WARN = \"WARN\",\r\n INFO = \"INFO\"\r\n}\r\n\r\nexport interface DiagnosticLog {\r\n /**\r\n * UTC\r\n */\r\n time?: string;\r\n\r\n /**\r\n * Log severity, INFO, WARN, ERROR\r\n */\r\n level?: SeverityLevel;\r\n\r\n /**\r\n * The logger writing this message. Usually the fully-qualified class or package name\r\n */\r\n logger?: string;\r\n\r\n /**\r\n * The log message\r\n */\r\n message: string;\r\n\r\n /**\r\n * Exception (as string)\r\n */\r\n exception?: string\r\n\r\n /**\r\n * Any custom data related to the error/application/operation. Each field should have a string value\r\n * Examples: operation, siteName, ikey, extensionVersion, sdkVersion, subscriptionId\r\n */\r\n properties: { [key: string]: string };\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Default.d.ts b/node_modules/applicationinsights/out/Bootstrap/Default.d.ts new file mode 100644 index 0000000..492cdbb --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Default.d.ts @@ -0,0 +1,22 @@ +import * as azureCoreAuth from "@azure/core-auth"; +import * as types from "../applicationinsights"; +import { StatusLogger } from "./StatusLogger"; +import { DiagnosticLogger } from "./DiagnosticLogger"; +import Config = require("../Library/Config"); +export declare const defaultConfig: Config; +/** + * Sets the attach-time logger + * @param logger logger which implements the `AgentLogger` interface + */ +export declare function setLogger(logger: DiagnosticLogger): DiagnosticLogger; +/** + * Sets the string which is prefixed to the existing sdkVersion, e.g. `ad_`, `alr_` + * @param prefix string prefix, including underscore. Defaults to `ud_` + */ +export declare function setUsagePrefix(prefix: string): void; +export declare function setStatusLogger(statusLogger: StatusLogger): void; +/** + * Try to setup and start this app insights instance if attach is enabled. + * @param aadTokenCredential Optional AAD credential + */ +export declare function setupAndStart(aadTokenCredential?: azureCoreAuth.TokenCredential, isAzureFunction?: boolean): typeof types | null; diff --git a/node_modules/applicationinsights/out/Bootstrap/Default.js b/node_modules/applicationinsights/out/Bootstrap/Default.js new file mode 100644 index 0000000..1928a18 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Default.js @@ -0,0 +1,179 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setupAndStart = exports.setStatusLogger = exports.setUsagePrefix = exports.setLogger = exports.defaultConfig = void 0; +var Helpers = require("./Helpers"); +var Constants = require("../Declarations/Constants"); +var StatusLogger_1 = require("./StatusLogger"); +var DiagnosticLogger_1 = require("./DiagnosticLogger"); +var Config = require("../Library/Config"); +var DataModel_1 = require("./DataModel"); +// Private configuration vars +var _appInsights; +var _prefix = "ud_"; // Unknown, Default +exports.defaultConfig = new Config(); // Will read env variables, expose for Agent initialization +var _instrumentationKey = exports.defaultConfig.instrumentationKey; +var _logger = new DiagnosticLogger_1.DiagnosticLogger(console, _instrumentationKey); +var _statusLogger = new StatusLogger_1.StatusLogger(console, _instrumentationKey); +// Env var local constants +var forceStart = process.env.APPLICATIONINSIGHTS_FORCE_START === "true"; +/** + * Sets the attach-time logger + * @param logger logger which implements the `AgentLogger` interface + */ +function setLogger(logger) { + return _logger = logger; +} +exports.setLogger = setLogger; +/** + * Sets the string which is prefixed to the existing sdkVersion, e.g. `ad_`, `alr_` + * @param prefix string prefix, including underscore. Defaults to `ud_` + */ +function setUsagePrefix(prefix) { + _prefix = prefix; +} +exports.setUsagePrefix = setUsagePrefix; +function setStatusLogger(statusLogger) { + _statusLogger = statusLogger; +} +exports.setStatusLogger = setStatusLogger; +/** + * Try to setup and start this app insights instance if attach is enabled. + * @param aadTokenCredential Optional AAD credential + */ +function setupAndStart(aadTokenCredential, isAzureFunction) { + // If app already contains SDK, skip agent attach + if (!forceStart && Helpers.sdkAlreadyExists(_logger)) { + _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, SDKPresent: true, Reason: "Application Insights SDK already exists." })); + return null; + } + if (!exports.defaultConfig.instrumentationKey) { + var diagnosticLog = { + message: "Application Insights wanted to be started, but no Connection String was provided", + properties: { + "msgId": DataModel_1.DiagnosticMessageId.missingIkey + } + }; + _logger.logError(diagnosticLog); + _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, Reason: diagnosticLog.message })); + return null; + } + try { + _appInsights = require("../applicationinsights"); + if (_appInsights.defaultClient) { + // setupAndStart was already called, return the result + var diagnosticLog_1 = { + message: "Setup was attempted on the Application Insights Client multiple times. Aborting and returning the first client instance.", + properties: { + "msgId": DataModel_1.DiagnosticMessageId.setupAlreadyCalled + } + }; + _logger.logError(diagnosticLog_1); + return _appInsights; + } + var prefixInternalSdkVersion = function (envelope, _contextObjects) { + try { + var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion; + envelope.tags[appInsightsSDKVersion] = _prefix + envelope.tags[appInsightsSDKVersion]; + } + catch (e) { + var diagnosticLog_2 = { + message: "Error prefixing SDK version.", + exception: e, + properties: { + "msgId": DataModel_1.DiagnosticMessageId.prefixFailed + } + }; + _logger.logError(diagnosticLog_2); + } + return true; + }; + var copyOverPrefixInternalSdkVersionToHeartBeatMetric = function (envelope, _contextObjects) { + var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion; + var sdkVersion = envelope.tags[appInsightsSDKVersion] || ""; + if (envelope.name === Constants.HeartBeatMetricName) { + (envelope.data.baseData).properties = (envelope.data.baseData).properties || {}; + (envelope.data.baseData).properties["sdk"] = sdkVersion; + } + return true; + }; + // Instrument the SDK + // Azure Functions + if (isAzureFunction) { + // Agent will always run in parallel with Azure Functions .NET Agent, disable requests and exceptions to avoid duplication of telemetry + _appInsights.setup().setSendLiveMetrics(false) + .setAutoCollectPerformance(false) + .setAutoCollectPreAggregatedMetrics(false) + .setAutoCollectIncomingRequestAzureFunctions(false) + .setAutoCollectRequests(false) + .setAutoCollectExceptions(false) + .setAutoCollectDependencies(true) + .setAutoCollectHeartbeat(true) + .setUseDiskRetryCaching(true); + } + // App Services + else { + _appInsights.setup().setSendLiveMetrics(true) + .setAutoCollectPerformance(true) + .setAutoCollectPreAggregatedMetrics(true) + .setAutoCollectIncomingRequestAzureFunctions(false) + .setAutoCollectRequests(true) + .setAutoCollectDependencies(true) + .setAutoCollectExceptions(true) + .setAutoCollectHeartbeat(true) + .setUseDiskRetryCaching(true); + } + _appInsights.defaultClient.setAutoPopulateAzureProperties(true); + _appInsights.defaultClient.addTelemetryProcessor(prefixInternalSdkVersion); + _appInsights.defaultClient.addTelemetryProcessor(copyOverPrefixInternalSdkVersionToHeartBeatMetric); + if (aadTokenCredential) { + var diagnosticLog_3 = { + message: "Application Insights using AAD Token Credential.", + properties: { + "msgId": DataModel_1.DiagnosticMessageId.aadEnabled + } + }; + _logger.logMessage(diagnosticLog_3); + _appInsights.defaultClient.config.aadTokenCredential = aadTokenCredential; + } + _appInsights.start(); + // Add attach flag in Statsbeat + var statsbeat = _appInsights.defaultClient.getStatsbeat(); + if (statsbeat) { + statsbeat.setCodelessAttach(); + } + // Agent successfully instrumented the SDK + var diagnosticLog = { + message: "Application Insights was started succesfully.", + properties: { + "msgId": DataModel_1.DiagnosticMessageId.attachSuccessful + } + }; + _logger.logMessage(diagnosticLog); + _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: true })); + } + catch (e) { + var diagnosticLog = { + message: "Error setting up Application Insights.", + exception: e, + properties: { + "msgId": DataModel_1.DiagnosticMessageId.unknownError + } + }; + _logger.logError(diagnosticLog); + _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, Reason: "Error setting up Application Insights: " + (e && e.message) })); + } + return _appInsights; +} +exports.setupAndStart = setupAndStart; +//# sourceMappingURL=Default.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Default.js.map b/node_modules/applicationinsights/out/Bootstrap/Default.js.map new file mode 100644 index 0000000..2d61ceb --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Default.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Default.js","sourceRoot":"","sources":["../../Bootstrap/Default.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAGA,mCAAqC;AACrC,qDAAwD;AACxD,+CAA8C;AAC9C,uDAAsD;AACtD,0CAA6C;AAC7C,yCAAiE;AAEjE,6BAA6B;AAC7B,IAAI,YAAiC,CAAC;AACtC,IAAI,OAAO,GAAG,KAAK,CAAC,CAAC,mBAAmB;AAE3B,QAAA,aAAa,GAAG,IAAI,MAAM,EAAE,CAAC,CAAC,2DAA2D;AACtG,IAAM,mBAAmB,GAAG,qBAAa,CAAC,kBAAkB,CAAC;AAC7D,IAAI,OAAO,GAAqB,IAAI,mCAAgB,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;AACnF,IAAI,aAAa,GAAiB,IAAI,2BAAY,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;AAEjF,0BAA0B;AAC1B,IAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,KAAK,MAAM,CAAC;AAG1E;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAwB;IAC9C,OAAO,OAAO,GAAG,MAAM,CAAC;AAC5B,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,cAAc,CAAC,MAAc;IACzC,OAAO,GAAG,MAAM,CAAC;AACrB,CAAC;AAFD,wCAEC;AAED,SAAgB,eAAe,CAAC,YAA0B;IACtD,aAAa,GAAG,YAAY,CAAC;AACjC,CAAC;AAFD,0CAEC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAC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AO,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;QAClC,aAAa,CAAC,SAAS,uBAChB,2BAAY,CAAC,cAAc,KAC9B,4BAA4B,EAAE,IAAI,IACpC,CAAC;KACN;IAAC,OAAO,CAAC,EAAE;QACR,IAAM,aAAa,GAAkB;YACjC,OAAO,EAAE,wCAAwC;YACjD,SAAS,EAAE,CAAC;YACZ,UAAU,EAAE;gBACR,OAAO,EAAE,+BAAmB,CAAC,YAAY;aAC5C;SACJ,CAAC;QACF,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;QAChC,aAAa,CAAC,SAAS,uBAChB,2BAAY,CAAC,cAAc,KAC9B,4BAA4B,EAAE,KAAK,EACnC,MAAM,EAAE,6CAA0C,CAAC,IAAI,CAAC,CAAC,OAAO,CAAE,IACpE,CAAA;KACL;IACD,OAAO,YAAY,CAAC;AACxB,CAAC;AAjJD,sCAiJC","sourcesContent":["import * as azureCoreAuth from \"@azure/core-auth\";\r\n\r\nimport * as types from \"../applicationinsights\";\r\nimport * as Helpers from \"./Helpers\";\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport { StatusLogger } from \"./StatusLogger\";\r\nimport { DiagnosticLogger } from \"./DiagnosticLogger\";\r\nimport Config = require(\"../Library/Config\");\r\nimport { DiagnosticLog, DiagnosticMessageId } from \"./DataModel\";\r\n\r\n// Private configuration vars\r\nlet _appInsights: typeof types | null;\r\nlet _prefix = \"ud_\"; // Unknown, Default\r\n\r\nexport const defaultConfig = new Config(); // Will read env variables, expose for Agent initialization\r\nconst _instrumentationKey = defaultConfig.instrumentationKey;\r\nlet _logger: DiagnosticLogger = new DiagnosticLogger(console, _instrumentationKey);\r\nlet _statusLogger: StatusLogger = new StatusLogger(console, _instrumentationKey);\r\n\r\n// Env var local constants\r\nconst forceStart = process.env.APPLICATIONINSIGHTS_FORCE_START === \"true\";\r\n\r\n\r\n/**\r\n * Sets the attach-time logger\r\n * @param logger logger which implements the `AgentLogger` interface\r\n */\r\nexport function setLogger(logger: DiagnosticLogger) {\r\n return _logger = logger;\r\n}\r\n\r\n/**\r\n * Sets the string which is prefixed to the existing sdkVersion, e.g. `ad_`, `alr_`\r\n * @param prefix string prefix, including underscore. Defaults to `ud_`\r\n */\r\nexport function setUsagePrefix(prefix: string) {\r\n _prefix = prefix;\r\n}\r\n\r\nexport function setStatusLogger(statusLogger: StatusLogger) {\r\n _statusLogger = statusLogger;\r\n}\r\n\r\n/**\r\n * Try to setup and start this app insights instance if attach is enabled.\r\n * @param aadTokenCredential Optional AAD credential\r\n */\r\nexport function setupAndStart(aadTokenCredential?: azureCoreAuth.TokenCredential, isAzureFunction?: boolean): typeof types | null {\r\n // If app already contains SDK, skip agent attach\r\n if (!forceStart && Helpers.sdkAlreadyExists(_logger)) {\r\n _statusLogger.logStatus({\r\n ...StatusLogger.DEFAULT_STATUS,\r\n AgentInitializedSuccessfully: false,\r\n SDKPresent: true,\r\n Reason: \"Application Insights SDK already exists.\"\r\n })\r\n return null;\r\n }\r\n if (!defaultConfig.instrumentationKey) {\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Application Insights wanted to be started, but no Connection String was provided\",\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.missingIkey\r\n }\r\n };\r\n _logger.logError(diagnosticLog);\r\n _statusLogger.logStatus({\r\n ...StatusLogger.DEFAULT_STATUS,\r\n AgentInitializedSuccessfully: false,\r\n Reason: diagnosticLog.message\r\n });\r\n return null;\r\n }\r\n\r\n try {\r\n _appInsights = require(\"../applicationinsights\");\r\n if (_appInsights.defaultClient) {\r\n // setupAndStart was already called, return the result\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Setup was attempted on the Application Insights Client multiple times. Aborting and returning the first client instance.\",\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.setupAlreadyCalled\r\n }\r\n };\r\n _logger.logError(diagnosticLog);\r\n return _appInsights;\r\n }\r\n\r\n const prefixInternalSdkVersion = function (envelope: types.Contracts.Envelope, _contextObjects: Object) {\r\n try {\r\n var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion;\r\n envelope.tags[appInsightsSDKVersion] = _prefix + envelope.tags[appInsightsSDKVersion];\r\n } catch (e) {\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Error prefixing SDK version.\",\r\n exception: e,\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.prefixFailed\r\n }\r\n };\r\n _logger.logError(diagnosticLog);\r\n }\r\n return true;\r\n }\r\n\r\n const copyOverPrefixInternalSdkVersionToHeartBeatMetric = function (envelope: types.Contracts.Envelope, _contextObjects: Object) {\r\n var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion;\r\n const sdkVersion = envelope.tags[appInsightsSDKVersion] || \"\";\r\n if (envelope.name === Constants.HeartBeatMetricName) {\r\n ((envelope.data as any).baseData).properties = ((envelope.data as any).baseData).properties || {};\r\n ((envelope.data as any).baseData).properties[\"sdk\"] = sdkVersion;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n // Instrument the SDK\r\n // Azure Functions\r\n if (isAzureFunction) {\r\n // Agent will always run in parallel with Azure Functions .NET Agent, disable requests and exceptions to avoid duplication of telemetry\r\n _appInsights.setup().setSendLiveMetrics(false)\r\n .setAutoCollectPerformance(false)\r\n .setAutoCollectPreAggregatedMetrics(false)\r\n .setAutoCollectIncomingRequestAzureFunctions(false)\r\n .setAutoCollectRequests(false)\r\n .setAutoCollectExceptions(false)\r\n .setAutoCollectDependencies(true)\r\n .setAutoCollectHeartbeat(true)\r\n .setUseDiskRetryCaching(true);\r\n }\r\n // App Services\r\n else {\r\n _appInsights.setup().setSendLiveMetrics(true)\r\n .setAutoCollectPerformance(true)\r\n .setAutoCollectPreAggregatedMetrics(true)\r\n .setAutoCollectIncomingRequestAzureFunctions(false)\r\n .setAutoCollectRequests(true)\r\n .setAutoCollectDependencies(true)\r\n .setAutoCollectExceptions(true)\r\n .setAutoCollectHeartbeat(true)\r\n .setUseDiskRetryCaching(true);\r\n }\r\n\r\n _appInsights.defaultClient.setAutoPopulateAzureProperties(true);\r\n _appInsights.defaultClient.addTelemetryProcessor(prefixInternalSdkVersion);\r\n _appInsights.defaultClient.addTelemetryProcessor(copyOverPrefixInternalSdkVersionToHeartBeatMetric);\r\n if (aadTokenCredential) {\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Application Insights using AAD Token Credential.\",\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.aadEnabled\r\n }\r\n };\r\n _logger.logMessage(diagnosticLog);\r\n _appInsights.defaultClient.config.aadTokenCredential = aadTokenCredential;\r\n }\r\n\r\n _appInsights.start();\r\n // Add attach flag in Statsbeat\r\n let statsbeat = _appInsights.defaultClient.getStatsbeat();\r\n if (statsbeat) {\r\n statsbeat.setCodelessAttach();\r\n }\r\n\r\n // Agent successfully instrumented the SDK\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Application Insights was started succesfully.\",\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.attachSuccessful\r\n }\r\n };\r\n _logger.logMessage(diagnosticLog);\r\n _statusLogger.logStatus({\r\n ...StatusLogger.DEFAULT_STATUS,\r\n AgentInitializedSuccessfully: true\r\n });\r\n } catch (e) {\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Error setting up Application Insights.\",\r\n exception: e,\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.unknownError\r\n }\r\n };\r\n _logger.logError(diagnosticLog);\r\n _statusLogger.logStatus({\r\n ...StatusLogger.DEFAULT_STATUS,\r\n AgentInitializedSuccessfully: false,\r\n Reason: `Error setting up Application Insights: ${e && e.message}`\r\n })\r\n }\r\n return _appInsights;\r\n}\r\n\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.d.ts b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.d.ts new file mode 100644 index 0000000..e91d474 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.d.ts @@ -0,0 +1,10 @@ +import * as DataModel from "./DataModel"; +export declare class DiagnosticLogger { + private _writer; + static readonly DEFAULT_FILE_NAME: string; + static readonly DEFAULT_LOG_DIR: string; + private _defaultProperties; + constructor(_writer?: DataModel.AgentLogger, instrumentationKey?: string); + logMessage(diagnosticLog: DataModel.DiagnosticLog): void; + logError(diagnosticLog: DataModel.DiagnosticLog): void; +} diff --git a/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js new file mode 100644 index 0000000..0f9af14 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DiagnosticLogger = void 0; +var path = require("path"); +var FileHelpers_1 = require("./Helpers/FileHelpers"); +var Constants_1 = require("../Declarations/Constants"); +var Util = require("../Library/Util"); +var LOGGER_NAME = "applicationinsights.extension.diagnostics"; +var DiagnosticLogger = /** @class */ (function () { + function DiagnosticLogger(_writer, instrumentationKey) { + if (_writer === void 0) { _writer = console; } + if (instrumentationKey === void 0) { instrumentationKey = "unknown"; } + this._writer = _writer; + this._defaultProperties = { + language: "nodejs", + operation: "Startup", + siteName: process.env.WEBSITE_SITE_NAME, + ikey: "unknown", + extensionVersion: process.env.ApplicationInsightsAgent_EXTENSION_VERSION, + sdkVersion: Constants_1.APPLICATION_INSIGHTS_SDK_VERSION, + subscriptionId: process.env.WEBSITE_OWNER_NAME ? process.env.WEBSITE_OWNER_NAME.split("+")[0] : null + }; + this._defaultProperties.ikey = instrumentationKey; + } + DiagnosticLogger.prototype.logMessage = function (diagnosticLog) { + var props = Object.assign({}, this._defaultProperties, diagnosticLog.properties); + var diagnosticMessage = { + properties: props, + logger: LOGGER_NAME, + message: diagnosticLog.message, + level: "INFO" /* INFO */, + time: new Date().toUTCString() + }; + this._writer.log(diagnosticMessage); + }; + DiagnosticLogger.prototype.logError = function (diagnosticLog) { + var message = diagnosticLog.message; + if (diagnosticLog.exception) { + message += " Error: " + Util.dumpObj(diagnosticLog.exception); + } + var props = Object.assign({}, this._defaultProperties, diagnosticLog.properties); + var diagnosticMessage = { + properties: props, + logger: LOGGER_NAME, + message: message, + level: "ERROR" /* ERROR */, + time: new Date().toUTCString() + }; + this._writer.error(diagnosticMessage); + }; + DiagnosticLogger.DEFAULT_FILE_NAME = "application-insights-extension.log"; + DiagnosticLogger.DEFAULT_LOG_DIR = process.env.APPLICATIONINSIGHTS_LOGDIR || path.join(FileHelpers_1.homedir, "LogFiles/ApplicationInsights"); + return DiagnosticLogger; +}()); +exports.DiagnosticLogger = DiagnosticLogger; +//# sourceMappingURL=DiagnosticLogger.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js.map b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js.map new file mode 100644 index 0000000..27118a0 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/DiagnosticLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DiagnosticLogger.js","sourceRoot":"","sources":["../../Bootstrap/DiagnosticLogger.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;AAEb,2BAA6B;AAE7B,qDAAgD;AAChD,uDAA6E;AAC7E,sCAAyC;AAEzC,IAAM,WAAW,GAAG,2CAA2C,CAAC;AAEhE;IAaI,0BAAoB,OAAwC,EAAE,kBAAsC;QAAhF,wBAAA,EAAA,iBAAwC;QAAE,mCAAA,EAAA,8BAAsC;QAAhF,YAAO,GAAP,OAAO,CAAiC;QAVpD,uBAAkB,GAA8B;YACpD,QAAQ,EAAE,QAAQ;YAClB,SAAS,EAAE,SAAS;YACpB,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB;YACvC,IAAI,EAAE,SAAS;YACf,gBAAgB,EAAE,OAAO,CAAC,GAAG,CAAC,0CAA0C;YACxE,UAAU,EAAE,4CAAgC;YAC5C,cAAc,EAAE,OAAO,CAAC,GAA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sB,kCAAiB,GAAW,oCAAoC,CAAC;IACjE,gCAAe,GAAW,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAAI,IAAI,CAAC,IAAI,CAAC,qBAAO,EAAE,8BAA8B,CAAC,CAAC;IA0ClJ,uBAAC;CAAA,AA5CD,IA4CC;AA5CY,4CAAgB","sourcesContent":["\"use strict\";\r\n\r\nimport * as path from \"path\";\r\nimport * as DataModel from \"./DataModel\";\r\nimport { homedir } from \"./Helpers/FileHelpers\";\r\nimport { APPLICATION_INSIGHTS_SDK_VERSION } from \"../Declarations/Constants\";\r\nimport Util = require(\"../Library/Util\");\r\n\r\nconst LOGGER_NAME = \"applicationinsights.extension.diagnostics\";\r\n\r\nexport class DiagnosticLogger {\r\n public static readonly DEFAULT_FILE_NAME: string = \"application-insights-extension.log\";\r\n public static readonly DEFAULT_LOG_DIR: string = process.env.APPLICATIONINSIGHTS_LOGDIR || path.join(homedir, \"LogFiles/ApplicationInsights\");\r\n private _defaultProperties: { [key: string]: string } = {\r\n language: \"nodejs\",\r\n operation: \"Startup\",\r\n siteName: process.env.WEBSITE_SITE_NAME,\r\n ikey: \"unknown\",\r\n extensionVersion: process.env.ApplicationInsightsAgent_EXTENSION_VERSION,\r\n sdkVersion: APPLICATION_INSIGHTS_SDK_VERSION,\r\n subscriptionId: process.env.WEBSITE_OWNER_NAME ? process.env.WEBSITE_OWNER_NAME.split(\"+\")[0] : null\r\n }\r\n\r\n constructor(private _writer: DataModel.AgentLogger = console, instrumentationKey: string = \"unknown\") {\r\n this._defaultProperties.ikey = instrumentationKey;\r\n }\r\n\r\n logMessage(diagnosticLog: DataModel.DiagnosticLog) {\r\n let props = Object.assign({}, this._defaultProperties, diagnosticLog.properties);\r\n const diagnosticMessage: DataModel.DiagnosticLog = {\r\n properties: props,\r\n logger: LOGGER_NAME,\r\n message: diagnosticLog.message,\r\n level: DataModel.SeverityLevel.INFO,\r\n time: new Date().toUTCString()\r\n };\r\n this._writer.log(diagnosticMessage);\r\n }\r\n\r\n logError(diagnosticLog: DataModel.DiagnosticLog) {\r\n let message: string = diagnosticLog.message;\r\n if (diagnosticLog.exception) {\r\n message += ` Error: ${Util.dumpObj(diagnosticLog.exception)}`;\r\n }\r\n let props = Object.assign({}, this._defaultProperties, diagnosticLog.properties);\r\n const diagnosticMessage: DataModel.DiagnosticLog = {\r\n properties: props,\r\n logger: LOGGER_NAME,\r\n message: message,\r\n level: DataModel.SeverityLevel.ERROR,\r\n time: new Date().toUTCString()\r\n };\r\n this._writer.error(diagnosticMessage);\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/FileWriter.d.ts b/node_modules/applicationinsights/out/Bootstrap/FileWriter.d.ts new file mode 100644 index 0000000..7063150 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/FileWriter.d.ts @@ -0,0 +1,27 @@ +import * as DataModel from "./DataModel"; +export interface FileWriterOptions { + append: boolean; + deleteOnExit: boolean; + sizeLimit: number; + renamePolicy: "rolling" | "overwrite" | "stop"; + chmod: number; +} +export declare const homedir: string; +export declare class FileWriter implements DataModel.AgentLogger { + private _filepath; + private _filename; + callback: (_err: Error) => void; + private _ready; + private _options; + private static _fullpathsToDelete; + private static _listenerAttached; + private static DEFAULT_OPTIONS; + static isNodeVersionCompatible(): boolean; + constructor(_filepath: string, _filename: string, options?: Partial); + log(message: any): void; + error(message: any): void; + private _appendFile; + private _writeFile; + private static _addCloseHandler; + private _shouldRenameFile; +} diff --git a/node_modules/applicationinsights/out/Bootstrap/FileWriter.js b/node_modules/applicationinsights/out/Bootstrap/FileWriter.js new file mode 100644 index 0000000..110cabc --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/FileWriter.js @@ -0,0 +1,140 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileWriter = exports.homedir = void 0; +var path = require("path"); +var fs = require("fs"); +var FileHelpers = require("./Helpers/FileHelpers"); +exports.homedir = FileHelpers.homedir; +var FileWriter = /** @class */ (function () { + // leave at "keep at single file only", "write up to certain size limit", "clear old file on process startup" + function FileWriter(_filepath, _filename, options) { + this._filepath = _filepath; + this._filename = _filename; + this.callback = function (_err) { }; // no-op + this._ready = false; + this._options = __assign(__assign({}, FileWriter.DEFAULT_OPTIONS), options); + this._ready = FileWriter.isNodeVersionCompatible() && FileHelpers.makeStatusDirs(this._filepath); + if (this._options.deleteOnExit) { + FileWriter._addCloseHandler(); + FileWriter._fullpathsToDelete.push(path.join(this._filepath, this._filename)); + } + } + FileWriter.isNodeVersionCompatible = function () { + var majVer = process.versions.node.split(".")[0]; + return parseInt(majVer) >= 1; + }; + FileWriter.prototype.log = function (message) { + var _this = this; + if (this._ready) { + var data_1 = typeof message === "object" + ? JSON.stringify(message) + : message.toString(); + // Check if existing file needs to be renamed + this._shouldRenameFile(function (err, shouldRename) { + if (err) + return; + if (shouldRename) { + if (_this._options.renamePolicy === "rolling") { + FileHelpers.renameCurrentFile(_this._filepath, _this._filename, function (renameErr, renamedFullpath) { + if (renameErr) + return; + FileWriter._fullpathsToDelete.push(renamedFullpath); + _this._options.append + ? _this._appendFile(data_1 + "\n") + : _this._writeFile(data_1); + }); + } + else if (_this._options.renamePolicy === "overwrite") { + // Clear the current file + _this._writeFile(data_1); + } + else if (_this._options.renamePolicy === "stop") { + // Stop future logging + _this._ready = false; + } + } + else { + _this._options.append + ? _this._appendFile(data_1 + "\n") + : _this._writeFile(data_1); + } + }); + } + }; + FileWriter.prototype.error = function (message) { + this.log(message); + }; + FileWriter.prototype._appendFile = function (message) { + var _this = this; + var fullpath = path.join(this._filepath, this._filename); + fs.appendFile(fullpath, message, function (err) { + _this.callback(err); + }); + }; + FileWriter.prototype._writeFile = function (message) { + var fullpath = path.join(this._filepath, this._filename); + fs.writeFile(fullpath, message, { mode: this._options.chmod }, this.callback); + }; + FileWriter._addCloseHandler = function () { + if (!FileWriter._listenerAttached) { + process.on("exit", function () { + FileWriter._fullpathsToDelete.forEach(function (filename) { + try { + fs.unlinkSync(filename); + } + catch (err) { /** ignore errors */ } + }); + }); + FileWriter._listenerAttached = true; + } + }; + FileWriter.prototype._shouldRenameFile = function (callback) { + var _this = this; + var fullpath = path.join(this._filepath, this._filename); + fs.stat(fullpath, function (err, stats) { + if (err) { + if (err.code === "ENOENT" && typeof callback === "function") { + callback(null, false); + } + else if (typeof callback === "function") { + callback(err); + } + return; + } + if (stats.size > _this._options.sizeLimit) { + callback(null, true); + } + else { + var createDate = new Date(stats.birthtime); + var currentDate = new Date(); + var result = (createDate.getUTCDate() !== currentDate.getUTCDate() || + createDate.getUTCMonth() !== currentDate.getUTCMonth() || + createDate.getUTCFullYear() !== currentDate.getUTCFullYear()); + callback(null, result); + } + }); + }; + FileWriter._fullpathsToDelete = []; + FileWriter._listenerAttached = false; + FileWriter.DEFAULT_OPTIONS = { + append: false, + deleteOnExit: true, + sizeLimit: 10 * 1024, + renamePolicy: "stop", + chmod: 420 // rw/r/r + }; + return FileWriter; +}()); +exports.FileWriter = FileWriter; +//# sourceMappingURL=FileWriter.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/FileWriter.js.map b/node_modules/applicationinsights/out/Bootstrap/FileWriter.js.map new file mode 100644 index 0000000..8dc05c6 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/FileWriter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileWriter.js","sourceRoot":"","sources":["../../Bootstrap/FileWriter.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;;;;;AAEb,2BAA6B;AAC7B,uBAAyB;AAGzB,mDAAqD;AAUxC,QAAA,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC;AAE3C;IAmBI,6GAA6G;IAC7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CAAC,GAAG,CAAC,CAAC;iBACjB;gBACD,OAAO;aACV;YAED,IAAI,KAAK,CAAC,IAAI,GAAG,KAAI,CAAC,QAAQ,CAAC,SAAS,EAAE;gBACtC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;aACxB;iBAAM;gBACH,IAAM,UAAU,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC7C,IAAM,WAAW,GAAG,IAAI,IAAI,EAAE,CAAC;gBAC/B,IAAM,MAAM,GAAG,CACX,UAAU,CAAC,UAAU,EAAE,KAAK,WAAW,CAAC,UAAU,EAAE;oBACpD,UAAU,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE;oBACtD,UAAU,CAAC,cAAc,EAAE,KAAK,WAAW,CAAC,cAAc,EAAE,CAC/D,CAAC;gBACF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;aAC1B;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAnHc,6BAAkB,GAAa,EAAE,CAAC;IAClC,4BAAiB,GAAG,KAAK,CAAC;IAC1B,0BAAe,GAAsB;QAChD,MAAM,EAAE,KAAK;QACb,YAAY,EAAE,IAAI;QAClB,SAAS,EAAE,EAAE,GAAC,IAAI;QAClB,YAAY,EAAE,MAAM;QACpB,KAAK,EAAE,GAAK,CAAC,SAAS;KACzB,CAAA;IA4GL,iBAAC;CAAA,AAxHD,IAwHC;AAxHY,gCAAU","sourcesContent":["\"use strict\";\r\n\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport * as os from \"os\";\r\nimport * as DataModel from \"./DataModel\";\r\nimport * as FileHelpers from \"./Helpers/FileHelpers\";\r\n\r\nexport interface FileWriterOptions {\r\n append: boolean; // Overwrite or append on file write (false)\r\n deleteOnExit: boolean; // (true)\r\n sizeLimit: number; // (10 KB)\r\n renamePolicy: \"rolling\" | \"overwrite\" | \"stop\"; // What to do with file when it exceeds time/size limits\r\n chmod: number; // Linux only\r\n}\r\n\r\nexport const homedir = FileHelpers.homedir;\r\n\r\nexport class FileWriter implements DataModel.AgentLogger {\r\n public callback = (_err: Error) => { }; // no-op\r\n private _ready = false;\r\n private _options: FileWriterOptions;\r\n private static _fullpathsToDelete: string[] = [];\r\n private static _listenerAttached = false;\r\n private static DEFAULT_OPTIONS: FileWriterOptions = {\r\n append: false,\r\n deleteOnExit: true,\r\n sizeLimit: 10*1024,\r\n renamePolicy: \"stop\",\r\n chmod: 0o644 // rw/r/r\r\n }\r\n\r\n public static isNodeVersionCompatible() {\r\n const majVer = process.versions.node.split(\".\")[0];\r\n return parseInt(majVer) >= 1;\r\n }\r\n\r\n // leave at \"keep at single file only\", \"write up to certain size limit\", \"clear old file on process startup\"\r\n constructor(private _filepath: string, private _filename: string, options?: Partial) {\r\n this._options = { ...FileWriter.DEFAULT_OPTIONS, ...options };\r\n this._ready = FileWriter.isNodeVersionCompatible() && FileHelpers.makeStatusDirs(this._filepath);\r\n if (this._options.deleteOnExit) {\r\n FileWriter._addCloseHandler();\r\n FileWriter._fullpathsToDelete.push(path.join(this._filepath, this._filename));\r\n }\r\n }\r\n\r\n public log(message: any) {\r\n if (this._ready) {\r\n let data = typeof message === \"object\"\r\n ? JSON.stringify(message)\r\n : message.toString();\r\n\r\n // Check if existing file needs to be renamed\r\n this._shouldRenameFile((err, shouldRename) => {\r\n if (err) return;\r\n\r\n if (shouldRename) {\r\n if (this._options.renamePolicy === \"rolling\") {\r\n FileHelpers.renameCurrentFile(this._filepath, this._filename, (renameErr, renamedFullpath) => {\r\n if (renameErr) return;\r\n FileWriter._fullpathsToDelete.push(renamedFullpath);\r\n this._options.append\r\n ? this._appendFile(data + \"\\n\")\r\n : this._writeFile(data);\r\n });\r\n } else if (this._options.renamePolicy === \"overwrite\") {\r\n // Clear the current file\r\n this._writeFile(data);\r\n } else if (this._options.renamePolicy === \"stop\") {\r\n // Stop future logging\r\n this._ready = false;\r\n }\r\n } else {\r\n this._options.append\r\n ? this._appendFile(data + \"\\n\")\r\n : this._writeFile(data);\r\n }\r\n });\r\n\r\n }\r\n }\r\n\r\n public error(message: any) {\r\n this.log(message);\r\n }\r\n\r\n private _appendFile(message: string) {\r\n const fullpath = path.join(this._filepath, this._filename);\r\n fs.appendFile(fullpath, message, (err) => {\r\n this.callback(err);\r\n });\r\n }\r\n\r\n private _writeFile(message: string) {\r\n const fullpath = path.join(this._filepath, this._filename);\r\n fs.writeFile(fullpath, message, { mode: this._options.chmod }, this.callback);\r\n }\r\n\r\n private static _addCloseHandler() {\r\n if (!FileWriter._listenerAttached) {\r\n process.on(\"exit\", () => {\r\n FileWriter._fullpathsToDelete.forEach((filename) => {\r\n try {\r\n fs.unlinkSync(filename);\r\n } catch (err) { /** ignore errors */ }\r\n });\r\n });\r\n FileWriter._listenerAttached = true;\r\n }\r\n }\r\n\r\n private _shouldRenameFile(callback?: (err: Error | null, shouldRename?: boolean) => void): void {\r\n const fullpath = path.join(this._filepath, this._filename);\r\n fs.stat(fullpath, (err, stats) => {\r\n if (err) {\r\n if (err.code === \"ENOENT\" && typeof callback === \"function\") {\r\n callback(null, false);\r\n } else if (typeof callback === \"function\") {\r\n callback(err);\r\n }\r\n return;\r\n }\r\n\r\n if (stats.size > this._options.sizeLimit) {\r\n callback(null, true);\r\n } else {\r\n const createDate = new Date(stats.birthtime);\r\n const currentDate = new Date();\r\n const result = (\r\n createDate.getUTCDate() !== currentDate.getUTCDate() ||\r\n createDate.getUTCMonth() !== currentDate.getUTCMonth() ||\r\n createDate.getUTCFullYear() !== currentDate.getUTCFullYear()\r\n );\r\n callback(null, result);\r\n }\r\n });\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers.d.ts b/node_modules/applicationinsights/out/Bootstrap/Helpers.d.ts new file mode 100644 index 0000000..a9eacfd --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers.d.ts @@ -0,0 +1,2 @@ +import { DiagnosticLogger } from "./DiagnosticLogger"; +export declare function sdkAlreadyExists(_logger: DiagnosticLogger): boolean; diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers.js b/node_modules/applicationinsights/out/Bootstrap/Helpers.js new file mode 100644 index 0000000..ddda885 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sdkAlreadyExists = void 0; +var DataModel_1 = require("./DataModel"); +function sdkAlreadyExists(_logger) { + try { + // appInstance should either resolve to user SDK or crash. If it resolves to attach SDK, user probably modified their NODE_PATH + var appInstance = void 0; + try { + // Node 8.9+ + appInstance = require.resolve("applicationinsights", { paths: [process.cwd()] }); + } + catch (e) { + // Node <8.9 + appInstance = require.resolve(process.cwd() + "/node_modules/applicationinsights"); + } + // If loaded instance is in Azure machine home path do not attach the SDK, this means customer already instrumented their app + if (appInstance.indexOf("home") > -1) { + var diagnosticLog = { + message: "Application Insights SDK already exists. Module is already installed in this application; not re-attaching. Installed SDK location: " + appInstance, + properties: { + "msgId": DataModel_1.DiagnosticMessageId.sdkExists + } + }; + _logger.logError(diagnosticLog); + return true; + } + else { + // ApplicationInsights could be loaded outside of customer application, attach in this case + return false; + } + } + catch (e) { + // crashed while trying to resolve "applicationinsights", so SDK does not exist. Attach appinsights + return false; + } +} +exports.sdkAlreadyExists = sdkAlreadyExists; +//# sourceMappingURL=Helpers.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers.js.map b/node_modules/applicationinsights/out/Bootstrap/Helpers.js.map new file mode 100644 index 0000000..2b052d6 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Helpers.js","sourceRoot":"","sources":["../../Bootstrap/Helpers.ts"],"names":[],"mappings":";;;AAAA,yCAAiE;AAGjE,SAAgB,gBAAgB,CAAC,OAAyB;IACtD,IAAI;QACA,+HAA+H;QAC/H,IAAI,WAAW,SAAQ,CAAC;QACxB,IAAI;YACA,YAAY;YACZ,WAAW,GAAI,OAAO,CAAC,OAAe,CAAC,qBAAqB,EAAE,EAAE,KAAK,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;SAC7F;QAAC,OAAO,CAAC,EAAE;YACR,YAAY;YACZ,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,mCAAmC,CAAC,CAAC;SACtF;QACD,6HAA6H;QAC7H,IAAI,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE;YAClC,IAAM,aAAa,GAAkB;gBACjC,OAAO,EAAE,sIAAsI,GAAG,WAAW;gBAC7J,UAAU,EAAE;oBACR,OAAO,EAAE,+BAAmB,CAAC,SAAS;iBACzC;aACJ,CAAC;YACF,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;YAChC,OAAO,IAAI,CAAC;SACf;aACI;YACD,2FAA2F;YAC3F,OAAO,KAAK,CAAC;SAChB;KACJ;IAAC,OAAO,CAAC,EAAE;QACR,mGAAmG;QACnG,OAAO,KAAK,CAAC;KAChB;AACL,CAAC;AA9BD,4CA8BC","sourcesContent":["import { DiagnosticLog, DiagnosticMessageId } from \"./DataModel\";\r\nimport { DiagnosticLogger } from \"./DiagnosticLogger\";\r\n\r\nexport function sdkAlreadyExists(_logger: DiagnosticLogger): boolean {\r\n try {\r\n // appInstance should either resolve to user SDK or crash. If it resolves to attach SDK, user probably modified their NODE_PATH\r\n let appInstance: string;\r\n try {\r\n // Node 8.9+\r\n appInstance = (require.resolve as any)(\"applicationinsights\", { paths: [process.cwd()] });\r\n } catch (e) {\r\n // Node <8.9\r\n appInstance = require.resolve(process.cwd() + \"/node_modules/applicationinsights\");\r\n }\r\n // If loaded instance is in Azure machine home path do not attach the SDK, this means customer already instrumented their app\r\n if (appInstance.indexOf(\"home\") > -1) {\r\n const diagnosticLog: DiagnosticLog = {\r\n message: \"Application Insights SDK already exists. Module is already installed in this application; not re-attaching. Installed SDK location: \" + appInstance,\r\n properties: {\r\n \"msgId\": DiagnosticMessageId.sdkExists\r\n }\r\n };\r\n _logger.logError(diagnosticLog);\r\n return true;\r\n }\r\n else {\r\n // ApplicationInsights could be loaded outside of customer application, attach in this case\r\n return false;\r\n }\r\n } catch (e) {\r\n // crashed while trying to resolve \"applicationinsights\", so SDK does not exist. Attach appinsights\r\n return false;\r\n }\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.d.ts b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.d.ts new file mode 100644 index 0000000..45b3747 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.d.ts @@ -0,0 +1,3 @@ +export declare const homedir: string; +export declare function makeStatusDirs(filepath: string): boolean; +export declare function renameCurrentFile(filepath: string, filename: string, callback?: (err: Error | null, destfullpath?: string) => void): void; diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js new file mode 100644 index 0000000..c70531f --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js @@ -0,0 +1,71 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.renameCurrentFile = exports.makeStatusDirs = exports.homedir = void 0; +var path = require("path"); +var fs = require("fs"); +var os = require("os"); +exports.homedir = os.homedir ? os.homedir() : (process.env[(process.platform == "win32") ? "USERPROFILE" : "HOME"]); +/** + * Zero dependencies: recursive mkdir + */ +function mkDirByPathSync(HOME_DIR, targetDir, _a) { + var _b = _a === void 0 ? {} : _a, _c = _b.isRelativeToScript, isRelativeToScript = _c === void 0 ? false : _c; + var sep = path.sep; + var initDir = path.isAbsolute(targetDir) ? sep : ""; + var baseDir = isRelativeToScript ? __dirname : "."; + return targetDir.split(sep).reduce(function (parentDir, childDir) { + var curDir = path.resolve(baseDir, parentDir, childDir); + try { + // Don't try to recreate homedir + if (HOME_DIR.indexOf(curDir) === -1) { + fs.mkdirSync(curDir); + } + } + catch (err) { + if (err.code === "EEXIST") { // curDir already exists! + return curDir; + } + // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows. + if (err.code === "ENOENT") { // Throw the original parentDir error on curDir `ENOENT` failure. + throw new Error("EACCES: permission denied, mkdir \"" + parentDir + "\""); + } + var caughtErr = ["EACCES", "EPERM", "EISDIR"].indexOf(err.code) > -1; + if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) { + throw err; // Throw if it's just the last created dir. + } + } + return curDir; + }, initDir); +} +function makeStatusDirs(filepath) { + try { + mkDirByPathSync(exports.homedir, filepath.replace(/\\/g, path.sep).replace(/\//g, path.sep)); + return true; + } + catch (e) { + console.error("Error creating Application Insights status folder", e); + return false; + } +} +exports.makeStatusDirs = makeStatusDirs; +function renameCurrentFile(filepath, filename, callback) { + var fullpath = path.join(filepath, filename); + var basename = path.basename(filename, path.extname(filename)); + var stats = fs.stat(fullpath, function (statsErr, stats) { + if (statsErr) { + return callback(statsErr); + } + var createDate = new Date(stats.birthtime); + var destfilename = basename + "-" + + createDate.toISOString().replace(/[T:\.]/g, "_").replace("Z", "") + + path.extname(filename) + ".old"; + var destfullpath = path.join(filepath, destfilename); + fs.rename(fullpath, destfullpath, function (renameErr) { + if (typeof callback === "function") { + callback(renameErr, destfullpath); + } + }); + }); +} +exports.renameCurrentFile = renameCurrentFile; +//# sourceMappingURL=FileHelpers.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js.map b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js.map new file mode 100644 index 0000000..e144a6b --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Helpers/FileHelpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileHelpers.js","sourceRoot":"","sources":["../../../Bootstrap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C,QAAQ,CAAC,CAAC;SAC7B;QAED,IAAM,UAAU,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QAC7C,IAAM,YAAY,GAAG,QAAQ,GAAG,GAAG;YAC/B,UAAU,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;YACjE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;QACpC,IAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;QACvD,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,UAAC,SAAS;YACxC,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gBAChC,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;aACrC;QACL,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC;AAnBD,8CAmBC","sourcesContent":["\"use strict\";\r\n\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport * as os from \"os\";\r\n\r\nexport const homedir = os.homedir ? os.homedir() : (process.env[(process.platform == \"win32\") ? \"USERPROFILE\" : \"HOME\"]);\r\n\r\n/**\r\n * Zero dependencies: recursive mkdir\r\n */\r\nfunction mkDirByPathSync(HOME_DIR: string, targetDir: string, { isRelativeToScript = false } = {}) {\r\n const sep = path.sep;\r\n const initDir = path.isAbsolute(targetDir) ? sep : \"\";\r\n const baseDir = isRelativeToScript ? __dirname : \".\";\r\n\r\n return targetDir.split(sep).reduce((parentDir, childDir) => {\r\n const curDir = path.resolve(baseDir, parentDir, childDir);\r\n try {\r\n // Don't try to recreate homedir\r\n if (HOME_DIR.indexOf(curDir) === -1) {\r\n fs.mkdirSync(curDir);\r\n }\r\n } catch (err) {\r\n if (err.code === \"EEXIST\") { // curDir already exists!\r\n return curDir;\r\n }\r\n\r\n // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.\r\n if (err.code === \"ENOENT\") { // Throw the original parentDir error on curDir `ENOENT` failure.\r\n throw new Error(`EACCES: permission denied, mkdir \"${parentDir}\"`);\r\n }\r\n\r\n const caughtErr = [\"EACCES\", \"EPERM\", \"EISDIR\"].indexOf(err.code) > -1;\r\n if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {\r\n throw err; // Throw if it's just the last created dir.\r\n }\r\n }\r\n return curDir;\r\n\r\n }, initDir);\r\n}\r\n\r\nexport function makeStatusDirs(filepath: string): boolean {\r\n try {\r\n mkDirByPathSync(homedir, filepath.replace(/\\\\/g, path.sep).replace(/\\//g, path.sep));\r\n return true;\r\n } catch (e) {\r\n console.error(\"Error creating Application Insights status folder\", e);\r\n return false;\r\n }\r\n}\r\n\r\n\r\n\r\nexport function renameCurrentFile(filepath: string, filename: string, callback?: (err: Error | null, destfullpath?: string) => void): void {\r\n const fullpath = path.join(filepath, filename);\r\n const basename = path.basename(filename, path.extname(filename));\r\n const stats = fs.stat(fullpath, (statsErr, stats) => {\r\n if (statsErr) {\r\n return callback(statsErr);\r\n }\r\n\r\n const createDate = new Date(stats.birthtime);\r\n const destfilename = basename + \"-\" +\r\n createDate.toISOString().replace(/[T:\\.]/g, \"_\").replace(\"Z\", \"\") +\r\n path.extname(filename) + \".old\";\r\n const destfullpath = path.join(filepath, destfilename);\r\n fs.rename(fullpath, destfullpath, (renameErr) => {\r\n if (typeof callback === \"function\") {\r\n callback(renameErr, destfullpath);\r\n }\r\n });\r\n });\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/NoopLogger.d.ts b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.d.ts new file mode 100644 index 0000000..acb05d1 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.d.ts @@ -0,0 +1,5 @@ +import * as DataModel from "./DataModel"; +export declare class NoopLogger implements DataModel.AgentLogger { + log(message?: any, ...optional: any[]): void; + error(message?: any, ...optional: any[]): void; +} diff --git a/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js new file mode 100644 index 0000000..87aa627 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopLogger = void 0; +var NoopLogger = /** @class */ (function () { + function NoopLogger() { + } + NoopLogger.prototype.log = function (message) { + var optional = []; + for (var _i = 1; _i < arguments.length; _i++) { + optional[_i - 1] = arguments[_i]; + } + }; + NoopLogger.prototype.error = function (message) { + var optional = []; + for (var _i = 1; _i < arguments.length; _i++) { + optional[_i - 1] = arguments[_i]; + } + }; + return NoopLogger; +}()); +exports.NoopLogger = NoopLogger; +//# sourceMappingURL=NoopLogger.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js.map b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js.map new file mode 100644 index 0000000..c24a2ce --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/NoopLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NoopLogger.js","sourceRoot":"","sources":["../../Bootstrap/NoopLogger.ts"],"names":[],"mappings":";;;AAGA;IAAA;IAKA,CAAC;IAJG,wBAAG,GAAH,UAAI,OAAa;QAAE,kBAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,iCAAkB;;IACrC,CAAC;IACD,0BAAK,GAAL,UAAM,OAAa;QAAE,kBAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,iCAAkB;;IACvC,CAAC;IACL,iBAAC;AAAD,CAAC,AALD,IAKC;AALY,gCAAU","sourcesContent":["import * as DataModel from \"./DataModel\";\r\nimport { FileWriter } from \"./FileWriter\";\r\n\r\nexport class NoopLogger implements DataModel.AgentLogger {\r\n log(message?: any, ...optional: any[]): void {\r\n }\r\n error(message?: any, ...optional: any[]): void {\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Oryx.d.ts b/node_modules/applicationinsights/out/Bootstrap/Oryx.d.ts new file mode 100644 index 0000000..6701e8c --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Oryx.d.ts @@ -0,0 +1,3 @@ +import * as types from "../applicationinsights"; +declare var appInsights: typeof types; +export = appInsights; diff --git a/node_modules/applicationinsights/out/Bootstrap/Oryx.js b/node_modules/applicationinsights/out/Bootstrap/Oryx.js new file mode 100644 index 0000000..e305e49 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Oryx.js @@ -0,0 +1,14 @@ +"use strict"; +var StatusLogger_1 = require("./StatusLogger"); +var DiagnosticLogger_1 = require("./DiagnosticLogger"); +var NoopLogger_1 = require("./NoopLogger"); +var appInsightsLoader = require("./Default"); +appInsightsLoader.setUsagePrefix("alr_"); // App Services Linux Attach +// Set Status.json logger +appInsightsLoader.setStatusLogger(new StatusLogger_1.StatusLogger(new NoopLogger_1.NoopLogger())); +// Set Attach Diagnostic Logger +appInsightsLoader.setLogger(new DiagnosticLogger_1.DiagnosticLogger(new NoopLogger_1.NoopLogger())); +// Start the SDK +var appInsights = appInsightsLoader.setupAndStart(); +module.exports = appInsights; +//# sourceMappingURL=Oryx.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/Oryx.js.map b/node_modules/applicationinsights/out/Bootstrap/Oryx.js.map new file mode 100644 index 0000000..8247d01 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/Oryx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Oryx.js","sourceRoot":"","sources":["../../Bootstrap/Oryx.ts"],"names":[],"mappings":";AACA,+CAA8C;AAC9C,uDAAsD;AACtD,2CAA0C;AAC1C,6CAAgD;AAEhD,iBAAiB,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,4BAA4B;AAEtE,yBAAyB;AACzB,iBAAiB,CAAC,eAAe,CAAC,IAAI,2BAAY,CAAC,IAAI,uBAAU,EAAE,CAAC,CAAC,CAAC;AAEtE,+BAA+B;AAC/B,iBAAiB,CAAC,SAAS,CAAC,IAAI,mCAAgB,CAAC,IAAI,uBAAU,EAAE,CAAC,CAAC,CAAC;AAEpE,gBAAgB;AAChB,IAAI,WAAW,GAAG,iBAAiB,CAAC,aAAa,EAAE,CAAC;AAEpD,iBAAS,WAAW,CAAC","sourcesContent":["import * as types from \"../applicationinsights\"; // needed but unused\r\nimport { StatusLogger } from \"./StatusLogger\";\r\nimport { DiagnosticLogger } from \"./DiagnosticLogger\";\r\nimport { NoopLogger } from \"./NoopLogger\";\r\nimport appInsightsLoader = require(\"./Default\");\r\n\r\nappInsightsLoader.setUsagePrefix(\"alr_\"); // App Services Linux Attach\r\n\r\n// Set Status.json logger\r\nappInsightsLoader.setStatusLogger(new StatusLogger(new NoopLogger()));\r\n\r\n// Set Attach Diagnostic Logger\r\nappInsightsLoader.setLogger(new DiagnosticLogger(new NoopLogger()));\r\n\r\n// Start the SDK\r\nvar appInsights = appInsightsLoader.setupAndStart();\r\n\r\nexport = appInsights;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/StatusLogger.d.ts b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.d.ts new file mode 100644 index 0000000..f469c8b --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.d.ts @@ -0,0 +1,19 @@ +import * as DataModel from "./DataModel"; +export interface StatusContract { + AgentInitializedSuccessfully: boolean; + Reason?: string; + SDKPresent: boolean; + AppType: string; + MachineName: string; + PID: string; + SdkVersion: string; + Ikey: string; +} +export declare class StatusLogger { + _writer: DataModel.AgentLogger; + static readonly DEFAULT_FILE_PATH: string; + static readonly DEFAULT_FILE_NAME: string; + static readonly DEFAULT_STATUS: StatusContract; + constructor(_writer?: DataModel.AgentLogger, instrumentationKey?: string); + logStatus(data: StatusContract, cb?: (err: Error) => void): void; +} diff --git a/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js new file mode 100644 index 0000000..6ca98ab --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StatusLogger = void 0; +var os = require("os"); +var path = require("path"); +var FileWriter_1 = require("./FileWriter"); +var Constants_1 = require("../Declarations/Constants"); +var StatusLogger = /** @class */ (function () { + function StatusLogger(_writer, instrumentationKey) { + if (_writer === void 0) { _writer = console; } + if (instrumentationKey === void 0) { instrumentationKey = "unknown"; } + this._writer = _writer; + StatusLogger.DEFAULT_STATUS.Ikey = instrumentationKey; + } + StatusLogger.prototype.logStatus = function (data, cb) { + if (typeof cb === "function" && this._writer instanceof FileWriter_1.FileWriter) { + this._writer.callback = cb; + } + this._writer.log(data); + }; + StatusLogger.DEFAULT_FILE_PATH = path.join(FileWriter_1.homedir, "status"); + StatusLogger.DEFAULT_FILE_NAME = "status_" + os.hostname() + "_" + process.pid + ".json"; + StatusLogger.DEFAULT_STATUS = { + AgentInitializedSuccessfully: false, + SDKPresent: false, + Ikey: "unknown", + AppType: "node.js", + SdkVersion: Constants_1.APPLICATION_INSIGHTS_SDK_VERSION, + MachineName: os.hostname(), + PID: String(process.pid) + }; + return StatusLogger; +}()); +exports.StatusLogger = StatusLogger; +//# sourceMappingURL=StatusLogger.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js.map b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js.map new file mode 100644 index 0000000..34c64a6 --- /dev/null +++ b/node_modules/applicationinsights/out/Bootstrap/StatusLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StatusLogger.js","sourceRoot":"","sources":["../../Bootstrap/StatusLogger.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;AAEb,uBAAyB;AACzB,2BAA6B;AAG7B,2CAAmD;AACnD,uDAA6E;AAa7E;IAaI,sBAAmB,OAAwC,EAAE,kBAAsC;QAAhF,wBAAA,EAAA,iBAAwC;QAAE,mCAAA,EAAA,8BAAsC;QAAhF,YAAO,GAAP,OAAO,CAAiC;QACvD,YAAY,CAAC,cAAc,CAAC,IAAI,GAAG,kBAAkB,CAAC;IAC1D,CAAC;IAEM,gCAAS,GAAhB,UAAiB,IAAoB,EAAE,EAAyB;QAC5D,IAAI,OAAO,EAAE,KAAK,UAAU,IAAI,IAAI,CAAC,OAAO,YAAY,uBAAU,EAAE;YAChE,IAAI,CAAC,OAAO,CAAC,QAAQ,GAAG,EAAE,CAAC;SAC9B;QACD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IArBsB,8BAAiB,GAAW,IAAI,CAAC,IAAI,CAAC,oBAAO,EAAE,QAAQ,CAAC,CAAC;IACzD,8BAAiB,GAAW,YAAU,EAAE,CAAC,QAAQ,EAAE,SAAI,OAAO,CAAC,GAAG,UAAO,CAAC;IAC1E,2BAAc,GAAmB;QACpD,4BAA4B,EAAE,KAAK;QACnC,UAAU,EAAE,KAAK;QACjB,IAAI,EAAE,SAAS;QACf,OAAO,EAAE,SAAS;QAClB,UAAU,EAAE,4CAAgC;QAC5C,WAAW,EAAE,EAAE,CAAC,QAAQ,EAAE;QAC1B,GAAG,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;KAC3B,CAAA;IAYL,mBAAC;CAAA,AAvBD,IAuBC;AAvBY,oCAAY","sourcesContent":["\"use strict\";\r\n\r\nimport * as os from \"os\";\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport * as DataModel from \"./DataModel\";\r\nimport { FileWriter, homedir } from \"./FileWriter\";\r\nimport { APPLICATION_INSIGHTS_SDK_VERSION } from \"../Declarations/Constants\";\r\n\r\nexport interface StatusContract {\r\n AgentInitializedSuccessfully: boolean;\r\n Reason?: string;\r\n SDKPresent: boolean;\r\n AppType: string;\r\n MachineName: string;\r\n PID: string;\r\n SdkVersion: string;\r\n Ikey: string;\r\n}\r\n\r\nexport class StatusLogger {\r\n public static readonly DEFAULT_FILE_PATH: string = path.join(homedir, \"status\");\r\n public static readonly DEFAULT_FILE_NAME: string = `status_${os.hostname()}_${process.pid}.json`;\r\n public static readonly DEFAULT_STATUS: StatusContract = {\r\n AgentInitializedSuccessfully: false,\r\n SDKPresent: false,\r\n Ikey: \"unknown\",\r\n AppType: \"node.js\",\r\n SdkVersion: APPLICATION_INSIGHTS_SDK_VERSION,\r\n MachineName: os.hostname(),\r\n PID: String(process.pid)\r\n }\r\n\r\n constructor(public _writer: DataModel.AgentLogger = console, instrumentationKey: string = \"unknown\") {\r\n StatusLogger.DEFAULT_STATUS.Ikey = instrumentationKey;\r\n }\r\n\r\n public logStatus(data: StatusContract, cb?: (err: Error) => void) {\r\n if (typeof cb === \"function\" && this._writer instanceof FileWriter) {\r\n this._writer.callback = cb;\r\n }\r\n this._writer.log(data);\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Constants.d.ts b/node_modules/applicationinsights/out/Declarations/Constants.d.ts new file mode 100644 index 0000000..4f746ce --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Constants.d.ts @@ -0,0 +1,119 @@ +import Contracts = require("./Contracts"); +export declare const APPLICATION_INSIGHTS_SDK_VERSION = "2.5.0"; +export declare const DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; +export declare const DEFAULT_LIVEMETRICS_ENDPOINT = "https://rt.services.visualstudio.com"; +export declare const DEFAULT_LIVEMETRICS_HOST = "rt.services.visualstudio.com"; +export declare enum QuickPulseCounter { + COMMITTED_BYTES = "\\Memory\\Committed Bytes", + PROCESSOR_TIME = "\\Processor(_Total)\\% Processor Time", + REQUEST_RATE = "\\ApplicationInsights\\Requests/Sec", + REQUEST_FAILURE_RATE = "\\ApplicationInsights\\Requests Failed/Sec", + REQUEST_DURATION = "\\ApplicationInsights\\Request Duration", + DEPENDENCY_RATE = "\\ApplicationInsights\\Dependency Calls/Sec", + DEPENDENCY_FAILURE_RATE = "\\ApplicationInsights\\Dependency Calls Failed/Sec", + DEPENDENCY_DURATION = "\\ApplicationInsights\\Dependency Call Duration", + EXCEPTION_RATE = "\\ApplicationInsights\\Exceptions/Sec" +} +export declare enum PerformanceCounter { + PRIVATE_BYTES = "\\Process(??APP_WIN32_PROC??)\\Private Bytes", + AVAILABLE_BYTES = "\\Memory\\Available Bytes", + PROCESSOR_TIME = "\\Processor(_Total)\\% Processor Time", + PROCESS_TIME = "\\Process(??APP_WIN32_PROC??)\\% Processor Time", + REQUEST_RATE = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec", + REQUEST_DURATION = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time" +} +export declare enum MetricId { + REQUESTS_DURATION = "requests/duration", + DEPENDENCIES_DURATION = "dependencies/duration", + EXCEPTIONS_COUNT = "exceptions/count", + TRACES_COUNT = "traces/count" +} +/** + * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined* + */ +export declare const PerformanceToQuickPulseCounter: { + [key: string]: QuickPulseCounter; +}; +export declare type QuickPulseDocumentType = "Event" | "Exception" | "Trace" | "Metric" | "Request" | "RemoteDependency" | "Availability" | "PageView"; +export declare type QuickPulseType = "EventTelemetryDocument" | "ExceptionTelemetryDocument" | "TraceTelemetryDocument" | "MetricTelemetryDocument" | "RequestTelemetryDocument" | "DependencyTelemetryDocument" | "AvailabilityTelemetryDocument" | "PageViewTelemetryDocument"; +export declare const QuickPulseDocumentType: { + [key in Contracts.TelemetryTypeKeys]: QuickPulseDocumentType; +}; +export declare const QuickPulseType: { + [key in Contracts.TelemetryTypeKeys]: QuickPulseType; +}; +export declare const TelemetryTypeStringToQuickPulseType: { + [key in Contracts.TelemetryTypeValues]: QuickPulseType; +}; +export declare const TelemetryTypeStringToQuickPulseDocumentType: { + [key in Contracts.TelemetryTypeValues]: QuickPulseDocumentType; +}; +export declare const DependencyTypeName: { + Grpc: string; + Http: string; + InProc: string; + Sql: string; + QueueMessage: string; +}; +export declare const HeartBeatMetricName = "HeartBeat"; +export declare const StatsbeatTelemetryName = "Statsbeat"; +export declare const StatsbeatResourceProvider: { + appsvc: string; + functions: string; + vm: string; + unknown: string; +}; +export declare const StatsbeatAttach: { + codeless: string; + sdk: string; +}; +export declare const StatsbeatCounter: { + REQUEST_SUCCESS: string; + REQUEST_FAILURE: string; + REQUEST_DURATION: string; + RETRY_COUNT: string; + THROTTLE_COUNT: string; + EXCEPTION_COUNT: string; + ATTACH: string; + FEATURE: string; +}; +export declare enum StatsbeatFeature { + NONE = 0, + DISK_RETRY = 1, + AAD_HANDLING = 2, + WEB_SNIPPET = 4 +} +export declare enum StatsbeatInstrumentation { + NONE = 0, + AZURE_CORE_TRACING = 1, + MONGODB = 2, + MYSQL = 4, + REDIS = 8, + POSTGRES = 16, + BUNYAN = 32, + WINSTON = 64, + CONSOLE = 128 +} +export declare enum StatsbeatFeatureType { + Feature = 0, + Instrumentation = 1 +} +export declare enum StatsbeatNetworkCategory { + Breeze = 0, + Quickpulse = 1 +} +export declare const AzNamespace = "az.namespace"; +export declare const MicrosoftEventHub = "Microsoft.EventHub"; +export declare const MessageBusDestination = "message_bus.destination"; +/** + * AI enqueued time attribute. + * @internal + */ +export declare const ENQUEUED_TIME = "enqueuedTime"; +/** + * AI time since enqueued attribute. + * @internal + */ +export declare const TIME_SINCE_ENQUEUED = "timeSinceEnqueued"; +export declare const WEB_INSTRUMENTATION_DEFAULT_SOURCE = "https://js.monitor.azure.com/scripts/b/ai"; +export declare const WEB_INSTRUMENTATION_DEPRECATED_SOURCE = "https://az416426.vo.msecnd.net/scripts/b/ai"; diff --git a/node_modules/applicationinsights/out/Declarations/Constants.js b/node_modules/applicationinsights/out/Declarations/Constants.js new file mode 100644 index 0000000..05d7224 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Constants.js @@ -0,0 +1,174 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WEB_INSTRUMENTATION_DEPRECATED_SOURCE = exports.WEB_INSTRUMENTATION_DEFAULT_SOURCE = exports.TIME_SINCE_ENQUEUED = exports.ENQUEUED_TIME = exports.MessageBusDestination = exports.MicrosoftEventHub = exports.AzNamespace = exports.StatsbeatNetworkCategory = exports.StatsbeatFeatureType = exports.StatsbeatInstrumentation = exports.StatsbeatFeature = exports.StatsbeatCounter = exports.StatsbeatAttach = exports.StatsbeatResourceProvider = exports.StatsbeatTelemetryName = exports.HeartBeatMetricName = exports.DependencyTypeName = exports.TelemetryTypeStringToQuickPulseDocumentType = exports.TelemetryTypeStringToQuickPulseType = exports.QuickPulseType = exports.QuickPulseDocumentType = exports.PerformanceToQuickPulseCounter = exports.MetricId = exports.PerformanceCounter = exports.QuickPulseCounter = exports.DEFAULT_LIVEMETRICS_HOST = exports.DEFAULT_LIVEMETRICS_ENDPOINT = exports.DEFAULT_BREEZE_ENDPOINT = exports.APPLICATION_INSIGHTS_SDK_VERSION = void 0; +exports.APPLICATION_INSIGHTS_SDK_VERSION = "2.5.0"; +exports.DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; +exports.DEFAULT_LIVEMETRICS_ENDPOINT = "https://rt.services.visualstudio.com"; +exports.DEFAULT_LIVEMETRICS_HOST = "rt.services.visualstudio.com"; +var QuickPulseCounter; +(function (QuickPulseCounter) { + // Memory + QuickPulseCounter["COMMITTED_BYTES"] = "\\Memory\\Committed Bytes"; + // CPU + QuickPulseCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time"; + // Request + QuickPulseCounter["REQUEST_RATE"] = "\\ApplicationInsights\\Requests/Sec"; + QuickPulseCounter["REQUEST_FAILURE_RATE"] = "\\ApplicationInsights\\Requests Failed/Sec"; + QuickPulseCounter["REQUEST_DURATION"] = "\\ApplicationInsights\\Request Duration"; + // Dependency + QuickPulseCounter["DEPENDENCY_RATE"] = "\\ApplicationInsights\\Dependency Calls/Sec"; + QuickPulseCounter["DEPENDENCY_FAILURE_RATE"] = "\\ApplicationInsights\\Dependency Calls Failed/Sec"; + QuickPulseCounter["DEPENDENCY_DURATION"] = "\\ApplicationInsights\\Dependency Call Duration"; + // Exception + QuickPulseCounter["EXCEPTION_RATE"] = "\\ApplicationInsights\\Exceptions/Sec"; +})(QuickPulseCounter = exports.QuickPulseCounter || (exports.QuickPulseCounter = {})); +var PerformanceCounter; +(function (PerformanceCounter) { + // Memory + PerformanceCounter["PRIVATE_BYTES"] = "\\Process(??APP_WIN32_PROC??)\\Private Bytes"; + PerformanceCounter["AVAILABLE_BYTES"] = "\\Memory\\Available Bytes"; + // CPU + PerformanceCounter["PROCESSOR_TIME"] = "\\Processor(_Total)\\% Processor Time"; + PerformanceCounter["PROCESS_TIME"] = "\\Process(??APP_WIN32_PROC??)\\% Processor Time"; + // Requests + PerformanceCounter["REQUEST_RATE"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Requests/Sec"; + PerformanceCounter["REQUEST_DURATION"] = "\\ASP.NET Applications(??APP_W3SVC_PROC??)\\Request Execution Time"; +})(PerformanceCounter = exports.PerformanceCounter || (exports.PerformanceCounter = {})); +var MetricId; +(function (MetricId) { + MetricId["REQUESTS_DURATION"] = "requests/duration"; + MetricId["DEPENDENCIES_DURATION"] = "dependencies/duration"; + MetricId["EXCEPTIONS_COUNT"] = "exceptions/count"; + MetricId["TRACES_COUNT"] = "traces/count"; +})(MetricId = exports.MetricId || (exports.MetricId = {})); +/** + * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined* + */ +exports.PerformanceToQuickPulseCounter = (_a = {}, + _a[PerformanceCounter.PROCESSOR_TIME] = QuickPulseCounter.PROCESSOR_TIME, + _a[PerformanceCounter.REQUEST_RATE] = QuickPulseCounter.REQUEST_RATE, + _a[PerformanceCounter.REQUEST_DURATION] = QuickPulseCounter.REQUEST_DURATION, + // Remap quick pulse only counters + _a[QuickPulseCounter.COMMITTED_BYTES] = QuickPulseCounter.COMMITTED_BYTES, + _a[QuickPulseCounter.REQUEST_FAILURE_RATE] = QuickPulseCounter.REQUEST_FAILURE_RATE, + _a[QuickPulseCounter.DEPENDENCY_RATE] = QuickPulseCounter.DEPENDENCY_RATE, + _a[QuickPulseCounter.DEPENDENCY_FAILURE_RATE] = QuickPulseCounter.DEPENDENCY_FAILURE_RATE, + _a[QuickPulseCounter.DEPENDENCY_DURATION] = QuickPulseCounter.DEPENDENCY_DURATION, + _a[QuickPulseCounter.EXCEPTION_RATE] = QuickPulseCounter.EXCEPTION_RATE, + _a); +exports.QuickPulseDocumentType = { + Event: "Event", + Exception: "Exception", + Trace: "Trace", + Metric: "Metric", + Request: "Request", + Dependency: "RemoteDependency", + Availability: "Availability", + PageView: "PageView" +}; +exports.QuickPulseType = { + Event: "EventTelemetryDocument", + Exception: "ExceptionTelemetryDocument", + Trace: "TraceTelemetryDocument", + Metric: "MetricTelemetryDocument", + Request: "RequestTelemetryDocument", + Dependency: "DependencyTelemetryDocument", + Availability: "AvailabilityTelemetryDocument", + PageView: "PageViewTelemetryDocument" +}; +exports.TelemetryTypeStringToQuickPulseType = { + EventData: exports.QuickPulseType.Event, + ExceptionData: exports.QuickPulseType.Exception, + MessageData: exports.QuickPulseType.Trace, + MetricData: exports.QuickPulseType.Metric, + RequestData: exports.QuickPulseType.Request, + RemoteDependencyData: exports.QuickPulseType.Dependency, + AvailabilityData: exports.QuickPulseType.Availability, + PageViewData: exports.QuickPulseType.PageView +}; +exports.TelemetryTypeStringToQuickPulseDocumentType = { + EventData: exports.QuickPulseDocumentType.Event, + ExceptionData: exports.QuickPulseDocumentType.Exception, + MessageData: exports.QuickPulseDocumentType.Trace, + MetricData: exports.QuickPulseDocumentType.Metric, + RequestData: exports.QuickPulseDocumentType.Request, + RemoteDependencyData: exports.QuickPulseDocumentType.Dependency, + AvailabilityData: exports.QuickPulseDocumentType.Availability, + PageViewData: exports.QuickPulseDocumentType.PageView +}; +exports.DependencyTypeName = { + Grpc: "GRPC", + Http: "HTTP", + InProc: "InProc", + Sql: "SQL", + QueueMessage: "Queue Message" +}; +exports.HeartBeatMetricName = "HeartBeat"; +exports.StatsbeatTelemetryName = "Statsbeat"; +exports.StatsbeatResourceProvider = { + appsvc: "appsvc", + functions: "functions", + vm: "vm", + unknown: "unknown" +}; +exports.StatsbeatAttach = { + codeless: "codeless", + sdk: "sdk" +}; +exports.StatsbeatCounter = { + REQUEST_SUCCESS: "Request Success Count", + REQUEST_FAILURE: "Request Failure Count", + REQUEST_DURATION: "Request Duration", + RETRY_COUNT: "Retry Count", + THROTTLE_COUNT: "Throttle Count", + EXCEPTION_COUNT: "Exception Count", + ATTACH: "Attach", + FEATURE: "Feature" +}; +var StatsbeatFeature; +(function (StatsbeatFeature) { + StatsbeatFeature[StatsbeatFeature["NONE"] = 0] = "NONE"; + StatsbeatFeature[StatsbeatFeature["DISK_RETRY"] = 1] = "DISK_RETRY"; + StatsbeatFeature[StatsbeatFeature["AAD_HANDLING"] = 2] = "AAD_HANDLING"; + StatsbeatFeature[StatsbeatFeature["WEB_SNIPPET"] = 4] = "WEB_SNIPPET"; +})(StatsbeatFeature = exports.StatsbeatFeature || (exports.StatsbeatFeature = {})); +var StatsbeatInstrumentation; +(function (StatsbeatInstrumentation) { + StatsbeatInstrumentation[StatsbeatInstrumentation["NONE"] = 0] = "NONE"; + StatsbeatInstrumentation[StatsbeatInstrumentation["AZURE_CORE_TRACING"] = 1] = "AZURE_CORE_TRACING"; + StatsbeatInstrumentation[StatsbeatInstrumentation["MONGODB"] = 2] = "MONGODB"; + StatsbeatInstrumentation[StatsbeatInstrumentation["MYSQL"] = 4] = "MYSQL"; + StatsbeatInstrumentation[StatsbeatInstrumentation["REDIS"] = 8] = "REDIS"; + StatsbeatInstrumentation[StatsbeatInstrumentation["POSTGRES"] = 16] = "POSTGRES"; + StatsbeatInstrumentation[StatsbeatInstrumentation["BUNYAN"] = 32] = "BUNYAN"; + StatsbeatInstrumentation[StatsbeatInstrumentation["WINSTON"] = 64] = "WINSTON"; + StatsbeatInstrumentation[StatsbeatInstrumentation["CONSOLE"] = 128] = "CONSOLE"; +})(StatsbeatInstrumentation = exports.StatsbeatInstrumentation || (exports.StatsbeatInstrumentation = {})); +var StatsbeatFeatureType; +(function (StatsbeatFeatureType) { + StatsbeatFeatureType[StatsbeatFeatureType["Feature"] = 0] = "Feature"; + StatsbeatFeatureType[StatsbeatFeatureType["Instrumentation"] = 1] = "Instrumentation"; +})(StatsbeatFeatureType = exports.StatsbeatFeatureType || (exports.StatsbeatFeatureType = {})); +var StatsbeatNetworkCategory; +(function (StatsbeatNetworkCategory) { + StatsbeatNetworkCategory[StatsbeatNetworkCategory["Breeze"] = 0] = "Breeze"; + StatsbeatNetworkCategory[StatsbeatNetworkCategory["Quickpulse"] = 1] = "Quickpulse"; +})(StatsbeatNetworkCategory = exports.StatsbeatNetworkCategory || (exports.StatsbeatNetworkCategory = {})); +//Azure SDK Span Attributes +exports.AzNamespace = "az.namespace"; +exports.MicrosoftEventHub = "Microsoft.EventHub"; +exports.MessageBusDestination = "message_bus.destination"; +/** + * AI enqueued time attribute. + * @internal + */ +exports.ENQUEUED_TIME = "enqueuedTime"; +/** + * AI time since enqueued attribute. + * @internal + */ +exports.TIME_SINCE_ENQUEUED = "timeSinceEnqueued"; +exports.WEB_INSTRUMENTATION_DEFAULT_SOURCE = "https://js.monitor.azure.com/scripts/b/ai"; +exports.WEB_INSTRUMENTATION_DEPRECATED_SOURCE = "https://az416426.vo.msecnd.net/scripts/b/ai"; +//# sourceMappingURL=Constants.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Constants.js.map b/node_modules/applicationinsights/out/Declarations/Constants.js.map new file mode 100644 index 0000000..1ea48f1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/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gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B;AAED,IAAY,wBAUX;AAVD,WAAY,wBAAwB;IAChC,uEAAQ,CAAA;IACR,mGAAsB,CAAA;IACtB,6EAAW,CAAA;IACX,yEAAS,CAAA;IACT,yEAAS,CAAA;IACT,gFAAa,CAAA;IACb,4EAAW,CAAA;IACX,8EAAY,CAAA;IACZ,+EAAa,CAAA;AACjB,CAAC,EAVW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAUnC;AAED,IAAY,oBAGX;AAHD,WAAY,oBAAoB;IAC5B,qEAAO,CAAA;IACP,qFAAe,CAAA;AACnB,CAAC,EAHW,oBAAoB,GAApB,4BAAoB,KAApB,4BAAoB,QAG/B;AAED,IAAY,wBAGX;AAHD,WAAY,wBAAwB;IAChC,2EAAM,CAAA;IACN,mFAAU,CAAA;AACd,CAAC,EAHW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAGnC;AAED,2BAA2B;AACd,QAAA,WAAW,GAAG,cAAc,CAAC;AAC7B,QAAA,iBAAiB,GAAG,oBAAoB,CAAC;AACzC,QAAA,qBAAqB,GAAG,yBAAyB,CAAC;AAE/D;;;GAGG;AACW,QAAA,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACU,QAAA,mBAAmB,GAAG,mBAAmB,CAAC;AAE1C,QAAA,kCAAkC,GAAE,2CAA2C,CAAC;AAChF,QAAA,qCAAqC,GAAE,6CAA6C,CAAC","sourcesContent":["import Contracts = require(\"./Contracts\")\r\n\r\nexport const APPLICATION_INSIGHTS_SDK_VERSION = \"2.5.0\";\r\nexport const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\r\nexport const DEFAULT_LIVEMETRICS_ENDPOINT = \"https://rt.services.visualstudio.com\";\r\nexport const DEFAULT_LIVEMETRICS_HOST = \"rt.services.visualstudio.com\";\r\n\r\nexport enum QuickPulseCounter {\r\n // Memory\r\n COMMITTED_BYTES = \"\\\\Memory\\\\Committed Bytes\",\r\n\r\n // CPU\r\n PROCESSOR_TIME = \"\\\\Processor(_Total)\\\\% Processor Time\",\r\n\r\n // Request\r\n REQUEST_RATE = \"\\\\ApplicationInsights\\\\Requests\\/Sec\",\r\n REQUEST_FAILURE_RATE = \"\\\\ApplicationInsights\\\\Requests Failed\\/Sec\",\r\n REQUEST_DURATION = \"\\\\ApplicationInsights\\\\Request Duration\",\r\n\r\n // Dependency\r\n DEPENDENCY_RATE = \"\\\\ApplicationInsights\\\\Dependency Calls\\/Sec\",\r\n DEPENDENCY_FAILURE_RATE = \"\\\\ApplicationInsights\\\\Dependency Calls Failed\\/Sec\",\r\n DEPENDENCY_DURATION = \"\\\\ApplicationInsights\\\\Dependency Call Duration\",\r\n\r\n // Exception\r\n EXCEPTION_RATE = \"\\\\ApplicationInsights\\\\Exceptions\\/Sec\"\r\n}\r\n\r\nexport enum PerformanceCounter {\r\n // Memory\r\n PRIVATE_BYTES = \"\\\\Process(??APP_WIN32_PROC??)\\\\Private Bytes\",\r\n AVAILABLE_BYTES = \"\\\\Memory\\\\Available Bytes\",\r\n\r\n // CPU\r\n PROCESSOR_TIME = \"\\\\Processor(_Total)\\\\% Processor Time\",\r\n PROCESS_TIME = \"\\\\Process(??APP_WIN32_PROC??)\\\\% Processor Time\",\r\n\r\n // Requests\r\n REQUEST_RATE = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Requests/Sec\",\r\n REQUEST_DURATION = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Request Execution Time\"\r\n}\r\n\r\nexport enum MetricId {\r\n REQUESTS_DURATION = \"requests/duration\",\r\n DEPENDENCIES_DURATION = \"dependencies/duration\",\r\n EXCEPTIONS_COUNT = \"exceptions/count\",\r\n TRACES_COUNT = \"traces/count\",\r\n}\r\n\r\n/**\r\n * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined*\r\n */\r\nexport const PerformanceToQuickPulseCounter: { [key: string]: QuickPulseCounter } = {\r\n [PerformanceCounter.PROCESSOR_TIME]: QuickPulseCounter.PROCESSOR_TIME,\r\n [PerformanceCounter.REQUEST_RATE]: QuickPulseCounter.REQUEST_RATE,\r\n [PerformanceCounter.REQUEST_DURATION]: QuickPulseCounter.REQUEST_DURATION,\r\n\r\n // Remap quick pulse only counters\r\n [QuickPulseCounter.COMMITTED_BYTES]: QuickPulseCounter.COMMITTED_BYTES,\r\n [QuickPulseCounter.REQUEST_FAILURE_RATE]: QuickPulseCounter.REQUEST_FAILURE_RATE,\r\n [QuickPulseCounter.DEPENDENCY_RATE]: QuickPulseCounter.DEPENDENCY_RATE,\r\n [QuickPulseCounter.DEPENDENCY_FAILURE_RATE]: QuickPulseCounter.DEPENDENCY_FAILURE_RATE,\r\n [QuickPulseCounter.DEPENDENCY_DURATION]: QuickPulseCounter.DEPENDENCY_DURATION,\r\n [QuickPulseCounter.EXCEPTION_RATE]: QuickPulseCounter.EXCEPTION_RATE\r\n};\r\n\r\n// Note: Explicitly define these types instead of using enum due to\r\n// potential 'export enum' issues with typescript < 2.0.\r\nexport type QuickPulseDocumentType = \"Event\" | \"Exception\" | \"Trace\" | \"Metric\" | \"Request\" | \"RemoteDependency\" | \"Availability\" | \"PageView\";\r\nexport type QuickPulseType =\r\n | \"EventTelemetryDocument\"\r\n | \"ExceptionTelemetryDocument\"\r\n | \"TraceTelemetryDocument\"\r\n | \"MetricTelemetryDocument\"\r\n | \"RequestTelemetryDocument\"\r\n | \"DependencyTelemetryDocument\"\r\n | \"AvailabilityTelemetryDocument\"\r\n | \"PageViewTelemetryDocument\";\r\n\r\nexport const QuickPulseDocumentType: { [key in Contracts.TelemetryTypeKeys]: QuickPulseDocumentType } = {\r\n Event: \"Event\",\r\n Exception: \"Exception\",\r\n Trace: \"Trace\",\r\n Metric: \"Metric\",\r\n Request: \"Request\",\r\n Dependency: \"RemoteDependency\",\r\n Availability: \"Availability\",\r\n PageView: \"PageView\"\r\n};\r\n\r\nexport const QuickPulseType: { [key in Contracts.TelemetryTypeKeys]: QuickPulseType } = {\r\n Event: \"EventTelemetryDocument\",\r\n Exception: \"ExceptionTelemetryDocument\",\r\n Trace: \"TraceTelemetryDocument\",\r\n Metric: \"MetricTelemetryDocument\",\r\n Request: \"RequestTelemetryDocument\",\r\n Dependency: \"DependencyTelemetryDocument\",\r\n Availability: \"AvailabilityTelemetryDocument\",\r\n PageView: \"PageViewTelemetryDocument\"\r\n};\r\n\r\nexport const TelemetryTypeStringToQuickPulseType: { [key in Contracts.TelemetryTypeValues]: QuickPulseType } = {\r\n EventData: QuickPulseType.Event,\r\n ExceptionData: QuickPulseType.Exception,\r\n MessageData: QuickPulseType.Trace,\r\n MetricData: QuickPulseType.Metric,\r\n RequestData: QuickPulseType.Request,\r\n RemoteDependencyData: QuickPulseType.Dependency,\r\n AvailabilityData: QuickPulseType.Availability,\r\n PageViewData: QuickPulseType.PageView\r\n};\r\n\r\nexport const TelemetryTypeStringToQuickPulseDocumentType: { [key in Contracts.TelemetryTypeValues]: QuickPulseDocumentType } = {\r\n EventData: QuickPulseDocumentType.Event,\r\n ExceptionData: QuickPulseDocumentType.Exception,\r\n MessageData: QuickPulseDocumentType.Trace,\r\n MetricData: QuickPulseDocumentType.Metric,\r\n RequestData: QuickPulseDocumentType.Request,\r\n RemoteDependencyData: QuickPulseDocumentType.Dependency,\r\n AvailabilityData: QuickPulseDocumentType.Availability,\r\n PageViewData: QuickPulseDocumentType.PageView\r\n};\r\n\r\nexport const DependencyTypeName = {\r\n Grpc: \"GRPC\",\r\n Http: \"HTTP\",\r\n InProc: \"InProc\",\r\n Sql: \"SQL\",\r\n QueueMessage: \"Queue Message\"\r\n}\r\n\r\nexport const HeartBeatMetricName = \"HeartBeat\";\r\n\r\nexport const StatsbeatTelemetryName = \"Statsbeat\";\r\n\r\nexport const StatsbeatResourceProvider = {\r\n appsvc: \"appsvc\",\r\n functions: \"functions\",\r\n vm: \"vm\",\r\n unknown: \"unknown\"\r\n}\r\n\r\nexport const StatsbeatAttach = {\r\n codeless: \"codeless\",\r\n sdk: \"sdk\"\r\n}\r\n\r\nexport const StatsbeatCounter = {\r\n REQUEST_SUCCESS: \"Request Success Count\",\r\n REQUEST_FAILURE: \"Request Failure Count\",\r\n REQUEST_DURATION: \"Request Duration\",\r\n RETRY_COUNT: \"Retry Count\",\r\n THROTTLE_COUNT: \"Throttle Count\",\r\n EXCEPTION_COUNT: \"Exception Count\",\r\n ATTACH: \"Attach\",\r\n FEATURE: \"Feature\"\r\n}\r\n\r\nexport enum StatsbeatFeature {\r\n NONE = 0,\r\n DISK_RETRY = 1,\r\n AAD_HANDLING = 2,\r\n WEB_SNIPPET = 4,\r\n}\r\n\r\nexport enum StatsbeatInstrumentation {\r\n NONE = 0,\r\n AZURE_CORE_TRACING = 1,\r\n MONGODB = 2,\r\n MYSQL = 4,\r\n REDIS = 8,\r\n POSTGRES = 16,\r\n BUNYAN = 32,\r\n WINSTON = 64,\r\n CONSOLE = 128,\r\n}\r\n\r\nexport enum StatsbeatFeatureType {\r\n Feature,\r\n Instrumentation,\r\n}\r\n\r\nexport enum StatsbeatNetworkCategory {\r\n Breeze,\r\n Quickpulse,\r\n}\r\n\r\n//Azure SDK Span Attributes\r\nexport const AzNamespace = \"az.namespace\";\r\nexport const MicrosoftEventHub = \"Microsoft.EventHub\";\r\nexport const MessageBusDestination = \"message_bus.destination\";\r\n\r\n/**\r\n * AI enqueued time attribute.\r\n * @internal\r\n */\r\n export const ENQUEUED_TIME = \"enqueuedTime\";\r\n /**\r\n * AI time since enqueued attribute.\r\n * @internal\r\n */\r\n export const TIME_SINCE_ENQUEUED = \"timeSinceEnqueued\";\r\n\r\n export const WEB_INSTRUMENTATION_DEFAULT_SOURCE= \"https://js.monitor.azure.com/scripts/b/ai\";\r\n export const WEB_INSTRUMENTATION_DEPRECATED_SOURCE= \"https://az416426.vo.msecnd.net/scripts/b/ai\";"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Constants.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.d.ts new file mode 100644 index 0000000..768c67a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.d.ts @@ -0,0 +1,38 @@ +import { Domain } from "./Generated"; +/** + * Breeze response definition. + */ +export interface BreezeResponse { + itemsReceived: number; + itemsAccepted: number; + errors: BreezeError[]; +} +/** +* Breeze errors. +*/ +export interface BreezeError { + index: number; + statusCode: number; + message: string; +} +export declare class RemoteDependencyDataConstants { + static TYPE_HTTP: string; + static TYPE_AI: string; +} +export interface ISupportProperties extends Domain { + properties: any; +} +export declare function domainSupportsProperties(domain: Domain): domain is ISupportProperties; +/** + * Subset of Connection String fields which this SDK can parse. Lower-typecased to + * allow for case-insensitivity across field names + * @type ConnectionStringKey + */ +export interface ConnectionString { + instrumentationkey?: string; + ingestionendpoint?: string; + liveendpoint?: string; + location?: string; + endpointsuffix?: string; +} +export declare type ConnectionStringKey = "instrumentationkey" | "ingestionendpoint" | "liveendpoint" | "location" | "endpointsuffix"; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js new file mode 100644 index 0000000..5e2d832 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.domainSupportsProperties = exports.RemoteDependencyDataConstants = void 0; +var Generated_1 = require("./Generated"); +var RemoteDependencyDataConstants = /** @class */ (function () { + function RemoteDependencyDataConstants() { + } + RemoteDependencyDataConstants.TYPE_HTTP = "Http"; + RemoteDependencyDataConstants.TYPE_AI = "Http (tracked component)"; + return RemoteDependencyDataConstants; +}()); +exports.RemoteDependencyDataConstants = RemoteDependencyDataConstants; +function domainSupportsProperties(domain) { + return "properties" in domain || // Do extra typechecks in case the type supports it but properties is null/undefined + domain instanceof Generated_1.EventData || + domain instanceof Generated_1.ExceptionData || + domain instanceof Generated_1.MessageData || + domain instanceof Generated_1.MetricData || + domain instanceof Generated_1.PageViewData || + domain instanceof Generated_1.RemoteDependencyData || + domain instanceof Generated_1.RequestData; +} +exports.domainSupportsProperties = domainSupportsProperties; +//# sourceMappingURL=Constants.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js.map new file mode 100644 index 0000000..2f11e49 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../../../Declarations/Contracts/Constants.ts"],"names":[],"mappings":";;;AAAA,yCAAyI;AAoBzI;IAAA;IAGA,CAAC;IAFiB,uCAAS,GAAW,MAAM,CAAC;IAC3B,qCAAO,GAAW,0BAA0B,CAAC;IAC/D,oCAAC;CAAA,AAHD,IAGC;AAHY,sEAA6B;AAS1C,SAAgB,wBAAwB,CAAC,MAAc;IACnD,OAAO,YAAY,IAAI,MAAM,IAAI,oFAAoF;QACjH,MAAM,YAAY,qBAAS;QAC3B,MAAM,YAAY,yBAAa;QAC/B,MAAM,YAAY,uBAAW;QAC7B,MAAM,YAAY,sBAAU;QAC5B,MAAM,YAAY,wBAAY;QAC9B,MAAM,YAAY,gCAAoB;QACtC,MAAM,YAAY,uBAAW,CAAC;AACtC,CAAC;AATD,4DASC","sourcesContent":["import { Domain, EventData, ExceptionData, MessageData, MetricData, PageViewData, RemoteDependencyData, RequestData } from \"./Generated\";\r\n\r\n/**\r\n * Breeze response definition.\r\n */\r\nexport interface BreezeResponse {\r\n itemsReceived: number;\r\n itemsAccepted: number;\r\n errors: BreezeError[];\r\n}\r\n\r\n/**\r\n* Breeze errors.\r\n*/\r\nexport interface BreezeError {\r\n index: number;\r\n statusCode: number;\r\n message: string;\r\n}\r\n\r\nexport class RemoteDependencyDataConstants {\r\n public static TYPE_HTTP: string = \"Http\";\r\n public static TYPE_AI: string = \"Http (tracked component)\";\r\n}\r\n\r\nexport interface ISupportProperties extends Domain {\r\n properties: any;\r\n}\r\n\r\nexport function domainSupportsProperties(domain: Domain): domain is ISupportProperties {\r\n return \"properties\" in domain || // Do extra typechecks in case the type supports it but properties is null/undefined\r\n domain instanceof EventData ||\r\n domain instanceof ExceptionData ||\r\n domain instanceof MessageData ||\r\n domain instanceof MetricData ||\r\n domain instanceof PageViewData ||\r\n domain instanceof RemoteDependencyData ||\r\n domain instanceof RequestData;\r\n}\r\n\r\n/**\r\n * Subset of Connection String fields which this SDK can parse. Lower-typecased to\r\n * allow for case-insensitivity across field names\r\n * @type ConnectionStringKey\r\n */\r\nexport interface ConnectionString {\r\n instrumentationkey?: string;\r\n ingestionendpoint?: string;\r\n liveendpoint?: string;\r\n location?: string;\r\n endpointsuffix?: string;\r\n\r\n // Note: this is a node types backcompat equivalent to\r\n // type ConnectionString = { [key in ConnectionStringKey]?: string }\r\n}\r\n\r\nexport type ConnectionStringKey = \"instrumentationkey\" | \"ingestionendpoint\" | \"liveendpoint\" | \"location\"| \"endpointsuffix\";\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.d.ts new file mode 100644 index 0000000..826e08d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.d.ts @@ -0,0 +1,44 @@ +import Domain = require("./Domain"); +/** + * Instances of AvailabilityData represent the result of executing an availability test. + */ +declare class AvailabilityData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. + */ + id: string; + /** + * Name of the test that these availability results represent. + */ + name: string; + /** + * Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. + */ + duration: string; + /** + * Success flag. + */ + success: boolean; + /** + * Name of the location where the test was run from. + */ + runLocation: string; + /** + * Diagnostic message for the result. + */ + message: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = AvailabilityData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js new file mode 100644 index 0000000..63ffba5 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js @@ -0,0 +1,33 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * Instances of AvailabilityData represent the result of executing an availability test. + */ +var AvailabilityData = /** @class */ (function (_super) { + __extends(AvailabilityData, _super); + function AvailabilityData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return AvailabilityData; +}(Domain)); +module.exports = AvailabilityData; +//# sourceMappingURL=AvailabilityData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js.map new file mode 100644 index 0000000..21f5b7d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/AvailabilityData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AvailabilityData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/AvailabilityData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AACpC,YAAY,CAAC;AAET;;GAEG;AACH;IAA+B,oCAAM;IAgDjC;QAAA,YAEI,iBAAO,SAKV;QAHG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,uBAAC;AAAD,CAAC,AAxDD,CAA+B,MAAM,GAwDpC;AACL,iBAAS,gBAAgB,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\n\"use strict\";\r\n \r\n /**\r\n * Instances of AvailabilityData represent the result of executing an availability test.\r\n */\r\n class AvailabilityData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service.\r\n */\r\n public id: string;\r\n \r\n /**\r\n * Name of the test that these availability results represent.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days.\r\n */\r\n public duration: string;\r\n \r\n /**\r\n * Success flag.\r\n */\r\n public success: boolean;\r\n \r\n /**\r\n * Name of the location where the test was run from.\r\n */\r\n public runLocation: string;\r\n \r\n /**\r\n * Diagnostic message for the result.\r\n */\r\n public message: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = AvailabilityData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.d.ts new file mode 100644 index 0000000..0e41b0d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.d.ts @@ -0,0 +1,11 @@ +/** + * Data struct to contain only C section with custom fields. + */ +declare class Base { + /** + * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. + */ + baseType: string; + constructor(); +} +export = Base; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js new file mode 100644 index 0000000..e285b62 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js @@ -0,0 +1,12 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +/** + * Data struct to contain only C section with custom fields. + */ +var Base = /** @class */ (function () { + function Base() { + } + return Base; +}()); +module.exports = Base; +//# sourceMappingURL=Base.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js.map new file mode 100644 index 0000000..8432cd1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Base.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/Base.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AAET;;GAEG;AACH;IAQI;IAEA,CAAC;IACL,WAAC;AAAD,CAAC,AAXD,IAWC;AACL,iBAAS,IAAI,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\n \r\n /**\r\n * Data struct to contain only C section with custom fields.\r\n */\r\n class Base\r\n {\r\n \r\n /**\r\n * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null.\r\n */\r\n public baseType: string;\r\n \r\n constructor()\r\n {\r\n }\r\n }\r\nexport = Base;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.d.ts new file mode 100644 index 0000000..39ce55c --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.d.ts @@ -0,0 +1,104 @@ +declare class ContextTagKeys { + /** + * Application version. Information in the application context fields is always about the application that is sending the telemetry. + */ + applicationVersion: string; + /** + * Unique client device id. Computer name in most cases. + */ + deviceId: string; + /** + * Device locale using - pattern, following RFC 5646. Example 'en-US'. + */ + deviceLocale: string; + /** + * Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent. + */ + deviceModel: string; + /** + * Client device OEM name taken from the browser. + */ + deviceOEMName: string; + /** + * Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0' + */ + deviceOSVersion: string; + /** + * The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value. + */ + deviceType: string; + /** + * The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service. + */ + locationIp: string; + /** + * A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance. + */ + operationId: string; + /** + * The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index'). + */ + operationName: string; + /** + * The unique identifier of the telemetry item's immediate parent. + */ + operationParentId: string; + /** + * Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself. + */ + operationSyntheticSource: string; + /** + * The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services. + */ + operationCorrelationVector: string; + /** + * Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service. + */ + sessionId: string; + /** + * Boolean value indicating whether the session identified by ai.session.id is first for the user or not. + */ + sessionIsFirst: string; + /** + * In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform. + */ + userAccountId: string; + /** + * Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service. + */ + userId: string; + /** + * Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs. + */ + userAuthUserId: string; + /** + * Name of the role the application is a part of. For Azure environment, this should be initialized with + * [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Role.Name + * See more details here: https://dzone.com/articles/accessing-azure-role-0 + * It is recommended that you initialize environment variable with this value during machine startup, and then set context field from environment variable + * appInsights.client.context.tags[appInsights.client.context.keys.cloudRole] = process.env.RoleName + */ + cloudRole: string; + /** + * Name of the instance where the application is running. For Azure environment, this should be initialized with + * [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Id + * See more details here: https://dzone.com/articles/accessing-azure-role-0 + * It is recommended that you initialize environment variable with this value during machine startup, and then set context field from environment variable + * appInsights.client.context.tags[appInsights.client.context.keys.cloudRoleInstance] = process.env.RoleInstanceId + */ + cloudRoleInstance: string; + /** + * SDK version. See https://github.com/microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information. + */ + internalSdkVersion: string; + /** + * Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection. + */ + internalAgentVersion: string; + /** + * This is the node name used for billing purposes. Use it to override the standard detection of nodes. + */ + internalNodeName: string; + constructor(); +} +export = ContextTagKeys; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js new file mode 100644 index 0000000..ce9dc0a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js @@ -0,0 +1,32 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +var ContextTagKeys = /** @class */ (function () { + function ContextTagKeys() { + this.applicationVersion = "ai.application.ver"; + this.deviceId = "ai.device.id"; + this.deviceLocale = "ai.device.locale"; + this.deviceModel = "ai.device.model"; + this.deviceOEMName = "ai.device.oemName"; + this.deviceOSVersion = "ai.device.osVersion"; + this.deviceType = "ai.device.type"; + this.locationIp = "ai.location.ip"; + this.operationId = "ai.operation.id"; + this.operationName = "ai.operation.name"; + this.operationParentId = "ai.operation.parentId"; + this.operationSyntheticSource = "ai.operation.syntheticSource"; + this.operationCorrelationVector = "ai.operation.correlationVector"; + this.sessionId = "ai.session.id"; + this.sessionIsFirst = "ai.session.isFirst"; + this.userAccountId = "ai.user.accountId"; + this.userId = "ai.user.id"; + this.userAuthUserId = "ai.user.authUserId"; + this.cloudRole = "ai.cloud.role"; + this.cloudRoleInstance = "ai.cloud.roleInstance"; + this.internalSdkVersion = "ai.internal.sdkVersion"; + this.internalAgentVersion = "ai.internal.agentVersion"; + this.internalNodeName = "ai.internal.nodeName"; + } + return ContextTagKeys; +}()); +module.exports = ContextTagKeys; +//# sourceMappingURL=ContextTagKeys.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js.map new file mode 100644 index 0000000..eaa0e9a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ContextTagKeys.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ContextTagKeys.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/ContextTagKeys.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AACb;IA8HI;QACI,IAAI,CAAC,kBAAkB,GAAG,oBAAoB,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,kBAAkB,CAAC;QACvC,IAAI,CAAC,WAAW,GAAG,iBAAiB,CAAC;QACrC,IAAI,CAAC,aAAa,GAAG,mBAAmB,CAAC;QACzC,IAAI,CAAC,eAAe,GAAG,qBAAqB,CAAC;QAC7C,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,gBAAgB,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,iBAAiB,CAAC;QACrC,IAAI,CAAC,aAAa,GAAG,mBAAmB,CAAC;QACzC,IAAI,CAAC,iBAAiB,GAAG,uBAAuB,CAAC;QACjD,IAAI,CAAC,wBAAwB,GAAG,8BAA8B,CAAC;QAC/D,IAAI,CAAC,0BAA0B,GAAG,gCAAgC,CAAC;QACnE,IAAI,CAAC,SAAS,GAAG,eAAe,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,oBAAoB,CAAC;QAC3C,IAAI,CAAC,aAAa,GAAG,mBAAmB,CAAC;QACzC,IAAI,CAAC,MAAM,GAAG,YAAY,CAAC;QAC3B,IAAI,CAAC,cAAc,GAAG,oBAAoB,CAAC;QAC3C,IAAI,CAAC,SAAS,GAAG,eAAe,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,uBAAuB,CAAC;QACjD,IAAI,CAAC,kBAAkB,GAAG,wBAAwB,CAAC;QACnD,IAAI,CAAC,oBAAoB,GAAG,0BAA0B,CAAC;QACvD,IAAI,CAAC,gBAAgB,GAAG,sBAAsB,CAAC;IACnD,CAAC;IACL,qBAAC;AAAD,CAAC,AAvJD,IAuJC;AACD,iBAAS,cAAc,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\nclass ContextTagKeys {\r\n\r\n /**\r\n * Application version. Information in the application context fields is always about the application that is sending the telemetry.\r\n */\r\n public applicationVersion: string;\r\n\r\n /**\r\n * Unique client device id. Computer name in most cases.\r\n */\r\n public deviceId: string;\r\n\r\n /**\r\n * Device locale using - pattern, following RFC 5646. Example 'en-US'.\r\n */\r\n public deviceLocale: string;\r\n\r\n /**\r\n * Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent.\r\n */\r\n public deviceModel: string;\r\n\r\n /**\r\n * Client device OEM name taken from the browser.\r\n */\r\n public deviceOEMName: string;\r\n\r\n /**\r\n * Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0'\r\n */\r\n public deviceOSVersion: string;\r\n\r\n /**\r\n * The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value.\r\n */\r\n public deviceType: string;\r\n\r\n /**\r\n * The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.\r\n */\r\n public locationIp: string;\r\n\r\n /**\r\n * A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance.\r\n */\r\n public operationId: string;\r\n\r\n /**\r\n * The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index').\r\n */\r\n public operationName: string;\r\n\r\n /**\r\n * The unique identifier of the telemetry item's immediate parent.\r\n */\r\n public operationParentId: string;\r\n\r\n /**\r\n * Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself.\r\n */\r\n public operationSyntheticSource: string;\r\n\r\n /**\r\n * The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services.\r\n */\r\n public operationCorrelationVector: string;\r\n\r\n /**\r\n * Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service.\r\n */\r\n public sessionId: string;\r\n\r\n /**\r\n * Boolean value indicating whether the session identified by ai.session.id is first for the user or not.\r\n */\r\n public sessionIsFirst: string;\r\n\r\n /**\r\n * In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform.\r\n */\r\n public userAccountId: string;\r\n\r\n /**\r\n * Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service.\r\n */\r\n public userId: string;\r\n\r\n /**\r\n * Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs.\r\n */\r\n public userAuthUserId: string;\r\n\r\n /**\r\n * Name of the role the application is a part of. For Azure environment, this should be initialized with\r\n * [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Role.Name\r\n * See more details here: https://dzone.com/articles/accessing-azure-role-0\r\n * It is recommended that you initialize environment variable with this value during machine startup, and then set context field from environment variable\r\n * appInsights.client.context.tags[appInsights.client.context.keys.cloudRole] = process.env.RoleName\r\n */\r\n public cloudRole: string;\r\n\r\n /**\r\n * Name of the instance where the application is running. For Azure environment, this should be initialized with\r\n * [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::CurrentRoleInstance.Id\r\n * See more details here: https://dzone.com/articles/accessing-azure-role-0\r\n * It is recommended that you initialize environment variable with this value during machine startup, and then set context field from environment variable\r\n * appInsights.client.context.tags[appInsights.client.context.keys.cloudRoleInstance] = process.env.RoleInstanceId\r\n */\r\n public cloudRoleInstance: string;\r\n\r\n\r\n /**\r\n * SDK version. See https://github.com/microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information.\r\n */\r\n public internalSdkVersion: string;\r\n\r\n /**\r\n * Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection.\r\n */\r\n public internalAgentVersion: string;\r\n\r\n /**\r\n * This is the node name used for billing purposes. Use it to override the standard detection of nodes.\r\n */\r\n public internalNodeName: string;\r\n\r\n constructor() {\r\n this.applicationVersion = \"ai.application.ver\";\r\n this.deviceId = \"ai.device.id\";\r\n this.deviceLocale = \"ai.device.locale\";\r\n this.deviceModel = \"ai.device.model\";\r\n this.deviceOEMName = \"ai.device.oemName\";\r\n this.deviceOSVersion = \"ai.device.osVersion\";\r\n this.deviceType = \"ai.device.type\";\r\n this.locationIp = \"ai.location.ip\";\r\n this.operationId = \"ai.operation.id\";\r\n this.operationName = \"ai.operation.name\";\r\n this.operationParentId = \"ai.operation.parentId\";\r\n this.operationSyntheticSource = \"ai.operation.syntheticSource\";\r\n this.operationCorrelationVector = \"ai.operation.correlationVector\";\r\n this.sessionId = \"ai.session.id\";\r\n this.sessionIsFirst = \"ai.session.isFirst\";\r\n this.userAccountId = \"ai.user.accountId\";\r\n this.userId = \"ai.user.id\";\r\n this.userAuthUserId = \"ai.user.authUserId\";\r\n this.cloudRole = \"ai.cloud.role\";\r\n this.cloudRoleInstance = \"ai.cloud.roleInstance\";\r\n this.internalSdkVersion = \"ai.internal.sdkVersion\";\r\n this.internalAgentVersion = \"ai.internal.agentVersion\";\r\n this.internalNodeName = \"ai.internal.nodeName\";\r\n }\r\n}\r\nexport = ContextTagKeys;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.d.ts new file mode 100644 index 0000000..6cd6e23 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.d.ts @@ -0,0 +1,16 @@ +import Base = require("./Base"); +/** + * Data struct to contain both B and C sections. + */ +declare class Data extends Base { + /** + * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. + */ + baseType: string; + /** + * Container for data item (B section). + */ + baseData: TDomain; + constructor(); +} +export = Data; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js new file mode 100644 index 0000000..30dffea --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js @@ -0,0 +1,29 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Base = require("./Base"); +"use strict"; +/** + * Data struct to contain both B and C sections. + */ +var Data = /** @class */ (function (_super) { + __extends(Data, _super); + function Data() { + return _super.call(this) || this; + } + return Data; +}(Base)); +module.exports = Data; +//# sourceMappingURL=Data.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js.map new file mode 100644 index 0000000..cb1e8cc --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Data.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/Data.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,6BAAgC;AAChC,YAAY,CAAC;AAET;;GAEG;AACH;IAA4B,wBAAI;IAa5B;eAEI,iBAAO;IAEX,CAAC;IACL,WAAC;AAAD,CAAC,AAlBD,CAA4B,IAAI,GAkB/B;AACL,iBAAS,IAAI,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Base = require(\"./Base\");\r\n\"use strict\";\r\n \r\n /**\r\n * Data struct to contain both B and C sections.\r\n */\r\n class Data extends Base\r\n {\r\n \r\n /**\r\n * Name of item (B section) if any. If telemetry data is derived straight from this, this should be null.\r\n */\r\n public baseType: string;\r\n \r\n /**\r\n * Container for data item (B section).\r\n */\r\n public baseData: TDomain;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n }\r\n }\r\nexport = Data;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.d.ts new file mode 100644 index 0000000..7dca541 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.d.ts @@ -0,0 +1,40 @@ +import DataPointType = require("./DataPointType"); +/** + * Metric data single measurement. + */ +declare class DataPoint { + /** + * Name of the metric. + */ + name: string; + /** + * Namespace of the metric. + */ + ns: string; + /** + * Metric type. Single measurement or the aggregated value. + */ + kind: DataPointType; + /** + * Single value for measurement. Sum of individual measurements for the aggregation. + */ + value: number; + /** + * Metric weight of the aggregated metric. Should not be set for a measurement. + */ + count: number; + /** + * Minimum value of the aggregated metric. Should not be set for a measurement. + */ + min: number; + /** + * Maximum value of the aggregated metric. Should not be set for a measurement. + */ + max: number; + /** + * Standard deviation of the aggregated metric. Should not be set for a measurement. + */ + stdDev: number; + constructor(); +} +export = DataPoint; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js new file mode 100644 index 0000000..29fd7f7 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js @@ -0,0 +1,15 @@ +"use strict"; +// THIS FILE WAS AUTOGENERATED +var DataPointType = require("./DataPointType"); +"use strict"; +/** + * Metric data single measurement. + */ +var DataPoint = /** @class */ (function () { + function DataPoint() { + this.kind = DataPointType.Measurement; + } + return DataPoint; +}()); +module.exports = DataPoint; +//# sourceMappingURL=DataPoint.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js.map new file mode 100644 index 0000000..27ea078 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPoint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DataPoint.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/DataPoint.ts"],"names":[],"mappings":";AAAA,8BAA8B;AAC9B,+CAAkD;AAClD,YAAY,CAAC;AAEb;;GAEG;AACH;IA0CI;QACI,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC,WAAW,CAAC;IAC1C,CAAC;IACL,gBAAC;AAAD,CAAC,AA7CD,IA6CC;AACD,iBAAS,SAAS,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport DataPointType = require(\"./DataPointType\");\r\n\"use strict\";\r\n\r\n/**\r\n * Metric data single measurement.\r\n */\r\nclass DataPoint {\r\n\r\n /**\r\n * Name of the metric.\r\n */\r\n public name: string;\r\n\r\n /**\r\n * Namespace of the metric.\r\n */\r\n public ns: string;\r\n\r\n /**\r\n * Metric type. Single measurement or the aggregated value.\r\n */\r\n public kind: DataPointType;\r\n\r\n /**\r\n * Single value for measurement. Sum of individual measurements for the aggregation.\r\n */\r\n public value: number;\r\n\r\n /**\r\n * Metric weight of the aggregated metric. Should not be set for a measurement.\r\n */\r\n public count: number;\r\n\r\n /**\r\n * Minimum value of the aggregated metric. Should not be set for a measurement.\r\n */\r\n public min: number;\r\n\r\n /**\r\n * Maximum value of the aggregated metric. Should not be set for a measurement.\r\n */\r\n public max: number;\r\n\r\n /**\r\n * Standard deviation of the aggregated metric. Should not be set for a measurement.\r\n */\r\n public stdDev: number;\r\n\r\n constructor() {\r\n this.kind = DataPointType.Measurement;\r\n }\r\n}\r\nexport = DataPoint;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.d.ts new file mode 100644 index 0000000..cc0693e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.d.ts @@ -0,0 +1,8 @@ +/** + * Type of the metric data measurement. + */ +declare enum DataPointType { + Measurement = 0, + Aggregation = 1 +} +export = DataPointType; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js new file mode 100644 index 0000000..7973804 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js @@ -0,0 +1,12 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +/** + * Type of the metric data measurement. + */ +var DataPointType; +(function (DataPointType) { + DataPointType[DataPointType["Measurement"] = 0] = "Measurement"; + DataPointType[DataPointType["Aggregation"] = 1] = "Aggregation"; +})(DataPointType || (DataPointType = {})); +module.exports = DataPointType; +//# sourceMappingURL=DataPointType.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js.map new file mode 100644 index 0000000..11710be --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/DataPointType.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DataPointType.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/DataPointType.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AAET;;GAEG;AACH,IAAK,aAIJ;AAJD,WAAK,aAAa;IAEd,+DAAe,CAAA;IACf,+DAAe,CAAA;AACnB,CAAC,EAJI,aAAa,KAAb,aAAa,QAIjB;AACL,iBAAS,aAAa,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\n \r\n /**\r\n * Type of the metric data measurement.\r\n */\r\n enum DataPointType\r\n {\r\n Measurement = 0,\r\n Aggregation = 1,\r\n }\r\nexport = DataPointType;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.d.ts new file mode 100644 index 0000000..a0f7161 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.d.ts @@ -0,0 +1,7 @@ +/** + * The abstract common base of all domains. + */ +declare class Domain { + constructor(); +} +export = Domain; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js new file mode 100644 index 0000000..e8b64bc --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js @@ -0,0 +1,12 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +/** + * The abstract common base of all domains. + */ +var Domain = /** @class */ (function () { + function Domain() { + } + return Domain; +}()); +module.exports = Domain; +//# sourceMappingURL=Domain.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js.map new file mode 100644 index 0000000..4a64308 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Domain.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Domain.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/Domain.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AAET;;GAEG;AACH;IAGI;IAEA,CAAC;IACL,aAAC;AAAD,CAAC,AAND,IAMC;AACL,iBAAS,MAAM,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\n \r\n /**\r\n * The abstract common base of all domains.\r\n */\r\n class Domain\r\n {\r\n \r\n constructor()\r\n {\r\n }\r\n }\r\nexport = Domain;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.d.ts new file mode 100644 index 0000000..30f83d8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.d.ts @@ -0,0 +1,40 @@ +import Base = require("./Base"); +/** + * System variables for a telemetry item. + */ +declare class Envelope { + /** + * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. + */ + ver: number; + /** + * Type name of telemetry data item. + */ + name: string; + /** + * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + */ + time: string; + /** + * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. + */ + sampleRate: number; + /** + * Sequence field used to track absolute order of uploaded events. + */ + seq: string; + /** + * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. + */ + iKey: string; + /** + * Key/value collection of context properties. See ContextTagKeys for information on available properties. + */ + tags: any; + /** + * Telemetry data item. + */ + data: Base; + constructor(); +} +export = Envelope; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js new file mode 100644 index 0000000..7821c32 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js @@ -0,0 +1,14 @@ +"use strict"; +/** + * System variables for a telemetry item. + */ +var Envelope = /** @class */ (function () { + function Envelope() { + this.ver = 1; + this.sampleRate = 100.0; + this.tags = {}; + } + return Envelope; +}()); +module.exports = Envelope; +//# sourceMappingURL=Envelope.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js.map new file mode 100644 index 0000000..065123b --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/Envelope.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Envelope.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/Envelope.ts"],"names":[],"mappings":"AAEA,YAAY,CAAC;AAET;;GAEG;AACH;IA2CI;QAEI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;IACnB,CAAC;IACL,eAAC;AAAD,CAAC,AAjDD,IAiDC;AACL,iBAAS,QAAQ,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Base = require(\"./Base\");\r\n\"use strict\";\r\n \r\n /**\r\n * System variables for a telemetry item.\r\n */\r\n class Envelope\r\n {\r\n \r\n /**\r\n * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1.\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Type name of telemetry data item.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z.\r\n */\r\n public time: string;\r\n \r\n /**\r\n * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items.\r\n */\r\n public sampleRate: number;\r\n \r\n /**\r\n * Sequence field used to track absolute order of uploaded events.\r\n */\r\n public seq: string;\r\n \r\n /**\r\n * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive.\r\n */\r\n public iKey: string;\r\n \r\n /**\r\n * Key/value collection of context properties. See ContextTagKeys for information on available properties.\r\n */\r\n public tags: any;\r\n \r\n /**\r\n * Telemetry data item.\r\n */\r\n public data: Base;\r\n \r\n constructor()\r\n {\r\n this.ver = 1;\r\n this.sampleRate = 100.0;\r\n this.tags = {};\r\n }\r\n }\r\nexport = Envelope;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.d.ts new file mode 100644 index 0000000..b540edc --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.d.ts @@ -0,0 +1,24 @@ +import Domain = require("./Domain"); +/** + * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. + */ +declare class EventData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Event name. Keep it low cardinality to allow proper grouping and useful metrics. + */ + name: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = EventData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js new file mode 100644 index 0000000..a5627df --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js @@ -0,0 +1,33 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. + */ +var EventData = /** @class */ (function (_super) { + __extends(EventData, _super); + function EventData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return EventData; +}(Domain)); +module.exports = EventData; +//# sourceMappingURL=EventData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js.map new file mode 100644 index 0000000..725c053 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/EventData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EventData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/EventData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AACpC,YAAY,CAAC;AAET;;GAEG;AACH;IAAwB,6BAAM;IAuB1B;QAAA,YAEI,iBAAO,SAKV;QAHG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,gBAAC;AAAD,CAAC,AA/BD,CAAwB,MAAM,GA+B7B;AACL,iBAAS,SAAS,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\n\"use strict\";\r\n \r\n /**\r\n * Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name.\r\n */\r\n class EventData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Event name. Keep it low cardinality to allow proper grouping and useful metrics.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = EventData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.d.ts new file mode 100644 index 0000000..5944b90 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.d.ts @@ -0,0 +1,34 @@ +import Domain = require("./Domain"); +import ExceptionDetails = require("./ExceptionDetails"); +import SeverityLevel = require("./SeverityLevel"); +/** + * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. + */ +declare class ExceptionData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Exception chain - list of inner exceptions. + */ + exceptions: ExceptionDetails[]; + /** + * Severity level. Mostly used to indicate exception severity level when it is reported by logging library. + */ + severityLevel: SeverityLevel; + /** + * Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. + */ + problemId: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = ExceptionData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js new file mode 100644 index 0000000..f0c4c8b --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js @@ -0,0 +1,34 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. + */ +var ExceptionData = /** @class */ (function (_super) { + __extends(ExceptionData, _super); + function ExceptionData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.exceptions = []; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return ExceptionData; +}(Domain)); +module.exports = ExceptionData; +//# sourceMappingURL=ExceptionData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js.map new file mode 100644 index 0000000..78c5db9 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExceptionData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/ExceptionData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AAGpC,YAAY,CAAC;AAET;;GAEG;AACH;IAA4B,iCAAM;IAiC9B;QAAA,YAEI,iBAAO,SAMV;QAJG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,oBAAC;AAAD,CAAC,AA1CD,CAA4B,MAAM,GA0CjC;AACL,iBAAS,aAAa,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\nimport ExceptionDetails = require(\"./ExceptionDetails\");\r\nimport SeverityLevel = require(\"./SeverityLevel\");\r\n\"use strict\";\r\n \r\n /**\r\n * An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application.\r\n */\r\n class ExceptionData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Exception chain - list of inner exceptions.\r\n */\r\n public exceptions: ExceptionDetails[];\r\n \r\n /**\r\n * Severity level. Mostly used to indicate exception severity level when it is reported by logging library.\r\n */\r\n public severityLevel: SeverityLevel;\r\n \r\n /**\r\n * Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack.\r\n */\r\n public problemId: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.exceptions = [];\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = ExceptionData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.d.ts new file mode 100644 index 0000000..05275ee --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.d.ts @@ -0,0 +1,36 @@ +import StackFrame = require("./StackFrame"); +/** + * Exception details of the exception in a chain. + */ +declare class ExceptionDetails { + /** + * In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. + */ + id: number; + /** + * The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception + */ + outerId: number; + /** + * Exception type name. + */ + typeName: string; + /** + * Exception message. + */ + message: string; + /** + * Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. + */ + hasFullStack: boolean; + /** + * Text describing the stack. Either stack or parsedStack should have a value. + */ + stack: string; + /** + * List of stack frames. Either stack or parsedStack should have a value. + */ + parsedStack: StackFrame[]; + constructor(); +} +export = ExceptionDetails; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js new file mode 100644 index 0000000..11a6712 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js @@ -0,0 +1,13 @@ +"use strict"; +/** + * Exception details of the exception in a chain. + */ +var ExceptionDetails = /** @class */ (function () { + function ExceptionDetails() { + this.hasFullStack = true; + this.parsedStack = []; + } + return ExceptionDetails; +}()); +module.exports = ExceptionDetails; +//# sourceMappingURL=ExceptionDetails.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js.map new file mode 100644 index 0000000..ef903cf --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/ExceptionDetails.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExceptionDetails.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/ExceptionDetails.ts"],"names":[],"mappings":"AAEA,YAAY,CAAC;AAET;;GAEG;AACH;IAsCI;QAEI,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,EAAE,CAAC;IAC1B,CAAC;IACL,uBAAC;AAAD,CAAC,AA3CD,IA2CC;AACL,iBAAS,gBAAgB,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport StackFrame = require(\"./StackFrame\");\r\n\"use strict\";\r\n \r\n /**\r\n * Exception details of the exception in a chain.\r\n */\r\n class ExceptionDetails\r\n {\r\n \r\n /**\r\n * In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting.\r\n */\r\n public id: number;\r\n \r\n /**\r\n * The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception\r\n */\r\n public outerId: number;\r\n \r\n /**\r\n * Exception type name.\r\n */\r\n public typeName: string;\r\n \r\n /**\r\n * Exception message.\r\n */\r\n public message: string;\r\n \r\n /**\r\n * Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception.\r\n */\r\n public hasFullStack: boolean;\r\n \r\n /**\r\n * Text describing the stack. Either stack or parsedStack should have a value.\r\n */\r\n public stack: string;\r\n \r\n /**\r\n * List of stack frames. Either stack or parsedStack should have a value.\r\n */\r\n public parsedStack: StackFrame[];\r\n \r\n constructor()\r\n {\r\n this.hasFullStack = true;\r\n this.parsedStack = [];\r\n }\r\n }\r\nexport = ExceptionDetails;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.d.ts new file mode 100644 index 0000000..8ae9655 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.d.ts @@ -0,0 +1,25 @@ +import Domain = require("./Domain"); +import SeverityLevel = require("./SeverityLevel"); +/** + * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements. + */ +declare class MessageData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Trace message + */ + message: string; + /** + * Trace severity level. + */ + severityLevel: SeverityLevel; + /** + * Collection of custom properties. + */ + properties: any; + constructor(); +} +export = MessageData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js new file mode 100644 index 0000000..89938ae --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js @@ -0,0 +1,32 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements. + */ +var MessageData = /** @class */ (function (_super) { + __extends(MessageData, _super); + function MessageData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.properties = {}; + return _this; + } + return MessageData; +}(Domain)); +module.exports = MessageData; +//# sourceMappingURL=MessageData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js.map new file mode 100644 index 0000000..fb4d86f --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MessageData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/MessageData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AAEpC,YAAY,CAAC;AAET;;GAEG;AACH;IAA0B,+BAAM;IAuB5B;QAAA,YAEI,iBAAO,SAIV;QAFG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;;IACzB,CAAC;IACL,kBAAC;AAAD,CAAC,AA9BD,CAA0B,MAAM,GA8B/B;AACL,iBAAS,WAAW,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\nimport SeverityLevel = require(\"./SeverityLevel\");\r\n\"use strict\";\r\n \r\n /**\r\n * Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements.\r\n */\r\n class MessageData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Trace message\r\n */\r\n public message: string;\r\n \r\n /**\r\n * Trace severity level.\r\n */\r\n public severityLevel: SeverityLevel;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.properties = {};\r\n }\r\n }\r\nexport = MessageData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.d.ts new file mode 100644 index 0000000..5f92f1c --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.d.ts @@ -0,0 +1,21 @@ +import Domain = require("./Domain"); +import DataPoint = require("./DataPoint"); +/** + * An instance of the Metric item is a list of measurements (single data points) and/or aggregations. + */ +declare class MetricData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. + */ + metrics: DataPoint[]; + /** + * Collection of custom properties. + */ + properties: any; + constructor(); +} +export = MetricData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js new file mode 100644 index 0000000..a68e5ea --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js @@ -0,0 +1,33 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * An instance of the Metric item is a list of measurements (single data points) and/or aggregations. + */ +var MetricData = /** @class */ (function (_super) { + __extends(MetricData, _super); + function MetricData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.metrics = []; + _this.properties = {}; + return _this; + } + return MetricData; +}(Domain)); +module.exports = MetricData; +//# sourceMappingURL=MetricData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js.map new file mode 100644 index 0000000..3447415 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/MetricData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MetricData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/MetricData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AAEpC,YAAY,CAAC;AAET;;GAEG;AACH;IAAyB,8BAAM;IAkB3B;QAAA,YAEI,iBAAO,SAKV;QAHG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;;IACzB,CAAC;IACL,iBAAC;AAAD,CAAC,AA1BD,CAAyB,MAAM,GA0B9B;AACL,iBAAS,UAAU,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\nimport DataPoint = require(\"./DataPoint\");\r\n\"use strict\";\r\n \r\n /**\r\n * An instance of the Metric item is a list of measurements (single data points) and/or aggregations.\r\n */\r\n class MetricData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used.\r\n */\r\n public metrics: DataPoint[];\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.metrics = [];\r\n this.properties = {};\r\n }\r\n }\r\nexport = MetricData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.d.ts new file mode 100644 index 0000000..bd9f98a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.d.ts @@ -0,0 +1,32 @@ +import EventData = require("./EventData"); +/** + * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. + */ +declare class PageViewData extends EventData { + /** + * Schema version + */ + ver: number; + /** + * Request URL with all query string parameters + */ + url: string; + /** + * Event name. Keep it low cardinality to allow proper grouping and useful metrics. + */ + name: string; + /** + * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. + */ + duration: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = PageViewData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js new file mode 100644 index 0000000..b2e2693 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js @@ -0,0 +1,33 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var EventData = require("./EventData"); +"use strict"; +/** + * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. + */ +var PageViewData = /** @class */ (function (_super) { + __extends(PageViewData, _super); + function PageViewData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return PageViewData; +}(EventData)); +module.exports = PageViewData; +//# sourceMappingURL=PageViewData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js.map new file mode 100644 index 0000000..0b4ca30 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/PageViewData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PageViewData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/PageViewData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,uCAA0C;AAC1C,YAAY,CAAC;AAET;;GAEG;AACH;IAA2B,gCAAS;IAiChC;QAAA,YAEI,iBAAO,SAKV;QAHG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,mBAAC;AAAD,CAAC,AAzCD,CAA2B,SAAS,GAyCnC;AACL,iBAAS,YAAY,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport EventData = require(\"./EventData\");\r\n\"use strict\";\r\n \r\n /**\r\n * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView.\r\n */\r\n class PageViewData extends EventData\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Request URL with all query string parameters\r\n */\r\n public url: string;\r\n \r\n /**\r\n * Event name. Keep it low cardinality to allow proper grouping and useful metrics.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days.\r\n */\r\n public duration: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = PageViewData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.d.ts new file mode 100644 index 0000000..e48442d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.d.ts @@ -0,0 +1,52 @@ +import Domain = require("./Domain"); +/** + * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. + */ +declare class RemoteDependencyData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. + */ + name: string; + /** + * Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. + */ + id: string; + /** + * Result code of a dependency call. Examples are SQL error code and HTTP status code. + */ + resultCode: string; + /** + * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. + */ + duration: string; + /** + * Indication of successfull or unsuccessfull call. + */ + success: boolean; + /** + * Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters. + */ + data: string; + /** + * Target site of a dependency call. Examples are server name, host address. + */ + target: string; + /** + * Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. + */ + type: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = RemoteDependencyData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js new file mode 100644 index 0000000..ca0164f --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js @@ -0,0 +1,34 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. + */ +var RemoteDependencyData = /** @class */ (function (_super) { + __extends(RemoteDependencyData, _super); + function RemoteDependencyData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.success = true; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return RemoteDependencyData; +}(Domain)); +module.exports = RemoteDependencyData; +//# sourceMappingURL=RemoteDependencyData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js.map new file mode 100644 index 0000000..89840bc --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RemoteDependencyData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RemoteDependencyData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/RemoteDependencyData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AACpC,YAAY,CAAC;AAET;;GAEG;AACH;IAAmC,wCAAM;IA0DrC;QAAA,YAEI,iBAAO,SAMV;QAJG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,2BAAC;AAAD,CAAC,AAnED,CAAmC,MAAM,GAmExC;AACL,iBAAS,oBAAoB,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\n\"use strict\";\r\n \r\n /**\r\n * An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint.\r\n */\r\n class RemoteDependencyData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call.\r\n */\r\n public id: string;\r\n \r\n /**\r\n * Result code of a dependency call. Examples are SQL error code and HTTP status code.\r\n */\r\n public resultCode: string;\r\n \r\n /**\r\n * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days.\r\n */\r\n public duration: string;\r\n \r\n /**\r\n * Indication of successfull or unsuccessfull call.\r\n */\r\n public success: boolean;\r\n \r\n /**\r\n * Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters.\r\n */\r\n public data: string;\r\n \r\n /**\r\n * Target site of a dependency call. Examples are server name, host address.\r\n */\r\n public target: string;\r\n \r\n /**\r\n * Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP.\r\n */\r\n public type: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.success = true;\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = RemoteDependencyData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.d.ts new file mode 100644 index 0000000..4327ab1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.d.ts @@ -0,0 +1,48 @@ +import Domain = require("./Domain"); +/** + * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. + */ +declare class RequestData extends Domain { + /** + * Schema version + */ + ver: number; + /** + * Identifier of a request call instance. Used for correlation between request and other telemetry items. + */ + id: string; + /** + * Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. + */ + source: string; + /** + * Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. + */ + name: string; + /** + * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. + */ + duration: string; + /** + * Result of a request execution. HTTP status code for HTTP requests. + */ + responseCode: string; + /** + * Indication of successfull or unsuccessfull call. + */ + success: boolean; + /** + * Request URL with all query string parameters. + */ + url: string; + /** + * Collection of custom properties. + */ + properties: any; + /** + * Collection of custom measurements. + */ + measurements: any; + constructor(); +} +export = RequestData; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js new file mode 100644 index 0000000..c109c23 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js @@ -0,0 +1,33 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +// THIS FILE WAS AUTOGENERATED +var Domain = require("./Domain"); +"use strict"; +/** + * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. + */ +var RequestData = /** @class */ (function (_super) { + __extends(RequestData, _super); + function RequestData() { + var _this = _super.call(this) || this; + _this.ver = 2; + _this.properties = {}; + _this.measurements = {}; + return _this; + } + return RequestData; +}(Domain)); +module.exports = RequestData; +//# sourceMappingURL=RequestData.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js.map new file mode 100644 index 0000000..88dbb11 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/RequestData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RequestData.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/RequestData.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8BAA8B;AAC9B,iCAAoC;AACpC,YAAY,CAAC;AAET;;GAEG;AACH;IAA0B,+BAAM;IAqD5B;QAAA,YAEI,iBAAO,SAKV;QAHG,KAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,KAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,KAAI,CAAC,YAAY,GAAG,EAAE,CAAC;;IAC3B,CAAC;IACL,kBAAC;AAAD,CAAC,AA7DD,CAA0B,MAAM,GA6D/B;AACL,iBAAS,WAAW,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\nimport Domain = require(\"./Domain\");\r\n\"use strict\";\r\n \r\n /**\r\n * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results.\r\n */\r\n class RequestData extends Domain\r\n {\r\n \r\n /**\r\n * Schema version\r\n */\r\n public ver: number;\r\n \r\n /**\r\n * Identifier of a request call instance. Used for correlation between request and other telemetry items.\r\n */\r\n public id: string;\r\n \r\n /**\r\n * Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller.\r\n */\r\n public source: string;\r\n \r\n /**\r\n * Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'.\r\n */\r\n public name: string;\r\n \r\n /**\r\n * Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days.\r\n */\r\n public duration: string;\r\n \r\n /**\r\n * Result of a request execution. HTTP status code for HTTP requests.\r\n */\r\n public responseCode: string;\r\n \r\n /**\r\n * Indication of successfull or unsuccessfull call.\r\n */\r\n public success: boolean;\r\n \r\n /**\r\n * Request URL with all query string parameters.\r\n */\r\n public url: string;\r\n \r\n /**\r\n * Collection of custom properties.\r\n */\r\n public properties: any;\r\n \r\n /**\r\n * Collection of custom measurements.\r\n */\r\n public measurements: any;\r\n \r\n constructor()\r\n {\r\n super();\r\n \r\n this.ver = 2;\r\n this.properties = {};\r\n this.measurements = {};\r\n }\r\n }\r\nexport = RequestData;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.d.ts new file mode 100644 index 0000000..a2bba92 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.d.ts @@ -0,0 +1,11 @@ +/** + * Defines the level of severity for the event. + */ +declare enum SeverityLevel { + Verbose = 0, + Information = 1, + Warning = 2, + Error = 3, + Critical = 4 +} +export = SeverityLevel; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js new file mode 100644 index 0000000..f63ce66 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js @@ -0,0 +1,15 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +/** + * Defines the level of severity for the event. + */ +var SeverityLevel; +(function (SeverityLevel) { + SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose"; + SeverityLevel[SeverityLevel["Information"] = 1] = "Information"; + SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning"; + SeverityLevel[SeverityLevel["Error"] = 3] = "Error"; + SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical"; +})(SeverityLevel || (SeverityLevel = {})); +module.exports = SeverityLevel; +//# sourceMappingURL=SeverityLevel.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js.map new file mode 100644 index 0000000..e92e162 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/SeverityLevel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SeverityLevel.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/SeverityLevel.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AAET;;GAEG;AACH,IAAK,aAOJ;AAPD,WAAK,aAAa;IAEd,uDAAW,CAAA;IACX,+DAAe,CAAA;IACf,uDAAW,CAAA;IACX,mDAAS,CAAA;IACT,yDAAY,CAAA;AAChB,CAAC,EAPI,aAAa,KAAb,aAAa,QAOjB;AACL,iBAAS,aAAa,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\n \r\n /**\r\n * Defines the level of severity for the event.\r\n */\r\n enum SeverityLevel\r\n {\r\n Verbose = 0,\r\n Information = 1,\r\n Warning = 2,\r\n Error = 3,\r\n Critical = 4,\r\n }\r\nexport = SeverityLevel;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.d.ts new file mode 100644 index 0000000..ed70746 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.d.ts @@ -0,0 +1,27 @@ +/** + * Stack frame information. + */ +declare class StackFrame { + /** + * Level in the call stack. For the long stacks SDK may not report every function in a call stack. + */ + level: number; + /** + * Method name. + */ + method: string; + /** + * Name of the assembly (dll, jar, etc.) containing this function. + */ + assembly: string; + /** + * File name or URL of the method implementation. + */ + fileName: string; + /** + * Line number of the code implementation. + */ + line: number; + constructor(); +} +export = StackFrame; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js new file mode 100644 index 0000000..f294af3 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js @@ -0,0 +1,12 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +/** + * Stack frame information. + */ +var StackFrame = /** @class */ (function () { + function StackFrame() { + } + return StackFrame; +}()); +module.exports = StackFrame; +//# sourceMappingURL=StackFrame.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js.map new file mode 100644 index 0000000..252d609 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/StackFrame.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StackFrame.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/StackFrame.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;AAET;;GAEG;AACH;IA4BI;IAEA,CAAC;IACL,iBAAC;AAAD,CAAC,AA/BD,IA+BC;AACL,iBAAS,UAAU,CAAC","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\n \r\n /**\r\n * Stack frame information.\r\n */\r\n class StackFrame\r\n {\r\n \r\n /**\r\n * Level in the call stack. For the long stacks SDK may not report every function in a call stack.\r\n */\r\n public level: number;\r\n \r\n /**\r\n * Method name.\r\n */\r\n public method: string;\r\n \r\n /**\r\n * Name of the assembly (dll, jar, etc.) containing this function.\r\n */\r\n public assembly: string;\r\n \r\n /**\r\n * File name or URL of the method implementation.\r\n */\r\n public fileName: string;\r\n \r\n /**\r\n * Line number of the code implementation.\r\n */\r\n public line: number;\r\n \r\n constructor()\r\n {\r\n }\r\n }\r\nexport = StackFrame;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.d.ts new file mode 100644 index 0000000..0818ac5 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.d.ts @@ -0,0 +1,18 @@ +export import AvailabilityData = require("./AvailabilityData"); +export import Base = require("./Base"); +export import ContextTagKeys = require("./ContextTagKeys"); +export import Data = require("./Data"); +export import DataPoint = require("./DataPoint"); +export import DataPointType = require("./DataPointType"); +export import Domain = require("./Domain"); +export import Envelope = require("./Envelope"); +export import EventData = require("./EventData"); +export import ExceptionData = require("./ExceptionData"); +export import ExceptionDetails = require("./ExceptionDetails"); +export import MessageData = require("./MessageData"); +export import MetricData = require("./MetricData"); +export import PageViewData = require("./PageViewData"); +export import RemoteDependencyData = require("./RemoteDependencyData"); +export import RequestData = require("./RequestData"); +export import SeverityLevel = require("./SeverityLevel"); +export import StackFrame = require("./StackFrame"); diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js new file mode 100644 index 0000000..93968d8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js @@ -0,0 +1,22 @@ +// THIS FILE WAS AUTOGENERATED +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AvailabilityData = require("./AvailabilityData"); +exports.Base = require("./Base"); +exports.ContextTagKeys = require("./ContextTagKeys"); +exports.Data = require("./Data"); +exports.DataPoint = require("./DataPoint"); +exports.DataPointType = require("./DataPointType"); +exports.Domain = require("./Domain"); +exports.Envelope = require("./Envelope"); +exports.EventData = require("./EventData"); +exports.ExceptionData = require("./ExceptionData"); +exports.ExceptionDetails = require("./ExceptionDetails"); +exports.MessageData = require("./MessageData"); +exports.MetricData = require("./MetricData"); +exports.PageViewData = require("./PageViewData"); +exports.RemoteDependencyData = require("./RemoteDependencyData"); +exports.RequestData = require("./RequestData"); +exports.SeverityLevel = require("./SeverityLevel"); +exports.StackFrame = require("./StackFrame"); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js.map new file mode 100644 index 0000000..a7fedab --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/Generated/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/Generated/index.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,YAAY,CAAC;;AACb,yDAA+D;AAC/D,iCAAuC;AACvC,qDAA2D;AAC3D,iCAAuC;AACvC,2CAAiD;AACjD,mDAAyD;AACzD,qCAA2C;AAC3C,yCAA+C;AAC/C,2CAAiD;AACjD,mDAAyD;AACzD,yDAA+D;AAC/D,+CAAqD;AACrD,6CAAmD;AACnD,iDAAuD;AACvD,iEAAuE;AACvE,+CAAqD;AACrD,mDAAyD;AACzD,6CAAmD","sourcesContent":["// THIS FILE WAS AUTOGENERATED\r\n\"use strict\";\r\nexport import AvailabilityData = require(\"./AvailabilityData\");\r\nexport import Base = require(\"./Base\");\r\nexport import ContextTagKeys = require(\"./ContextTagKeys\");\r\nexport import Data = require(\"./Data\");\r\nexport import DataPoint = require(\"./DataPoint\");\r\nexport import DataPointType = require(\"./DataPointType\");\r\nexport import Domain = require(\"./Domain\");\r\nexport import Envelope = require(\"./Envelope\");\r\nexport import EventData = require(\"./EventData\");\r\nexport import ExceptionData = require(\"./ExceptionData\");\r\nexport import ExceptionDetails = require(\"./ExceptionDetails\");\r\nexport import MessageData = require(\"./MessageData\");\r\nexport import MetricData = require(\"./MetricData\");\r\nexport import PageViewData = require(\"./PageViewData\");\r\nexport import RemoteDependencyData = require(\"./RemoteDependencyData\");\r\nexport import RequestData = require(\"./RequestData\");\r\nexport import SeverityLevel = require(\"./SeverityLevel\");\r\nexport import StackFrame = require(\"./StackFrame\");\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.d.ts new file mode 100644 index 0000000..e3d9aa8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.d.ts @@ -0,0 +1,11 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +export interface DependencyDocumentQuickPulse extends DocumentQuickPulse { + Name: string; + Target: string; + Success?: boolean; + Duration: string; + ResultCode: string; + CommandName: string; + DependencyTypeName: string; + OperationName: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js new file mode 100644 index 0000000..985d158 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DependencyDocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js.map new file mode 100644 index 0000000..da812aa --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DependencyDocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/DependencyDocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\n\r\nexport interface DependencyDocumentQuickPulse extends DocumentQuickPulse {\r\n Name: string;\r\n Target: string;\r\n Success?: boolean;\r\n Duration: string;\r\n ResultCode: string,\r\n CommandName: string;\r\n DependencyTypeName: string;\r\n OperationName: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.d.ts new file mode 100644 index 0000000..fc86f78 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.d.ts @@ -0,0 +1,11 @@ +export interface DocumentQuickPulse { + __type: string; + DocumentType: string; + Version: string; + OperationId: string; + Properties: IDocumentProperty[]; +} +export interface IDocumentProperty { + key: string; + value: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js new file mode 100644 index 0000000..f49cb71 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js.map new file mode 100644 index 0000000..8a6a52e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/DocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["export interface DocumentQuickPulse {\r\n __type: string;\r\n\r\n DocumentType: string;\r\n\r\n Version: string;\r\n\r\n OperationId: string;\r\n\r\n Properties: IDocumentProperty[];\r\n}\r\n\r\nexport interface IDocumentProperty {\r\n key: string;\r\n value: string;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.d.ts new file mode 100644 index 0000000..13756cd --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.d.ts @@ -0,0 +1,14 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +import { MetricQuickPulse } from "./MetricQuickPulse"; +export interface EnvelopeQuickPulse { + Documents: DocumentQuickPulse[]; + Instance: string; + RoleName: string; + InstrumentationKey: string; + InvariantVersion: number; + MachineName: string; + Metrics: MetricQuickPulse[]; + StreamId: string; + Timestamp: string; + Version: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js new file mode 100644 index 0000000..78259ca --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnvelopeQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js.map new file mode 100644 index 0000000..f3034a9 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnvelopeQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/EnvelopeQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\nimport { MetricQuickPulse } from \"./MetricQuickPulse\";\r\n\r\nexport interface EnvelopeQuickPulse {\r\n Documents: DocumentQuickPulse[];\r\n\r\n Instance: string;\r\n\r\n RoleName: string;\r\n\r\n InstrumentationKey: string;\r\n\r\n InvariantVersion: number;\r\n\r\n MachineName: string;\r\n\r\n Metrics: MetricQuickPulse[];\r\n\r\n StreamId: string;\r\n\r\n Timestamp: string;\r\n\r\n Version: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.d.ts new file mode 100644 index 0000000..48ee6a3 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.d.ts @@ -0,0 +1,4 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +export interface EventDocumentQuickPulse extends DocumentQuickPulse { + Name: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js new file mode 100644 index 0000000..a1a11c7 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EventDocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js.map new file mode 100644 index 0000000..93e5822 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EventDocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/EventDocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\n\r\nexport interface EventDocumentQuickPulse extends DocumentQuickPulse {\r\n Name: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.d.ts new file mode 100644 index 0000000..333b7e0 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.d.ts @@ -0,0 +1,6 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +export interface ExceptionDocumentQuickPulse extends DocumentQuickPulse { + Exception: string; + ExceptionMessage: string; + ExceptionType: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js new file mode 100644 index 0000000..6d06c9b --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ExceptionDocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js.map new file mode 100644 index 0000000..55867a7 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExceptionDocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/ExceptionDocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\n\r\nexport interface ExceptionDocumentQuickPulse extends DocumentQuickPulse {\r\n Exception: string;\r\n ExceptionMessage: string;\r\n ExceptionType: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.d.ts new file mode 100644 index 0000000..22ef6cb --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.d.ts @@ -0,0 +1,5 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +export interface MessageDocumentQuickPulse extends DocumentQuickPulse { + Message: string; + SeverityLevel: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js new file mode 100644 index 0000000..16c780d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MessageDocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js.map new file mode 100644 index 0000000..fcf8852 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MessageDocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/MessageDocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\n\r\nexport interface MessageDocumentQuickPulse extends DocumentQuickPulse {\r\n Message: string;\r\n SeverityLevel: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.d.ts new file mode 100644 index 0000000..2f7362a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.d.ts @@ -0,0 +1,5 @@ +export interface MetricQuickPulse { + Name: string; + Value: number; + Weight: number; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js new file mode 100644 index 0000000..a138ae8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MetricQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js.map new file mode 100644 index 0000000..32f103d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MetricQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/MetricQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["export interface MetricQuickPulse {\r\n Name: string;\r\n\r\n Value: number;\r\n\r\n Weight: number;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.d.ts new file mode 100644 index 0000000..d4eec1d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.d.ts @@ -0,0 +1,8 @@ +import { DocumentQuickPulse } from "./DocumentQuickPulse"; +export interface RequestDocumentQuickPulse extends DocumentQuickPulse { + Name: string; + Success?: boolean; + Duration: string; + ResponseCode: string; + OperationName: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js new file mode 100644 index 0000000..aa45129 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=RequestDocumentQuickPulse.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js.map new file mode 100644 index 0000000..9be6fd7 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RequestDocumentQuickPulse.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/RequestDocumentQuickPulse.ts"],"names":[],"mappings":"","sourcesContent":["import { DocumentQuickPulse } from \"./DocumentQuickPulse\";\r\n\r\nexport interface RequestDocumentQuickPulse extends DocumentQuickPulse {\r\n Name: string;\r\n Success?: boolean;\r\n Duration: string;\r\n ResponseCode: string,\r\n OperationName: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.d.ts new file mode 100644 index 0000000..b0f5c86 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.d.ts @@ -0,0 +1,8 @@ +export * from "./MetricQuickPulse"; +export * from "./EnvelopeQuickPulse"; +export * from "./DocumentQuickPulse"; +export * from "./ExceptionDocumentQuickPulse"; +export * from "./MessageDocumentQuickPulse"; +export * from "./DependencyDocumentQuickPulse"; +export * from "./RequestDocumentQuickPulse"; +export * from "./EventDocumentQuickPulse"; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js new file mode 100644 index 0000000..a0de54e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./MetricQuickPulse"), exports); +__exportStar(require("./EnvelopeQuickPulse"), exports); +__exportStar(require("./DocumentQuickPulse"), exports); +__exportStar(require("./ExceptionDocumentQuickPulse"), exports); +__exportStar(require("./MessageDocumentQuickPulse"), exports); +__exportStar(require("./DependencyDocumentQuickPulse"), exports); +__exportStar(require("./RequestDocumentQuickPulse"), exports); +__exportStar(require("./EventDocumentQuickPulse"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js.map new file mode 100644 index 0000000..43fea06 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/QuickPulseTypes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/QuickPulseTypes/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qDAAmC;AACnC,uDAAqC;AACrC,uDAAqC;AACrC,gEAA8C;AAC9C,8DAA4C;AAC5C,iEAA+C;AAC/C,8DAA4C;AAC5C,4DAA0C","sourcesContent":["export * from \"./MetricQuickPulse\";\r\nexport * from \"./EnvelopeQuickPulse\";\r\nexport * from \"./DocumentQuickPulse\";\r\nexport * from \"./ExceptionDocumentQuickPulse\";\r\nexport * from \"./MessageDocumentQuickPulse\";\r\nexport * from \"./DependencyDocumentQuickPulse\";\r\nexport * from \"./RequestDocumentQuickPulse\";\r\nexport * from \"./EventDocumentQuickPulse\";\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.d.ts new file mode 100644 index 0000000..e17f01b --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.d.ts @@ -0,0 +1,36 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry type used for availability web test results. + */ +export interface AvailabilityTelemetry extends Telemetry { + /** + * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. + */ + id: string; + /** + * Name of the test that these availability results represent. + */ + name: string; + /** + * Request duration in ms + */ + duration: number; + /** + * Success flag. + */ + success: boolean; + /** + * Name of the location where the test was run from. + */ + runLocation: string; + /** + * Diagnostic message for the result. + */ + message: string; + /** + * Metrics associated with this event, displayed in Metrics Explorer on the portal. + */ + measurements?: { + [key: string]: number; + }; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js new file mode 100644 index 0000000..70d2d90 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=AvailabilityTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js.map new file mode 100644 index 0000000..ed61f72 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AvailabilityTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/AvailabilityTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry type used for availability web test results.\r\n */\r\nexport interface AvailabilityTelemetry extends Telemetry {\r\n\r\n /**\r\n * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service.\r\n */\r\n id: string;\r\n\r\n /**\r\n * Name of the test that these availability results represent.\r\n */\r\n name: string;\r\n\r\n /**\r\n * Request duration in ms\r\n */\r\n duration: number;\r\n\r\n /**\r\n * Success flag.\r\n */\r\n success: boolean;\r\n\r\n /**\r\n * Name of the location where the test was run from.\r\n */\r\n runLocation: string;\r\n\r\n /**\r\n * Diagnostic message for the result.\r\n */\r\n message: string;\r\n\r\n /**\r\n * Metrics associated with this event, displayed in Metrics Explorer on the portal.\r\n */\r\n measurements?: { [key: string]: number; };\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.d.ts new file mode 100644 index 0000000..911d233 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.d.ts @@ -0,0 +1,36 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry about the call to remote component + */ +export interface DependencyTelemetry extends Telemetry { + /** + * Type name of the telemetry, such as HTTP of SQL + */ + dependencyTypeName: string; + /** + * Remote component general target information + * If left empty, this will be prepopulated with an extracted hostname from the data field, if it is a url. + * This prepopulation happens when calling `trackDependency`. Use `track` directly to avoid this behavior. + */ + target?: string; + /** + * Remote call name + */ + name: string; + /** + * Remote call data. This is the most detailed information about the call, such as full URL or SQL statement + */ + data: string; + /** + * Remote call duration in ms + */ + duration: number; + /** + * Result code returned form the remote component. This is domain specific and can be HTTP status code or SQL result code + */ + resultCode: string | number; + /** + * True if remote call was successful, false otherwise + */ + success: boolean; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js new file mode 100644 index 0000000..cca78c1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DependencyTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js.map new file mode 100644 index 0000000..4d86505 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/DependencyTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DependencyTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/DependencyTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry about the call to remote component\r\n */\r\nexport interface DependencyTelemetry extends Telemetry {\r\n /**\r\n * Type name of the telemetry, such as HTTP of SQL\r\n */\r\n dependencyTypeName: string;\r\n\r\n /**\r\n * Remote component general target information\r\n * If left empty, this will be prepopulated with an extracted hostname from the data field, if it is a url.\r\n * This prepopulation happens when calling `trackDependency`. Use `track` directly to avoid this behavior.\r\n */\r\n target?: string;\r\n\r\n /**\r\n * Remote call name\r\n */\r\n name: string;\r\n\r\n /**\r\n * Remote call data. This is the most detailed information about the call, such as full URL or SQL statement\r\n */\r\n data: string;\r\n\r\n /**\r\n * Remote call duration in ms\r\n */\r\n duration: number;\r\n\r\n /**\r\n * Result code returned form the remote component. This is domain specific and can be HTTP status code or SQL result code\r\n */\r\n resultCode: string | number;\r\n\r\n /**\r\n * True if remote call was successful, false otherwise\r\n */\r\n success: boolean;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.d.ts new file mode 100644 index 0000000..a68dda3 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.d.ts @@ -0,0 +1,58 @@ +/** + * Telemetry Envelope + */ +export interface EnvelopeTelemetry { + /** + * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. + */ + ver: number; + /** + * Type name of telemetry data item. + */ + name: string; + /** + * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. + */ + time: string; + /** + * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. + */ + sampleRate: number; + /** + * Sequence field used to track absolute order of uploaded events. + */ + seq: string; + /** + * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. + */ + iKey: string; + /** + * Key/value collection of context properties. See ContextTagKeys for information on available properties. + */ + tags: Tags & Tags[]; + /** + * Part B Data + */ + data: DataTelemetry; +} +/** + * Envelope Data + */ +export interface DataTelemetry { + /** + * Telemetry type used for part B + */ + baseType: string; + /** + * Based on schema for part B + */ + baseData?: { + [key: string]: any; + }; +} +/** + * Envelope Tags + */ +export interface Tags { + [key: string]: any; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js new file mode 100644 index 0000000..8f517c4 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EnvelopeTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js.map new file mode 100644 index 0000000..32ab4e2 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnvelopeTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/EnvelopeTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["/**\r\n * Telemetry Envelope\r\n */\r\nexport interface EnvelopeTelemetry {\r\n /**\r\n * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1.\r\n */\r\n ver: number;\r\n /**\r\n * Type name of telemetry data item.\r\n */\r\n name: string;\r\n\r\n /**\r\n * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z.\r\n */\r\n time: string;\r\n\r\n /**\r\n * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items.\r\n */\r\n sampleRate: number;\r\n\r\n /**\r\n * Sequence field used to track absolute order of uploaded events.\r\n */\r\n seq: string;\r\n\r\n /**\r\n * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive.\r\n */\r\n iKey: string;\r\n\r\n /**\r\n * Key/value collection of context properties. See ContextTagKeys for information on available properties.\r\n */\r\n tags: Tags & Tags[];\r\n /**\r\n * Part B Data\r\n */\r\n data: DataTelemetry;\r\n\r\n}\r\n\r\n/**\r\n * Envelope Data\r\n */\r\nexport interface DataTelemetry {\r\n /**\r\n * Telemetry type used for part B\r\n */\r\n baseType: string;\r\n /**\r\n * Based on schema for part B\r\n */\r\n baseData?: {\r\n [key: string]: any;\r\n };\r\n}\r\n\r\n/**\r\n * Envelope Tags\r\n */\r\nexport interface Tags {\r\n [key: string]: any;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.d.ts new file mode 100644 index 0000000..ea03174 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.d.ts @@ -0,0 +1,17 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry about the custom event of interest, such application workflow event, business logic event (purchase) and anything that + * you would like to track and aggregate by count. Event can contain measurements such as purchase amount associated with purchase event + */ +export interface EventTelemetry extends Telemetry { + /** + * Name of the event + */ + name: string; + /** + * Metrics associated with this event, displayed in Metrics Explorer on the portal. + */ + measurements?: { + [key: string]: number; + }; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js new file mode 100644 index 0000000..08f33c1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=EventTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js.map new file mode 100644 index 0000000..f1be305 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/EventTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EventTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/EventTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry about the custom event of interest, such application workflow event, business logic event (purchase) and anything that\r\n * you would like to track and aggregate by count. Event can contain measurements such as purchase amount associated with purchase event\r\n */\r\nexport interface EventTelemetry extends Telemetry\r\n{\r\n /**\r\n * Name of the event\r\n */\r\n name: string;\r\n \r\n /**\r\n * Metrics associated with this event, displayed in Metrics Explorer on the portal.\r\n */\r\n measurements?: { [key: string]: number; };\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.d.ts new file mode 100644 index 0000000..a828b76 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.d.ts @@ -0,0 +1,21 @@ +import { Telemetry } from "./Telemetry"; +import Contracts = require("../"); +/** + * Telemetry about the exception thrown by the application + */ +export interface ExceptionTelemetry extends Telemetry { + /** + * Exception thrown + */ + exception: Error; + /** + * Metrics associated with this exception, displayed in Metrics Explorer on the portal. Defaults to empty + */ + measurements?: { + [key: string]: number; + }; + /** + * Exception severity level + */ + severity?: Contracts.SeverityLevel; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js new file mode 100644 index 0000000..b0b117a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ExceptionTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js.map new file mode 100644 index 0000000..9841486 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ExceptionTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/ExceptionTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\nimport Contracts = require(\"../\");\r\n\r\n/**\r\n * Telemetry about the exception thrown by the application\r\n */\r\nexport interface ExceptionTelemetry extends Telemetry\r\n{\r\n /**\r\n * Exception thrown\r\n */\r\n exception: Error;\r\n\r\n /**\r\n * Metrics associated with this exception, displayed in Metrics Explorer on the portal. Defaults to empty\r\n */\r\n measurements?: { [key: string]: number; };\r\n /**\r\n * Exception severity level\r\n */\r\n severity?: Contracts.SeverityLevel;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.d.ts new file mode 100644 index 0000000..aa8929e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.d.ts @@ -0,0 +1,39 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry encapsulating a custom metric, i.e. aggregated numeric values describing value, count, frequency and distribution of + * of a particular indicator. + */ +export interface MetricTelemetry extends Telemetry { + /** + * A string that identifies the metric. + */ + name: string; + /** + * The value of the metric + */ + value: number; + /** + * A string that identifies the metric namespace. + */ + namespace?: string; + /** + * Type of metric being sent, e.g. Pre-agg metrics have kind=Aggregation + */ + kind?: string; + /** + * The number of samples used to get this value + */ + count?: number; + /** + * The min sample for this set + */ + min?: number; + /** + * The max sample for this set + */ + max?: number; + /** + * The standard deviation of the set + */ + stdDev?: number; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js new file mode 100644 index 0000000..d1083d4 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=MetricTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js.map new file mode 100644 index 0000000..3add033 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/MetricTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MetricTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/MetricTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry encapsulating a custom metric, i.e. aggregated numeric values describing value, count, frequency and distribution of\r\n * of a particular indicator.\r\n */\r\nexport interface MetricTelemetry extends Telemetry {\r\n /**\r\n * A string that identifies the metric.\r\n */\r\n name: string;\r\n\r\n /**\r\n * The value of the metric\r\n */\r\n value: number;\r\n\r\n /**\r\n * A string that identifies the metric namespace.\r\n */\r\n namespace?: string;\r\n\r\n /**\r\n * Type of metric being sent, e.g. Pre-agg metrics have kind=Aggregation\r\n */\r\n kind?: string;\r\n\r\n /**\r\n * The number of samples used to get this value\r\n */\r\n count?: number;\r\n\r\n /**\r\n * The min sample for this set\r\n */\r\n min?: number;\r\n\r\n /**\r\n * The max sample for this set\r\n */\r\n max?: number;\r\n\r\n /**\r\n * The standard deviation of the set\r\n */\r\n stdDev?: number;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.d.ts new file mode 100644 index 0000000..8b349b5 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.d.ts @@ -0,0 +1,21 @@ +/// +import { Telemetry } from "./Telemetry"; +import http = require("http"); +import https = require("https"); +/** + * Object encapsulating information about the outgoing request + */ +export interface NodeHttpDependencyTelemetry extends Telemetry { + /** + * Request options that will be used to instrument outgoing request + */ + options: string | URL | http.RequestOptions | https.RequestOptions; + /** + * Outgoing HTTP request object + */ + request: http.ClientRequest; + /** + * Flag to determine if telemetry had been processed. + */ + isProcessed?: boolean; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js new file mode 100644 index 0000000..91fbe39 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=NodeHttpDependencyTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js.map new file mode 100644 index 0000000..a3480ac --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NodeHttpDependencyTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/NodeHttpDependencyTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\nimport http = require(\"http\");\r\nimport https = require(\"https\");\r\n\r\n/**\r\n * Object encapsulating information about the outgoing request\r\n */\r\nexport interface NodeHttpDependencyTelemetry extends Telemetry\r\n{\r\n /**\r\n * Request options that will be used to instrument outgoing request\r\n */\r\n options: string | URL | http.RequestOptions | https.RequestOptions;\r\n\r\n /**\r\n * Outgoing HTTP request object\r\n */\r\n request: http.ClientRequest;\r\n\r\n /**\r\n * Flag to determine if telemetry had been processed.\r\n */\r\n isProcessed?: boolean;\r\n\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.d.ts new file mode 100644 index 0000000..0d6623f --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.d.ts @@ -0,0 +1,28 @@ +/// +import { Telemetry } from "./Telemetry"; +import http = require("http"); +/** + * Object encapsulating information about the incoming HTTP request + */ +export interface NodeHttpRequestTelemetry extends Telemetry { + /** + * HTTP request object + */ + request: http.IncomingMessage; + /** + * HTTP response object + */ + response: http.ServerResponse; + /** + * HTTP request duration. Used only for synchronous tracks. + */ + duration?: number; + /** + * Flag to determine if telemetry had been processed. + */ + isProcessed?: boolean; + /** + * Error that occurred while processing the request. Used only for synchronous tracks. + */ + error?: any; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js new file mode 100644 index 0000000..56d59e9 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=NodeHttpRequestTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js.map new file mode 100644 index 0000000..7b4e201 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NodeHttpRequestTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/NodeHttpRequestTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\nimport http = require(\"http\");\r\n\r\n/**\r\n * Object encapsulating information about the incoming HTTP request\r\n */\r\nexport interface NodeHttpRequestTelemetry extends Telemetry {\r\n /**\r\n * HTTP request object\r\n */\r\n request: http.IncomingMessage;\r\n\r\n /**\r\n * HTTP response object\r\n */\r\n response: http.ServerResponse;\r\n\r\n /**\r\n * HTTP request duration. Used only for synchronous tracks.\r\n */\r\n duration?: number;\r\n\r\n /**\r\n * Flag to determine if telemetry had been processed.\r\n */\r\n isProcessed?: boolean;\r\n\r\n /**\r\n * Error that occurred while processing the request. Used only for synchronous tracks.\r\n */\r\n error?: any\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.d.ts new file mode 100644 index 0000000..ddb2900 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.d.ts @@ -0,0 +1,24 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry type used for availability web test results. + */ +export interface PageViewTelemetry extends Telemetry { + /** + * Name of the test that these availability results represent. + */ + name?: string; + /** + * URL of the page to track. + */ + url?: string; + /** + * Request duration in ms + */ + duration?: number; + /** + * Metrics associated with this event, displayed in Metrics Explorer on the portal. + */ + measurements?: { + [key: string]: number; + }; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js new file mode 100644 index 0000000..4c974e0 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=PageViewTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js.map new file mode 100644 index 0000000..3db0be4 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/PageViewTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PageViewTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/PageViewTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry type used for availability web test results.\r\n */\r\nexport interface PageViewTelemetry extends Telemetry {\r\n\r\n /**\r\n * Name of the test that these availability results represent.\r\n */\r\n name?: string;\r\n\r\n /**\r\n * URL of the page to track.\r\n */\r\n url?: string;\r\n\r\n /**\r\n * Request duration in ms\r\n */\r\n duration?: number;\r\n\r\n /**\r\n * Metrics associated with this event, displayed in Metrics Explorer on the portal.\r\n */\r\n measurements?: { [key: string]: number; };\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.d.ts new file mode 100644 index 0000000..6d80859 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.d.ts @@ -0,0 +1,36 @@ +import { Telemetry } from "./Telemetry"; +/** + * Telemetry about the incoming request processed by the application + */ +export interface RequestTelemetry extends Telemetry { + /** + * Request name + */ + name: string; + /** + * Request url + */ + url: string; + /** + * Request source. This encapsulates the information about the component that initiated the request + */ + source?: string; + /** + * Request duration in ms + */ + duration: number; + /** + * Result code reported by the application + */ + resultCode: string | number; + /** + * Whether the request was successful + */ + success: boolean; + /** + * Collection of custom measurements + */ + measurements?: { + [key: string]: number; + }; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js new file mode 100644 index 0000000..24be259 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=RequestTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js.map new file mode 100644 index 0000000..f8b959a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/RequestTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RequestTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/RequestTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\n\r\n/**\r\n * Telemetry about the incoming request processed by the application\r\n */\r\nexport interface RequestTelemetry extends Telemetry {\r\n /**\r\n * Request name\r\n */\r\n name: string;\r\n\r\n /**\r\n * Request url\r\n */\r\n url: string;\r\n\r\n /**\r\n * Request source. This encapsulates the information about the component that initiated the request\r\n */\r\n source?: string;\r\n\r\n /**\r\n * Request duration in ms\r\n */\r\n duration: number;\r\n\r\n /**\r\n * Result code reported by the application\r\n */\r\n resultCode: string | number;\r\n\r\n /**\r\n * Whether the request was successful\r\n */\r\n success: boolean;\r\n\r\n /**\r\n * Collection of custom measurements\r\n */\r\n measurements?: { [key: string]: number; };\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.d.ts new file mode 100644 index 0000000..076ca02 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.d.ts @@ -0,0 +1,27 @@ +/** + * Base telemetry interface encapsulating coming properties + */ +export interface Telemetry { + /** + * Telemetry time stamp. When it is not specified, current timestamp will be used. + */ + time?: Date; + /** + * Additional data used to filter events and metrics in the portal. Defaults to empty. + */ + properties?: { + [key: string]: any; + }; + /** + * An event-specific context that will be passed to telemetry processors handling this event before it is sent. For a context spanning your entire operation, consider appInsights.getCorrelationContext + */ + contextObjects?: { + [name: string]: any; + }; + /** + * The context tags to use for this telemetry which overwrite default context values + */ + tagOverrides?: { + [key: string]: string; + }; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js new file mode 100644 index 0000000..eace59e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Telemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js.map new file mode 100644 index 0000000..a749fd1 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/Telemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Telemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/Telemetry.ts"],"names":[],"mappings":"","sourcesContent":["/**\r\n * Base telemetry interface encapsulating coming properties\r\n */\r\nexport interface Telemetry {\r\n /**\r\n * Telemetry time stamp. When it is not specified, current timestamp will be used.\r\n */\r\n time?: Date;\r\n /**\r\n * Additional data used to filter events and metrics in the portal. Defaults to empty.\r\n */\r\n properties?: { [key: string]: any; };\r\n /**\r\n * An event-specific context that will be passed to telemetry processors handling this event before it is sent. For a context spanning your entire operation, consider appInsights.getCorrelationContext\r\n */\r\n contextObjects?: { [name: string]: any; };\r\n /**\r\n * The context tags to use for this telemetry which overwrite default context values\r\n */\r\n tagOverrides?: { [key: string]: string; };\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.d.ts new file mode 100644 index 0000000..0d1c3bb --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.d.ts @@ -0,0 +1,31 @@ +export declare type TelemetryTypeKeys = "Event" | "Exception" | "Trace" | "Metric" | "Request" | "Dependency" | "Availability" | "PageView"; +export declare type TelemetryTypeValues = "EventData" | "ExceptionData" | "MessageData" | "MetricData" | "RequestData" | "RemoteDependencyData" | "AvailabilityData" | "PageViewData"; +/** + * Converts the user-friendly enumeration TelemetryType to the underlying schema baseType value + * @param type Type to convert to BaseData string + */ +export declare function telemetryTypeToBaseType(type: TelemetryType): TelemetryTypeValues; +/** + * Converts the schema baseType value to the user-friendly enumeration TelemetryType + * @param baseType BaseData string to convert to TelemetryType + */ +export declare function baseTypeToTelemetryType(baseType: TelemetryTypeValues): TelemetryType; +export declare const TelemetryTypeString: { + [key: string]: TelemetryTypeValues; +}; +/** + * Telemetry types supported by this SDK + */ +export declare enum TelemetryType { + Event = 0, + Exception = 1, + Trace = 2, + Metric = 3, + Request = 4, + Dependency = 5, + Availability = 6, + PageView = 7 +} +export interface Identified { + id?: string; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js new file mode 100644 index 0000000..fade29a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js @@ -0,0 +1,80 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TelemetryType = exports.TelemetryTypeString = exports.baseTypeToTelemetryType = exports.telemetryTypeToBaseType = void 0; +/** + * Converts the user-friendly enumeration TelemetryType to the underlying schema baseType value + * @param type Type to convert to BaseData string + */ +function telemetryTypeToBaseType(type) { + switch (type) { + case TelemetryType.Event: + return "EventData"; + case TelemetryType.Exception: + return "ExceptionData"; + case TelemetryType.Trace: + return "MessageData"; + case TelemetryType.Metric: + return "MetricData"; + case TelemetryType.Request: + return "RequestData"; + case TelemetryType.Dependency: + return "RemoteDependencyData"; + case TelemetryType.Availability: + return "AvailabilityData"; + case TelemetryType.PageView: + return "PageViewData"; + } + return undefined; +} +exports.telemetryTypeToBaseType = telemetryTypeToBaseType; +/** + * Converts the schema baseType value to the user-friendly enumeration TelemetryType + * @param baseType BaseData string to convert to TelemetryType + */ +function baseTypeToTelemetryType(baseType) { + switch (baseType) { + case "EventData": + return TelemetryType.Event; + case "ExceptionData": + return TelemetryType.Exception; + case "MessageData": + return TelemetryType.Trace; + case "MetricData": + return TelemetryType.Metric; + case "RequestData": + return TelemetryType.Request; + case "RemoteDependencyData": + return TelemetryType.Dependency; + case "AvailabilityData": + return TelemetryType.Availability; + case "PageViewData": + return TelemetryType.PageView; + } + return undefined; +} +exports.baseTypeToTelemetryType = baseTypeToTelemetryType; +exports.TelemetryTypeString = { + Event: "EventData", + Exception: "ExceptionData", + Trace: "MessageData", + Metric: "MetricData", + Request: "RequestData", + Dependency: "RemoteDependencyData", + Availability: "AvailabilityData", + PageView: "PageViewData" +}; +/** + * Telemetry types supported by this SDK + */ +var TelemetryType; +(function (TelemetryType) { + TelemetryType[TelemetryType["Event"] = 0] = "Event"; + TelemetryType[TelemetryType["Exception"] = 1] = "Exception"; + TelemetryType[TelemetryType["Trace"] = 2] = "Trace"; + TelemetryType[TelemetryType["Metric"] = 3] = "Metric"; + TelemetryType[TelemetryType["Request"] = 4] = "Request"; + TelemetryType[TelemetryType["Dependency"] = 5] = "Dependency"; + TelemetryType[TelemetryType["Availability"] = 6] = "Availability"; + TelemetryType[TelemetryType["PageView"] = 7] = "PageView"; +})(TelemetryType = exports.TelemetryType || (exports.TelemetryType = {})); +//# sourceMappingURL=TelemetryType.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js.map new file mode 100644 index 0000000..bbc1d0d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TelemetryType.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TelemetryType.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/TelemetryType.ts"],"names":[],"mappings":";;;AAWA;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,IAAmB;IACvD,QAAO,IAAI,EAAE;QACT,KAAK,aAAa,CAAC,KAAK;YACpB,OAAO,WAAW,CAAC;QACvB,KAAK,aAAa,CAAC,SAAS;YACxB,OAAO,eAAe,CAAC;QAC3B,KAAK,aAAa,CAAC,KAAK;YACpB,OAAO,aAAa,CAAC;QACzB,KAAK,aAAa,CAAC,MAAM;YACrB,OAAO,YAAY,CAAC;QACxB,KAAK,aAAa,CAAC,OAAO;YACtB,OAAO,aAAa,CAAC;QACzB,KAAK,aAAa,CAAC,UAAU;YACzB,OAAO,sBAAsB,CAAC;QAClC,KAAK,aAAa,CAAC,YAAY;YAC3B,OAAO,kBAAkB,CAAC;QAC9B,KAAK,aAAa,CAAC,QAAQ;YACvB,OAAO,cAAc,CAAC;KAC7B;IACD,OAAO,SAAS,CAAC;AACrB,CAAC;AApBD,0DAoBC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,QAA6B;IACjE,QAAO,QAAQ,EAAE;QACb,KAAK,WAAW;YACZ,OAAO,aAAa,CAAC,KAAK,CAAC;QAC/B,KAAK,eAAe;YAChB,OAAO,aAAa,CAAC,SAAS,CAAC;QACnC,KAAK,aAAa;YACd,OAAO,aAAa,CAAC,KAAK,CAAC;QAC/B,KAAK,YAAY;YACb,OAAO,aAAa,CAAC,MAAM,CAAC;QAChC,KAAK,aAAa;YACd,OAAO,aAAa,CAAC,OAAO,CAAC;QACjC,KAAK,sBAAsB;YACvB,OAAO,aAAa,CAAC,UAAU,CAAC;QACpC,KAAK,kBAAkB;YACnB,OAAO,aAAa,CAAC,YAAY,CAAC;QACtC,KAAK,cAAc;YACf,OAAO,aAAa,CAAC,QAAQ,CAAC;KACrC;IACD,OAAO,SAAS,CAAC;AACrB,CAAC;AApBD,0DAoBC;AAEY,QAAA,mBAAmB,GAAyC;IACrE,KAAK,EAAE,WAAW;IAClB,SAAS,EAAE,eAAe;IAC1B,KAAK,EAAE,aAAa;IACpB,MAAM,EAAE,YAAY;IACpB,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,sBAAsB;IAClC,YAAY,EAAE,kBAAkB;IAChC,QAAQ,EAAE,cAAc;CAC3B,CAAA;AAED;;GAEG;AACH,IAAY,aASX;AATD,WAAY,aAAa;IACrB,mDAAK,CAAA;IACL,2DAAS,CAAA;IACT,mDAAK,CAAA;IACL,qDAAM,CAAA;IACN,uDAAO,CAAA;IACP,6DAAU,CAAA;IACV,iEAAY,CAAA;IACZ,yDAAQ,CAAA;AACZ,CAAC,EATW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QASxB","sourcesContent":["export type TelemetryTypeKeys = \"Event\" | \"Exception\" | \"Trace\" | \"Metric\" | \"Request\" | \"Dependency\" | \"Availability\" | \"PageView\";\r\nexport type TelemetryTypeValues =\r\n | \"EventData\"\r\n | \"ExceptionData\"\r\n | \"MessageData\"\r\n | \"MetricData\"\r\n | \"RequestData\"\r\n | \"RemoteDependencyData\"\r\n | \"AvailabilityData\"\r\n | \"PageViewData\";\r\n\r\n/**\r\n * Converts the user-friendly enumeration TelemetryType to the underlying schema baseType value\r\n * @param type Type to convert to BaseData string\r\n */\r\nexport function telemetryTypeToBaseType(type: TelemetryType): TelemetryTypeValues {\r\n switch(type) {\r\n case TelemetryType.Event:\r\n return \"EventData\";\r\n case TelemetryType.Exception:\r\n return \"ExceptionData\";\r\n case TelemetryType.Trace:\r\n return \"MessageData\";\r\n case TelemetryType.Metric:\r\n return \"MetricData\";\r\n case TelemetryType.Request:\r\n return \"RequestData\";\r\n case TelemetryType.Dependency:\r\n return \"RemoteDependencyData\";\r\n case TelemetryType.Availability:\r\n return \"AvailabilityData\";\r\n case TelemetryType.PageView:\r\n return \"PageViewData\";\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Converts the schema baseType value to the user-friendly enumeration TelemetryType\r\n * @param baseType BaseData string to convert to TelemetryType\r\n */\r\nexport function baseTypeToTelemetryType(baseType: TelemetryTypeValues): TelemetryType {\r\n switch(baseType) {\r\n case \"EventData\":\r\n return TelemetryType.Event;\r\n case \"ExceptionData\":\r\n return TelemetryType.Exception;\r\n case \"MessageData\":\r\n return TelemetryType.Trace;\r\n case \"MetricData\":\r\n return TelemetryType.Metric;\r\n case \"RequestData\":\r\n return TelemetryType.Request;\r\n case \"RemoteDependencyData\":\r\n return TelemetryType.Dependency;\r\n case \"AvailabilityData\":\r\n return TelemetryType.Availability;\r\n case \"PageViewData\":\r\n return TelemetryType.PageView;\r\n }\r\n return undefined;\r\n}\r\n\r\nexport const TelemetryTypeString: {[key: string]: TelemetryTypeValues} = {\r\n Event: \"EventData\",\r\n Exception: \"ExceptionData\",\r\n Trace: \"MessageData\",\r\n Metric: \"MetricData\",\r\n Request: \"RequestData\",\r\n Dependency: \"RemoteDependencyData\",\r\n Availability: \"AvailabilityData\",\r\n PageView: \"PageViewData\"\r\n}\r\n\r\n/**\r\n * Telemetry types supported by this SDK\r\n */\r\nexport enum TelemetryType {\r\n Event,\r\n Exception,\r\n Trace,\r\n Metric,\r\n Request,\r\n Dependency,\r\n Availability,\r\n PageView\r\n}\r\n\r\nexport interface Identified {\r\n id?: string;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.d.ts new file mode 100644 index 0000000..691d3a8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.d.ts @@ -0,0 +1,16 @@ +import { Telemetry } from "./Telemetry"; +import Contracts = require("../"); +/** + * Trace telemetry reports technical, usually detailed information about the environment, + * usage of resources, performance, capacity etc + */ +export interface TraceTelemetry extends Telemetry { + /** + * Trace message + */ + message: string; + /** + * Trace severity level + */ + severity?: Contracts.SeverityLevel; +} diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js new file mode 100644 index 0000000..d5f4478 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=TraceTelemetry.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js.map new file mode 100644 index 0000000..7634f5c --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/TraceTelemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TraceTelemetry.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/TraceTelemetry.ts"],"names":[],"mappings":"","sourcesContent":["import { Telemetry } from \"./Telemetry\";\r\nimport Contracts = require(\"../\");\r\n\r\n/**\r\n * Trace telemetry reports technical, usually detailed information about the environment,\r\n * usage of resources, performance, capacity etc\r\n */\r\nexport interface TraceTelemetry extends Telemetry {\r\n /**\r\n * Trace message\r\n */\r\n message: string;\r\n /**\r\n * Trace severity level\r\n */\r\n severity?: Contracts.SeverityLevel;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.d.ts new file mode 100644 index 0000000..403432d --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.d.ts @@ -0,0 +1,13 @@ +export * from "./DependencyTelemetry"; +export * from "./EventTelemetry"; +export * from "./ExceptionTelemetry"; +export * from "./MetricTelemetry"; +export * from "./RequestTelemetry"; +export * from "./TraceTelemetry"; +export * from "./Telemetry"; +export * from "./NodeHttpDependencyTelemetry"; +export * from "./NodeHttpRequestTelemetry"; +export * from "./AvailabilityTelemetry"; +export * from "./PageViewTelemetry"; +export * from "./EnvelopeTelemetry"; +export * from "./TelemetryType"; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js new file mode 100644 index 0000000..754cc45 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js @@ -0,0 +1,26 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./DependencyTelemetry"), exports); +__exportStar(require("./EventTelemetry"), exports); +__exportStar(require("./ExceptionTelemetry"), exports); +__exportStar(require("./MetricTelemetry"), exports); +__exportStar(require("./RequestTelemetry"), exports); +__exportStar(require("./TraceTelemetry"), exports); +__exportStar(require("./Telemetry"), exports); +__exportStar(require("./NodeHttpDependencyTelemetry"), exports); +__exportStar(require("./NodeHttpRequestTelemetry"), exports); +__exportStar(require("./AvailabilityTelemetry"), exports); +__exportStar(require("./PageViewTelemetry"), exports); +__exportStar(require("./EnvelopeTelemetry"), exports); +__exportStar(require("./TelemetryType"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js.map new file mode 100644 index 0000000..f3cb75a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/TelemetryTypes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../Declarations/Contracts/TelemetryTypes/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wDAAsC;AACtC,mDAAiC;AACjC,uDAAqC;AACrC,oDAAkC;AAClC,qDAAmC;AACnC,mDAAiC;AACjC,8CAA4B;AAE5B,gEAA8C;AAC9C,6DAA2C;AAC3C,0DAAwC;AACxC,sDAAoC;AAEpC,sDAAoC;AACpC,kDAAgC","sourcesContent":["export * from \"./DependencyTelemetry\";\r\nexport * from \"./EventTelemetry\";\r\nexport * from \"./ExceptionTelemetry\";\r\nexport * from \"./MetricTelemetry\";\r\nexport * from \"./RequestTelemetry\";\r\nexport * from \"./TraceTelemetry\";\r\nexport * from \"./Telemetry\";\r\n\r\nexport * from \"./NodeHttpDependencyTelemetry\";\r\nexport * from \"./NodeHttpRequestTelemetry\";\r\nexport * from \"./AvailabilityTelemetry\";\r\nexport * from \"./PageViewTelemetry\";\r\n\r\nexport * from \"./EnvelopeTelemetry\";\r\nexport * from \"./TelemetryType\";"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/index.d.ts b/node_modules/applicationinsights/out/Declarations/Contracts/index.d.ts new file mode 100644 index 0000000..8e5e7d8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/index.d.ts @@ -0,0 +1,4 @@ +export * from "./Constants"; +export * from "./Generated"; +export * from "./TelemetryTypes"; +export * from "./QuickPulseTypes"; diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/index.js b/node_modules/applicationinsights/out/Declarations/Contracts/index.js new file mode 100644 index 0000000..2aeafbd --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/index.js @@ -0,0 +1,17 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./Constants"), exports); +__exportStar(require("./Generated"), exports); +__exportStar(require("./TelemetryTypes"), exports); +__exportStar(require("./QuickPulseTypes"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Contracts/index.js.map b/node_modules/applicationinsights/out/Declarations/Contracts/index.js.map new file mode 100644 index 0000000..c95c3d8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Contracts/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../Declarations/Contracts/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,8CAA4B;AAC5B,8CAA4B;AAC5B,mDAAiC;AACjC,oDAAkC","sourcesContent":["export * from \"./Constants\";\r\nexport * from \"./Generated\";\r\nexport * from \"./TelemetryTypes\";\r\nexport * from \"./QuickPulseTypes\";\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Interfaces.d.ts b/node_modules/applicationinsights/out/Declarations/Interfaces.d.ts new file mode 100644 index 0000000..42a437e --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Interfaces.d.ts @@ -0,0 +1,220 @@ +/// +import http = require("http"); +import https = require("https"); +import * as azureCoreAuth from "@azure/core-auth"; +import { DistributedTracingModes } from "../applicationinsights"; +import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance"; +export interface IBaseConfig { + /** Application Insights resource instrumentation key */ + instrumentationKey: string; + /** The ingestion endpoint to send telemetry payloads to */ + endpointUrl: string; + /** The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default 250) */ + maxBatchSize: number; + /** The maximum amount of time to wait for a payload to reach maxBatchSize (Default 15000) */ + maxBatchIntervalMs: number; + /** A flag indicating if telemetry transmission is disabled (Default false) */ + disableAppInsights: boolean; + /** The percentage of telemetry items tracked that should be transmitted (Default 100) */ + samplingPercentage: number; + /** The time to wait before retrying to retrieve the id for cross-component correlation (Default 30000) */ + correlationIdRetryIntervalMs: number; + /** A list of domains to exclude from cross-component header injection */ + correlationHeaderExcludedDomains: string[]; + /** A proxy server for SDK HTTP traffic (Optional, Default pulled from `http_proxy` environment variable) */ + proxyHttpUrl: string; + /** A proxy server for SDK HTTPS traffic (Optional, Default pulled from `https_proxy` environment variable) */ + proxyHttpsUrl: string; + /** Disable including legacy headers in outgoing requests, x-ms-request-id */ + ignoreLegacyHeaders: boolean; + /** + * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context + * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing + * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included. + * Enabling W3C mode will not break existing correlation with other Application Insights instrumented + * services. Default=AI + */ + distributedTracingMode: DistributedTracingModes; + /** + * Sets the state of console + * if true logger activity will be sent to Application Insights + */ + enableAutoCollectExternalLoggers: boolean; + /** + * Sets the state of logger tracking (enabled by default for third-party loggers only) + * if true, logger autocollection will include console.log calls (default false) + */ + enableAutoCollectConsole: boolean; + /** + * Sets the state of exception tracking (enabled by default) + * if true uncaught exceptions will be sent to Application Insights + */ + enableAutoCollectExceptions: boolean; + /** + * Sets the state of performance tracking (enabled by default) + * if true performance counters will be collected every second and sent to Application Insights + */ + enableAutoCollectPerformance: boolean; + /** + * Sets the state of performance tracking (enabled by default) + * if true, extended metrics counters will be collected every minute and sent to Application Insights + */ + enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics; + /** + * Sets the state of pre aggregated metrics tracking (enabled by default) + * if true pre aggregated metrics will be collected every minute and sent to Application Insights + */ + enableAutoCollectPreAggregatedMetrics: boolean; + /** + * Sets the state of request tracking (enabled by default) + * if true HeartBeat metric data will be collected every 15 minutes and sent to Application Insights + */ + enableAutoCollectHeartbeat: boolean; + /** + * Sets the state of request tracking (enabled by default) + * if true requests will be sent to Application Insights + */ + enableAutoCollectRequests: boolean; + /** + * Sets the state of dependency tracking (enabled by default) + * if true dependencies will be sent to Application Insights + */ + enableAutoCollectDependencies: boolean; + /** + * Sets the state of automatic dependency correlation (enabled by default) + * if true dependencies will be correlated with requests + */ + enableAutoDependencyCorrelation: boolean; + /** + * Sets the state of automatic dependency correlation (enabled by default) + * if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. + */ + enableUseAsyncHooks: boolean; + /** + * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) + * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients. + * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true). + * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. + * enableUseDiskRetryCaching if true events that occured while client is offline will be cached on disk + * enableResendInterval The wait interval for resending cached events. + * enableMaxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. + */ + enableUseDiskRetryCaching: boolean; + enableResendInterval: number; + enableMaxBytesOnDisk: number; + /** + * Enables debug and warning logging for AppInsights itself. + * if true, enables debug logging + */ + enableInternalDebugLogging: boolean; + /** + * Enables debug and warning logging for AppInsights itself. + * if true, enables warning logging + */ + enableInternalWarningLogging: boolean; + /** + * Enables communication with Application Insights Live Metrics. + * if true, enables communication with the live metrics service + */ + enableSendLiveMetrics: boolean; + /** + * Disable all environment variables set + */ + disableAllExtendedMetrics: boolean; + /** + * Disable individual environment variables set. eg. "extendedMetricDisablers": "..." + */ + extendedMetricDisablers: string; + /** + * Disable Statsbeat + */ + disableStatsbeat: boolean; + /** + * Live Metrics custom host + */ + quickPulseHost: string; + /** + * @deprecated, please use enableWebInstrumentation instead + * Enable web snippet auto html injection, default to false, this config is NOT exposed in documentation after version 2.3.5 + */ + enableAutoWebSnippetInjection?: boolean; + /** + * @deprecated, Please use webInstrumentationConnectionString instead + * Application Insights resource connection string for web snippet, this config is NOT exposed in documentation after version 2.3.5 + * Note: if no valid connection string is provided here, web snippet will use the connection string during initializing Nodejs SDK + */ + webSnippetConnectionString?: string; + /** + * Enable web instrumentation and automatic monitoring, default to false + */ + enableWebInstrumentation: boolean; + /** + * Enable automatic incoming request tracking when running in Azure Functions + */ + enableAutoCollectIncomingRequestAzureFunctions: boolean; + /** + * Application Insights resource connection string for web instrumentation and automatic monitoring + * Note: if no VALID connection string is provided here, web instrumentation will use the connection string during initializing Nodejs SDK + */ + webInstrumentationConnectionString?: string; + /** + * Application Insights web Instrumentation config + * NOTE: if no config is provided here, web instrumentation will use default values + * IMPORTANT NOTE: please convert any functions and objects to double-quoted strings, otherwise they will be skipped. + * For example: if you want to pass in a function: function() { return 'hi'; }, + * you SHOULD wrap it in double-quoted string: "function () {\n return \"hi\";\n}" + * see more Application Insights web Instrumentation config details at: https://github.com/microsoft/ApplicationInsights-JS#configuration + */ + webInstrumentationConfig?: IWebInstrumentationConfig[]; + /** + * Application Insights web Instrumentation CDN url + * NOTE: this config can be changed from env variable: APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE or Json Config: webInstrumentationSrc + * If no resouce is provided here, default CDN endpoint: https://js.monitor.azure.com/scripts/b/ai will be used + * see more details at: https://github.com/microsoft/ApplicationInsights-JS + */ + webInstrumentationSrc?: string; +} +export interface IWebInstrumentationConfig { + /** + * Name of Application Insights web Instrumentation config to be changed + * see more Application Insights web Instrumentation config details at: https://github.com/microsoft/ApplicationInsights-JS#configuration + */ + name: string; + /** + * value provided to replace the default config value above + */ + value: string | boolean | number; +} +export interface IEnvironmentConfig { + /** Connection String used to send telemetry payloads to */ + connectionString: string; + /** + * In order to track context across asynchronous calls, + * some changes are required in third party libraries such as mongodb and redis. + * By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries. + * This property is to disable the feature. + * Note that by setting this flag, events may no longer be correctly associated with the right operation. + */ + noDiagnosticChannel: boolean; + /** + * Disable individual monkey-patches. + * Set `noPatchModules` to a comma separated list of packages to disable. + * e.g. `"noPatchModules": "console,redis"` to avoid patching the console and redis packages. + * The following modules are available: `azuresdk, bunyan, console, mongodb, mongodb-core, mysql, redis, winston, pg`, and `pg-pool`. + */ + noPatchModules: string; + /** + * HTTPS without a passed in agent + */ + noHttpAgentKeepAlive: boolean; +} +export interface IJsonConfig extends IBaseConfig, IEnvironmentConfig { +} +export interface IConfig extends IBaseConfig { + /** An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) */ + httpAgent: http.Agent; + /** An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) */ + httpsAgent: https.Agent; + /** AAD TokenCredential to use to authenticate the app */ + aadTokenCredential?: azureCoreAuth.TokenCredential; +} diff --git a/node_modules/applicationinsights/out/Declarations/Interfaces.js b/node_modules/applicationinsights/out/Declarations/Interfaces.js new file mode 100644 index 0000000..e74847b --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Interfaces.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Interfaces.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Interfaces.js.map b/node_modules/applicationinsights/out/Declarations/Interfaces.js.map new file mode 100644 index 0000000..970d139 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Interfaces.js","sourceRoot":"","sources":["../../Declarations/Interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport * as azureCoreAuth from \"@azure/core-auth\";\r\nimport { DistributedTracingModes } from \"../applicationinsights\";\r\nimport { IDisabledExtendedMetrics } from \"../AutoCollection/NativePerformance\";\r\n\r\n\r\nexport interface IBaseConfig {\r\n /** Application Insights resource instrumentation key */\r\n instrumentationKey: string;\r\n /** The ingestion endpoint to send telemetry payloads to */\r\n endpointUrl: string;\r\n /** The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default 250) */\r\n maxBatchSize: number;\r\n /** The maximum amount of time to wait for a payload to reach maxBatchSize (Default 15000) */\r\n maxBatchIntervalMs: number;\r\n /** A flag indicating if telemetry transmission is disabled (Default false) */\r\n disableAppInsights: boolean;\r\n /** The percentage of telemetry items tracked that should be transmitted (Default 100) */\r\n samplingPercentage: number;\r\n /** The time to wait before retrying to retrieve the id for cross-component correlation (Default 30000) */\r\n correlationIdRetryIntervalMs: number;\r\n /** A list of domains to exclude from cross-component header injection */\r\n correlationHeaderExcludedDomains: string[];\r\n /** A proxy server for SDK HTTP traffic (Optional, Default pulled from `http_proxy` environment variable) */\r\n proxyHttpUrl: string;\r\n /** A proxy server for SDK HTTPS traffic (Optional, Default pulled from `https_proxy` environment variable) */\r\n proxyHttpsUrl: string;\r\n /** Disable including legacy headers in outgoing requests, x-ms-request-id */\r\n ignoreLegacyHeaders: boolean;\r\n /**\r\n * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context\r\n * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing\r\n * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included.\r\n * Enabling W3C mode will not break existing correlation with other Application Insights instrumented\r\n * services. Default=AI\r\n */\r\n distributedTracingMode: DistributedTracingModes;\r\n /**\r\n * Sets the state of console\r\n * if true logger activity will be sent to Application Insights\r\n */\r\n enableAutoCollectExternalLoggers: boolean;\r\n /**\r\n * Sets the state of logger tracking (enabled by default for third-party loggers only)\r\n * if true, logger autocollection will include console.log calls (default false)\r\n */\r\n enableAutoCollectConsole: boolean;\r\n /**\r\n * Sets the state of exception tracking (enabled by default)\r\n * if true uncaught exceptions will be sent to Application Insights\r\n */\r\n enableAutoCollectExceptions: boolean;\r\n /**\r\n * Sets the state of performance tracking (enabled by default)\r\n * if true performance counters will be collected every second and sent to Application Insights\r\n */\r\n enableAutoCollectPerformance: boolean;\r\n /**\r\n * Sets the state of performance tracking (enabled by default)\r\n * if true, extended metrics counters will be collected every minute and sent to Application Insights\r\n */\r\n enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics;\r\n /**\r\n * Sets the state of pre aggregated metrics tracking (enabled by default)\r\n * if true pre aggregated metrics will be collected every minute and sent to Application Insights\r\n */\r\n enableAutoCollectPreAggregatedMetrics: boolean;\r\n /**\r\n * Sets the state of request tracking (enabled by default)\r\n * if true HeartBeat metric data will be collected every 15 minutes and sent to Application Insights\r\n */\r\n enableAutoCollectHeartbeat: boolean;\r\n /**\r\n * Sets the state of request tracking (enabled by default)\r\n * if true requests will be sent to Application Insights\r\n */\r\n enableAutoCollectRequests: boolean;\r\n /**\r\n * Sets the state of dependency tracking (enabled by default)\r\n * if true dependencies will be sent to Application Insights\r\n */\r\n enableAutoCollectDependencies: boolean;\r\n /**\r\n * Sets the state of automatic dependency correlation (enabled by default)\r\n * if true dependencies will be correlated with requests\r\n */\r\n enableAutoDependencyCorrelation: boolean;\r\n /**\r\n * Sets the state of automatic dependency correlation (enabled by default)\r\n * if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js.\r\n */\r\n enableUseAsyncHooks: boolean;\r\n /**\r\n * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default)\r\n * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients.\r\n * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true).\r\n * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible.\r\n * enableUseDiskRetryCaching if true events that occured while client is offline will be cached on disk\r\n * enableResendInterval The wait interval for resending cached events.\r\n * enableMaxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled.\r\n */\r\n enableUseDiskRetryCaching: boolean;\r\n enableResendInterval: number;\r\n enableMaxBytesOnDisk: number;\r\n /**\r\n * Enables debug and warning logging for AppInsights itself.\r\n * if true, enables debug logging\r\n */\r\n enableInternalDebugLogging: boolean;\r\n /**\r\n * Enables debug and warning logging for AppInsights itself.\r\n * if true, enables warning logging\r\n */\r\n enableInternalWarningLogging: boolean;\r\n /**\r\n * Enables communication with Application Insights Live Metrics.\r\n * if true, enables communication with the live metrics service\r\n */\r\n enableSendLiveMetrics: boolean;\r\n /**\r\n * Disable all environment variables set\r\n */\r\n disableAllExtendedMetrics: boolean;\r\n /**\r\n * Disable individual environment variables set. eg. \"extendedMetricDisablers\": \"...\"\r\n */\r\n extendedMetricDisablers: string;\r\n /**\r\n * Disable Statsbeat\r\n */\r\n disableStatsbeat: boolean;\r\n /**\r\n * Live Metrics custom host\r\n */\r\n quickPulseHost: string;\r\n /**\r\n * @deprecated, please use enableWebInstrumentation instead\r\n * Enable web snippet auto html injection, default to false, this config is NOT exposed in documentation after version 2.3.5\r\n */\r\n enableAutoWebSnippetInjection?: boolean;\r\n /**\r\n * @deprecated, Please use webInstrumentationConnectionString instead\r\n * Application Insights resource connection string for web snippet, this config is NOT exposed in documentation after version 2.3.5\r\n * Note: if no valid connection string is provided here, web snippet will use the connection string during initializing Nodejs SDK\r\n */\r\n webSnippetConnectionString?: string;\r\n /**\r\n * Enable web instrumentation and automatic monitoring, default to false\r\n */\r\n enableWebInstrumentation: boolean;\r\n /**\r\n * Enable automatic incoming request tracking when running in Azure Functions\r\n */\r\n enableAutoCollectIncomingRequestAzureFunctions: boolean;\r\n /**\r\n * Application Insights resource connection string for web instrumentation and automatic monitoring\r\n * Note: if no VALID connection string is provided here, web instrumentation will use the connection string during initializing Nodejs SDK\r\n */\r\n webInstrumentationConnectionString?: string;\r\n /**\r\n * Application Insights web Instrumentation config\r\n * NOTE: if no config is provided here, web instrumentation will use default values\r\n * IMPORTANT NOTE: please convert any functions and objects to double-quoted strings, otherwise they will be skipped.\r\n * For example: if you want to pass in a function: function() { return 'hi'; },\r\n * you SHOULD wrap it in double-quoted string: \"function () {\\n return \\\"hi\\\";\\n}\"\r\n * see more Application Insights web Instrumentation config details at: https://github.com/microsoft/ApplicationInsights-JS#configuration\r\n */\r\n webInstrumentationConfig?: IWebInstrumentationConfig[];\r\n /**\r\n * Application Insights web Instrumentation CDN url\r\n * NOTE: this config can be changed from env variable: APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE or Json Config: webInstrumentationSrc\r\n * If no resouce is provided here, default CDN endpoint: https://js.monitor.azure.com/scripts/b/ai will be used\r\n * see more details at: https://github.com/microsoft/ApplicationInsights-JS\r\n */\r\n webInstrumentationSrc?: string;\r\n}\r\n\r\nexport interface IWebInstrumentationConfig {\r\n /**\r\n * Name of Application Insights web Instrumentation config to be changed\r\n * see more Application Insights web Instrumentation config details at: https://github.com/microsoft/ApplicationInsights-JS#configuration\r\n */\r\n name: string;\r\n /**\r\n * value provided to replace the default config value above\r\n */\r\n value: string | boolean | number;\r\n}\r\n\r\nexport interface IEnvironmentConfig {\r\n /** Connection String used to send telemetry payloads to */\r\n connectionString: string;\r\n /**\r\n * In order to track context across asynchronous calls,\r\n * some changes are required in third party libraries such as mongodb and redis.\r\n * By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries.\r\n * This property is to disable the feature.\r\n * Note that by setting this flag, events may no longer be correctly associated with the right operation.\r\n */\r\n noDiagnosticChannel: boolean;\r\n /**\r\n * Disable individual monkey-patches.\r\n * Set `noPatchModules` to a comma separated list of packages to disable.\r\n * e.g. `\"noPatchModules\": \"console,redis\"` to avoid patching the console and redis packages.\r\n * The following modules are available: `azuresdk, bunyan, console, mongodb, mongodb-core, mysql, redis, winston, pg`, and `pg-pool`.\r\n */\r\n noPatchModules: string;\r\n /**\r\n * HTTPS without a passed in agent\r\n */\r\n noHttpAgentKeepAlive: boolean;\r\n}\r\n\r\nexport interface IJsonConfig extends IBaseConfig, IEnvironmentConfig { }\r\n\r\nexport interface IConfig extends IBaseConfig {\r\n /** An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) */\r\n httpAgent: http.Agent;\r\n /** An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) */\r\n httpsAgent: https.Agent;\r\n /** AAD TokenCredential to use to authenticate the app */\r\n aadTokenCredential?: azureCoreAuth.TokenCredential;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.d.ts b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.d.ts new file mode 100644 index 0000000..2216aa8 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.d.ts @@ -0,0 +1,11 @@ +import Constants = require("../Constants"); +export declare class AggregatedMetric { + name: string; + metricType: Constants.MetricId; + dimensions: { + [key: string]: any; + }; + value: number; + count: number; + aggregationInterval: number; +} diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js new file mode 100644 index 0000000..3914a56 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregatedMetric = void 0; +var AggregatedMetric = /** @class */ (function () { + function AggregatedMetric() { + } + return AggregatedMetric; +}()); +exports.AggregatedMetric = AggregatedMetric; +//# sourceMappingURL=AggregatedMetric.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js.map b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js.map new file mode 100644 index 0000000..8f2415f --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetric.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AggregatedMetric.js","sourceRoot":"","sources":["../../../Declarations/Metrics/AggregatedMetric.ts"],"names":[],"mappings":";;;AAEA;IAAA;IAaA,CAAC;IAAD,uBAAC;AAAD,CAAC,AAbD,IAaC;AAbY,4CAAgB","sourcesContent":["import Constants = require(\"../Constants\");\r\n\r\nexport class AggregatedMetric {\r\n\r\n public name: string;\r\n\r\n public metricType: Constants.MetricId;\r\n\r\n public dimensions: { [key: string]: any; };\r\n\r\n public value: number;\r\n\r\n public count: number;\r\n\r\n public aggregationInterval: number;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.d.ts b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.d.ts new file mode 100644 index 0000000..c20b5e6 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.d.ts @@ -0,0 +1,11 @@ +import { MetricBaseDimensions } from "./AggregatedMetricDimensions"; +export declare class AggregatedMetricCounter { + time: number; + lastTime: number; + totalCount: number; + lastTotalCount: number; + intervalExecutionTime: number; + lastIntervalExecutionTime: number; + dimensions: MetricBaseDimensions; + constructor(dimensions: MetricBaseDimensions); +} diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js new file mode 100644 index 0000000..3474817 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AggregatedMetricCounter = void 0; +var AggregatedMetricCounter = /** @class */ (function () { + function AggregatedMetricCounter(dimensions) { + this.dimensions = dimensions; + this.totalCount = 0; + this.lastTotalCount = 0; + this.intervalExecutionTime = 0; + this.lastTime = +new Date; + this.lastIntervalExecutionTime = 0; + } + return AggregatedMetricCounter; +}()); +exports.AggregatedMetricCounter = AggregatedMetricCounter; +//# sourceMappingURL=AggregatedMetricCounters.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js.map b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js.map new file mode 100644 index 0000000..4e4bb7a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricCounters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AggregatedMetricCounters.js","sourceRoot":"","sources":["../../../Declarations/Metrics/AggregatedMetricCounters.ts"],"names":[],"mappings":";;;AAEA;IAgBI,iCAAY,UAAgC;QACxC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,qBAAqB,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,CAAC,IAAI,IAAI,CAAC;QAC1B,IAAI,CAAC,yBAAyB,GAAG,CAAC,CAAC;IACvC,CAAC;IACL,8BAAC;AAAD,CAAC,AAxBD,IAwBC;AAxBY,0DAAuB","sourcesContent":["import { MetricBaseDimensions } from \"./AggregatedMetricDimensions\";\r\n\r\nexport class AggregatedMetricCounter {\r\n\r\n public time: number;\r\n\r\n public lastTime: number;\r\n\r\n public totalCount: number;\r\n\r\n public lastTotalCount: number;\r\n\r\n public intervalExecutionTime: number;\r\n\r\n public lastIntervalExecutionTime: number;\r\n\r\n public dimensions: MetricBaseDimensions;\r\n\r\n constructor(dimensions: MetricBaseDimensions) {\r\n this.dimensions = dimensions;\r\n this.totalCount = 0;\r\n this.lastTotalCount = 0;\r\n this.intervalExecutionTime = 0;\r\n this.lastTime = +new Date;\r\n this.lastIntervalExecutionTime = 0;\r\n }\r\n}\r\n\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.d.ts b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.d.ts new file mode 100644 index 0000000..0d66e7a --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.d.ts @@ -0,0 +1,25 @@ +export interface MetricBaseDimensions { + cloudRoleInstance?: string; + cloudRoleName?: string; +} +export interface MetricDependencyDimensions extends MetricBaseDimensions { + dependencyType?: string; + dependencyTarget?: string; + dependencySuccess?: boolean; + dependencyResultCode?: string; + operationSynthetic?: string; +} +export interface MetricRequestDimensions extends MetricBaseDimensions { + requestSuccess?: boolean; + requestResultCode?: string; + operationSynthetic?: string; +} +export interface MetricExceptionDimensions extends MetricBaseDimensions { +} +export interface MetricTraceDimensions extends MetricBaseDimensions { + traceSeverityLevel?: string; +} +export declare type MetricDimensionTypeKeys = "cloudRoleInstance" | "cloudRoleName" | "requestSuccess" | "requestResultCode" | "dependencyType" | "dependencyTarget" | "dependencySuccess" | "dependencyResultCode" | "traceSeverityLevel" | "operationSynthetic"; +export declare const PreaggregatedMetricPropertyNames: { + [key in MetricDimensionTypeKeys]: string; +}; diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js new file mode 100644 index 0000000..c386559 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PreaggregatedMetricPropertyNames = void 0; +// Names expected in Breeze side for dimensions +exports.PreaggregatedMetricPropertyNames = { + cloudRoleInstance: "cloud/roleInstance", + cloudRoleName: "cloud/roleName", + operationSynthetic: "operation/synthetic", + requestSuccess: "Request.Success", + requestResultCode: "request/resultCode", + dependencyType: "Dependency.Type", + dependencyTarget: "dependency/target", + dependencySuccess: "Dependency.Success", + dependencyResultCode: "dependency/resultCode", + traceSeverityLevel: "trace/severityLevel" +}; +//# sourceMappingURL=AggregatedMetricDimensions.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js.map b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js.map new file mode 100644 index 0000000..a92f511 --- /dev/null +++ b/node_modules/applicationinsights/out/Declarations/Metrics/AggregatedMetricDimensions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AggregatedMetricDimensions.js","sourceRoot":"","sources":["../../../Declarations/Metrics/AggregatedMetricDimensions.ts"],"names":[],"mappings":";;;AA6BA,+CAA+C;AAClC,QAAA,gCAAgC,GAAiD;IAC1F,iBAAiB,EAAE,oBAAoB;IACvC,aAAa,EAAE,gBAAgB;IAC/B,kBAAkB,EAAE,qBAAqB;IACzC,cAAc,EAAE,iBAAiB;IACjC,iBAAiB,EAAE,oBAAoB;IACvC,cAAc,EAAE,iBAAiB;IACjC,gBAAgB,EAAE,mBAAmB;IACrC,iBAAiB,EAAE,oBAAoB;IACvC,oBAAoB,EAAE,uBAAuB;IAC7C,kBAAkB,EAAE,qBAAqB;CAC5C,CAAC","sourcesContent":["export interface MetricBaseDimensions {\r\n cloudRoleInstance?: string;\r\n cloudRoleName?: string\r\n}\r\n\r\nexport interface MetricDependencyDimensions extends MetricBaseDimensions {\r\n dependencyType?: string;\r\n dependencyTarget?: string;\r\n dependencySuccess?: boolean;\r\n dependencyResultCode?: string;\r\n operationSynthetic?: string;\r\n}\r\n\r\nexport interface MetricRequestDimensions extends MetricBaseDimensions {\r\n requestSuccess?: boolean;\r\n requestResultCode?: string;\r\n operationSynthetic?: string;\r\n}\r\n\r\nexport interface MetricExceptionDimensions extends MetricBaseDimensions {\r\n}\r\n\r\nexport interface MetricTraceDimensions extends MetricBaseDimensions {\r\n traceSeverityLevel?: string;\r\n}\r\n\r\nexport type MetricDimensionTypeKeys = \"cloudRoleInstance\" | \"cloudRoleName\" | \"requestSuccess\" | \"requestResultCode\"\r\n | \"dependencyType\" | \"dependencyTarget\" | \"dependencySuccess\" | \"dependencyResultCode\" | \"traceSeverityLevel\" | \"operationSynthetic\";\r\n\r\n// Names expected in Breeze side for dimensions\r\nexport const PreaggregatedMetricPropertyNames: { [key in MetricDimensionTypeKeys]: string } = {\r\n cloudRoleInstance: \"cloud/roleInstance\",\r\n cloudRoleName: \"cloud/roleName\",\r\n operationSynthetic: \"operation/synthetic\",\r\n requestSuccess: \"Request.Success\",\r\n requestResultCode: \"request/resultCode\",\r\n dependencyType: \"Dependency.Type\",\r\n dependencyTarget: \"dependency/target\",\r\n dependencySuccess: \"Dependency.Success\",\r\n dependencyResultCode: \"dependency/resultCode\",\r\n traceSeverityLevel: \"trace/severityLevel\"\r\n};\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/AuthorizationHandler.d.ts b/node_modules/applicationinsights/out/Library/AuthorizationHandler.d.ts new file mode 100644 index 0000000..b15ff67 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AuthorizationHandler.d.ts @@ -0,0 +1,13 @@ +/// +import http = require("http"); +import https = require("https"); +import azureCoreAuth = require("@azure/core-auth"); +declare class AuthorizationHandler { + private _azureTokenPolicy; + constructor(credential: azureCoreAuth.TokenCredential); + /** + * Applies the Bearer token to the request through the Authorization header. + */ + addAuthorizationHeader(requestOptions: http.RequestOptions | https.RequestOptions): Promise; +} +export = AuthorizationHandler; diff --git a/node_modules/applicationinsights/out/Library/AuthorizationHandler.js b/node_modules/applicationinsights/out/Library/AuthorizationHandler.js new file mode 100644 index 0000000..7ce7415 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AuthorizationHandler.js @@ -0,0 +1,71 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var azureCore = require("@azure/core-rest-pipeline"); +var applicationInsightsResource = "https://monitor.azure.com//.default"; +function emptySendRequest(_request) { + return null; +} +var AuthorizationHandler = /** @class */ (function () { + function AuthorizationHandler(credential) { + var scopes = [applicationInsightsResource]; + this._azureTokenPolicy = azureCore.bearerTokenAuthenticationPolicy({ credential: credential, scopes: scopes }); + } + /** + * Applies the Bearer token to the request through the Authorization header. + */ + AuthorizationHandler.prototype.addAuthorizationHeader = function (requestOptions) { + return __awaiter(this, void 0, void 0, function () { + var authHeaderName, webResource; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + authHeaderName = "authorization"; + webResource = azureCore.createPipelineRequest({ url: "https://" }); + return [4 /*yield*/, this._azureTokenPolicy.sendRequest(webResource, emptySendRequest)]; + case 1: + _a.sent(); + requestOptions.headers[authHeaderName] = webResource.headers.get(authHeaderName); + return [2 /*return*/]; + } + }); + }); + }; + return AuthorizationHandler; +}()); +module.exports = AuthorizationHandler; +//# sourceMappingURL=AuthorizationHandler.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/AuthorizationHandler.js.map b/node_modules/applicationinsights/out/Library/AuthorizationHandler.js.map new file mode 100644 index 0000000..8b438ff --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AuthorizationHandler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AuthorizationHandler.js","sourceRoot":"","sources":["../../Library/AuthorizationHandler.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,qDAAwD;AAExD,IAAM,2BAA2B,GAAG,qCAAqC,CAAC;AAG1E,SAAS,gBAAgB,CAAC,QAAmC;IAC3D,OAAO,IAAI,CAAC;AACd,CAAC;AAED;IAIE,8BAAY,UAAyC;QACnD,IAAI,MAAM,GAAa,CAAC,2BAA2B,CAAC,CAAC;QACrD,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC,+BAA+B,CAAC,EAAE,UAAU,YAAA,EAAE,MAAM,QAAA,EAAE,CAAC,CAAC;IAC7F,CAAC;IAED;;MAEE;IACW,qDAAsB,GAAnC,UAAoC,cAA0D;;;;;;wBACxF,cAAc,GAAG,eAAe,CAAC;wBACjC,WAAW,GAAG,SAAS,CAAC,qBAAqB,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC;wBACvE,qBAAM,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,WAAW,EAAE,gBAAgB,CAAC,EAAA;;wBAAvE,SAAuE,CAAC;wBACxE,cAAc,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;;;;;KAClF;IACH,2BAAC;AAAD,CAAC,AAlBD,IAkBC;AAED,iBAAS,oBAAoB,CAAC","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport azureCoreAuth = require(\"@azure/core-auth\");\r\nimport azureCore = require(\"@azure/core-rest-pipeline\");\r\n\r\nconst applicationInsightsResource = \"https://monitor.azure.com//.default\";\r\n\r\n\r\nfunction emptySendRequest(_request: azureCore.PipelineRequest): Promise {\r\n return null;\r\n}\r\n\r\nclass AuthorizationHandler {\r\n\r\n private _azureTokenPolicy: azureCore.PipelinePolicy;\r\n\r\n constructor(credential: azureCoreAuth.TokenCredential) {\r\n let scopes: string[] = [applicationInsightsResource];\r\n this._azureTokenPolicy = azureCore.bearerTokenAuthenticationPolicy({ credential, scopes });\r\n }\r\n\r\n /**\r\n * Applies the Bearer token to the request through the Authorization header.\r\n */\r\n public async addAuthorizationHeader(requestOptions: http.RequestOptions | https.RequestOptions): Promise {\r\n let authHeaderName = \"authorization\";\r\n let webResource = azureCore.createPipelineRequest({ url: \"https://\" });\r\n await this._azureTokenPolicy.sendRequest(webResource, emptySendRequest);\r\n requestOptions.headers[authHeaderName] = webResource.headers.get(authHeaderName);\r\n }\r\n}\r\n\r\nexport = AuthorizationHandler;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/AzureVirtualMachine.d.ts b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.d.ts new file mode 100644 index 0000000..ddfba3e --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.d.ts @@ -0,0 +1,13 @@ +import Config = require("./Config"); +export interface IVirtualMachineInfo { + isVM?: boolean; + id?: string; + subscriptionId?: string; + osType?: string; +} +export declare class AzureVirtualMachine { + static HTTP_TIMEOUT: number; + private static TAG; + private static _requestTimedOut; + static getAzureComputeMetadata(config: Config, callback: (vm: IVirtualMachineInfo) => void): void; +} diff --git a/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js new file mode 100644 index 0000000..628fabd --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AzureVirtualMachine = void 0; +var Logging = require("./Logging"); +var Util = require("./Util"); +var AutoCollectHttpDependencies = require("../AutoCollection/HttpDependencies"); +var AIMS_URI = "http://169.254.169.254/metadata/instance/compute"; +var AIMS_API_VERSION = "api-version=2017-12-01"; +var AIMS_FORMAT = "format=json"; +var ConnectionErrorMessage = "UNREACH"; // EHOSTUNREACH, ENETUNREACH +var AzureVirtualMachine = /** @class */ (function () { + function AzureVirtualMachine() { + } + AzureVirtualMachine.getAzureComputeMetadata = function (config, callback) { + var _a; + var _this = this; + var vmInfo = {}; + var metadataRequestUrl = AIMS_URI + "?" + AIMS_API_VERSION + "&" + AIMS_FORMAT; + var requestOptions = (_a = { + method: "GET" + }, + _a[AutoCollectHttpDependencies.disableCollectionRequestOption] = true, + _a.headers = { + "Metadata": "True" + }, + _a); + var req = Util.makeRequest(config, metadataRequestUrl, requestOptions, function (res) { + if (res.statusCode === 200) { + // Success; VM + vmInfo.isVM = true; + var virtualMachineData_1 = ""; + res.on("data", function (data) { + virtualMachineData_1 += data; + }); + res.on("end", function () { + try { + var data = JSON.parse(virtualMachineData_1); + vmInfo.id = data["vmId"] || ""; + vmInfo.subscriptionId = data["subscriptionId"] || ""; + vmInfo.osType = data["osType"] || ""; + } + catch (error) { + // Failed to parse JSON + Logging.info(AzureVirtualMachine.TAG, error); + } + callback(vmInfo); + }); + } + else { + callback(vmInfo); + } + }, false, false); + if (req) { + setTimeout(function () { + _this._requestTimedOut = true; + req.abort(); + }, AzureVirtualMachine.HTTP_TIMEOUT); + req.on("error", function (error) { + // Unable to contact endpoint. + // Do nothing for now. + if (_this._requestTimedOut) { + if (error) { + error.name = "telemetry timeout"; + error.message = "telemetry request timed out"; + } + } + if (error && error.message && error.message.indexOf(ConnectionErrorMessage) > -1) { + vmInfo.isVM = false; // confirm it's not in VM + } + else { + // Only log when is not determined if VM or not to avoid noise outside of Azure VMs + Logging.info(AzureVirtualMachine.TAG, error); + } + callback(vmInfo); + }); + req.end(); + } + }; + AzureVirtualMachine.HTTP_TIMEOUT = 2500; // 2.5 seconds + AzureVirtualMachine.TAG = "AzureVirtualMachine"; + return AzureVirtualMachine; +}()); +exports.AzureVirtualMachine = AzureVirtualMachine; +//# sourceMappingURL=AzureVirtualMachine.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js.map b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js.map new file mode 100644 index 0000000..b339ddb --- /dev/null +++ b/node_modules/applicationinsights/out/Library/AzureVirtualMachine.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AzureVirtualMachine.js","sourceRoot":"","sources":["../../Library/AzureVirtualMachine.ts"],"names":[],"mappings":";;;AAIA,mCAAsC;AACtC,6BAAgC;AAChC,gFAAmF;AAEnF,IAAM,QAAQ,GAAG,kDAAkD,CAAC;AACpE,IAAM,gBAAgB,GAAG,wBAAwB,CAAC;AAClD,IAAM,WAAW,GAAG,aAAa,CAAC;AAClC,IAAM,sBAAsB,GAAG,SAAS,CAAC,CAAC,4BAA4B;AAStE;IAAA;IAsEA,CAAC;IAhEiB,2CAAuB,GAArC,UAAsC,MAAc,EAAE,QAA2C;;QAAjG,iBA+DC;QA9DG,IAAI,MAAM,GAAwB,EAAE,CAAC;QACrC,IAAM,kBAAkB,GAAM,QAAQ,SAAI,gBAAgB,SAAI,WAAa,CAAC;QAC5E,IAAM,cAAc;gBAChB,MAAM,EAAE,KAAK;;YACb,GAAC,2BAA2B,CAAC,8BAA8B,IAAG,IAAI;YAClE,UAAO,GAAE;gBACL,UAAU,EAAE,MAAM;aACrB;eACJ,CAAC;QAEF,IAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,kBAAkB,EAAE,cAAc,EAAE,UAAC,GAAG;YACzE,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,EAAE;gBACxB,cAAc;gBACd,MAAM,C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AA6B,CAAC;qBACjD;iBACJ;gBAED,IAAI,KAAK,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,EAAE;oBAC9E,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,yBAAyB;iBACjD;qBACI;oBACD,mFAAmF;oBACnF,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;iBAChD;gBACD,QAAQ,CAAC,MAAM,CAAC,CAAC;YACrB,CAAC,CAAC,CAAC;YACH,GAAG,CAAC,GAAG,EAAE,CAAC;SACb;IACL,CAAC;IApEa,gCAAY,GAAW,IAAI,CAAC,CAAC,cAAc;IAE1C,uBAAG,GAAG,qBAAqB,CAAC;IAmE/C,0BAAC;CAAA,AAtED,IAsEC;AAtEY,kDAAmB","sourcesContent":["\r\nimport http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport Config = require(\"./Config\");\r\nimport Logging = require(\"./Logging\");\r\nimport Util = require(\"./Util\");\r\nimport AutoCollectHttpDependencies = require(\"../AutoCollection/HttpDependencies\");\r\n\r\nconst AIMS_URI = \"http://169.254.169.254/metadata/instance/compute\";\r\nconst AIMS_API_VERSION = \"api-version=2017-12-01\";\r\nconst AIMS_FORMAT = \"format=json\";\r\nconst ConnectionErrorMessage = \"UNREACH\"; // EHOSTUNREACH, ENETUNREACH\r\n\r\nexport interface IVirtualMachineInfo {\r\n isVM?: boolean;\r\n id?: string;\r\n subscriptionId?: string;\r\n osType?: string;\r\n}\r\n\r\nexport class AzureVirtualMachine {\r\n public static HTTP_TIMEOUT: number = 2500; // 2.5 seconds\r\n\r\n private static TAG = \"AzureVirtualMachine\";\r\n private static _requestTimedOut: boolean;\r\n\r\n public static getAzureComputeMetadata(config: Config, callback: (vm: IVirtualMachineInfo) => void) {\r\n let vmInfo: IVirtualMachineInfo = {};\r\n const metadataRequestUrl = `${AIMS_URI}?${AIMS_API_VERSION}&${AIMS_FORMAT}`;\r\n const requestOptions: http.RequestOptions | https.RequestOptions = {\r\n method: \"GET\",\r\n [AutoCollectHttpDependencies.disableCollectionRequestOption]: true,\r\n headers: {\r\n \"Metadata\": \"True\"\r\n }\r\n };\r\n\r\n const req = Util.makeRequest(config, metadataRequestUrl, requestOptions, (res) => {\r\n if (res.statusCode === 200) {\r\n // Success; VM\r\n vmInfo.isVM = true;\r\n let virtualMachineData = \"\";\r\n res.on(\"data\", (data: any) => {\r\n virtualMachineData += data;\r\n });\r\n res.on(\"end\", () => {\r\n try {\r\n let data = JSON.parse(virtualMachineData);\r\n vmInfo.id = data[\"vmId\"] || \"\";\r\n vmInfo.subscriptionId = data[\"subscriptionId\"] || \"\";\r\n vmInfo.osType = data[\"osType\"] || \"\";\r\n }\r\n catch (error) {\r\n // Failed to parse JSON\r\n Logging.info(AzureVirtualMachine.TAG, error);\r\n }\r\n callback(vmInfo);\r\n });\r\n } else {\r\n callback(vmInfo);\r\n }\r\n }, false, false);\r\n if (req) {\r\n setTimeout(() => {\r\n this._requestTimedOut = true;\r\n req.abort();\r\n }, AzureVirtualMachine.HTTP_TIMEOUT);\r\n\r\n req.on(\"error\", (error: Error) => {\r\n // Unable to contact endpoint.\r\n // Do nothing for now.\r\n if (this._requestTimedOut) {\r\n if (error) {\r\n error.name = \"telemetry timeout\";\r\n error.message = \"telemetry request timed out\";\r\n }\r\n }\r\n\r\n if (error && error.message && error.message.indexOf(ConnectionErrorMessage) > -1) {\r\n vmInfo.isVM = false; // confirm it's not in VM\r\n }\r\n else {\r\n // Only log when is not determined if VM or not to avoid noise outside of Azure VMs\r\n Logging.info(AzureVirtualMachine.TAG, error);\r\n }\r\n callback(vmInfo);\r\n });\r\n req.end();\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Channel.d.ts b/node_modules/applicationinsights/out/Library/Channel.d.ts new file mode 100644 index 0000000..c3e575c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Channel.d.ts @@ -0,0 +1,30 @@ +import Contracts = require("../Declarations/Contracts"); +import Sender = require("./Sender"); +declare class Channel { + protected _lastSend: number; + protected _timeoutHandle: any; + protected _isDisabled: () => boolean; + protected _getBatchSize: () => number; + protected _getBatchIntervalMs: () => number; + _sender: Sender; + _buffer: Contracts.EnvelopeTelemetry[]; + constructor(isDisabled: () => boolean, getBatchSize: () => number, getBatchIntervalMs: () => number, sender: Sender); + /** + * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) + * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. + * @param value if true events that occurred while client is offline will be cached on disk + * @param resendInterval The wait interval for resending cached events. + * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. + * @returns {Configuration} this class + */ + setUseDiskRetryCaching(value: boolean, resendInterval?: number, maxBytesOnDisk?: number): void; + /** + * Add a telemetry item to the send buffer + */ + send(envelope: Contracts.EnvelopeTelemetry): void; + /** + * Immediately send buffered data + */ + triggerSend(isNodeCrashing: boolean, callback?: (v: string) => void): void; +} +export = Channel; diff --git a/node_modules/applicationinsights/out/Library/Channel.js b/node_modules/applicationinsights/out/Library/Channel.js new file mode 100644 index 0000000..819460b --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Channel.js @@ -0,0 +1,84 @@ +"use strict"; +var Logging = require("./Logging"); +var Util = require("./Util"); +var Channel = /** @class */ (function () { + function Channel(isDisabled, getBatchSize, getBatchIntervalMs, sender) { + this._buffer = []; + this._lastSend = 0; + this._isDisabled = isDisabled; + this._getBatchSize = getBatchSize; + this._getBatchIntervalMs = getBatchIntervalMs; + this._sender = sender; + } + /** + * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) + * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. + * @param value if true events that occurred while client is offline will be cached on disk + * @param resendInterval The wait interval for resending cached events. + * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. + * @returns {Configuration} this class + */ + Channel.prototype.setUseDiskRetryCaching = function (value, resendInterval, maxBytesOnDisk) { + this._sender.setDiskRetryMode(value, resendInterval, maxBytesOnDisk); + }; + /** + * Add a telemetry item to the send buffer + */ + Channel.prototype.send = function (envelope) { + var _this = this; + // if master off switch is set, don't send any data + if (this._isDisabled()) { + // Do not send/save data + return; + } + // validate input + if (!envelope) { + Logging.warn("Cannot send null/undefined telemetry"); + return; + } + // enqueue the payload + this._buffer.push(envelope); + // flush if we would exceed the max-size limit by adding this item + if (this._buffer.length >= this._getBatchSize()) { + this.triggerSend(false); + return; + } + // ensure an invocation timeout is set if anything is in the buffer + if (!this._timeoutHandle && this._buffer.length > 0) { + this._timeoutHandle = setTimeout(function () { + _this._timeoutHandle = null; + _this.triggerSend(false); + }, this._getBatchIntervalMs()); + } + }; + /** + * Immediately send buffered data + */ + Channel.prototype.triggerSend = function (isNodeCrashing, callback) { + var bufferIsEmpty = this._buffer.length < 1; + if (!bufferIsEmpty) { + // invoke send + if (isNodeCrashing || Util.isNodeExit) { + this._sender.saveOnCrash(this._buffer); + if (typeof callback === "function") { + callback("data saved on crash"); + } + } + else { + this._sender.send(this._buffer, callback); + } + } + // update lastSend time to enable throttling + this._lastSend = +new Date; + // clear buffer + this._buffer = []; + clearTimeout(this._timeoutHandle); + this._timeoutHandle = null; + if (bufferIsEmpty && typeof callback === "function") { + callback("no data to send"); + } + }; + return Channel; +}()); +module.exports = Channel; +//# sourceMappingURL=Channel.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Channel.js.map b/node_modules/applicationinsights/out/Library/Channel.js.map new file mode 100644 index 0000000..67b268a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Channel.js","sourceRoot":"","sources":["../../Library/Channel.ts"],"names":[],"mappings":";AACA,mCAAsC;AAEtC,6BAAgC;AAEhC;IAWI,iBAAY,UAAyB,EAAE,YAA0B,EAAE,kBA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C,mBAAmB,EAAE,CAAC,CAAC;SAClC;IACL,CAAC;IAED;;OAEG;IACI,6BAAW,GAAlB,UAAmB,cAAuB,EAAE,QAA8B;QACtE,IAAI,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5C,IAAI,CAAC,aAAa,EAAE;YAChB,cAAc;YACd,IAAI,cAAc,IAAI,IAAI,CAAC,UAAU,EAAE;gBACnC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACvC,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;oBAChC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;iBACnC;aACJ;iBAAM;gBACH,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;aAC7C;SACJ;QAED,4CAA4C;QAC5C,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,IAAI,CAAC;QAE3B,eAAe;QACf,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAClC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,aAAa,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YACjD,QAAQ,CAAC,iBAAiB,CAAC,CAAC;SAC/B;IACL,CAAC;IACL,cAAC;AAAD,CAAC,AA/FD,IA+FC;AAED,iBAAS,OAAO,CAAC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\");\r\nimport Logging = require(\"./Logging\");\r\nimport Sender = require(\"./Sender\");\r\nimport Util = require(\"./Util\");\r\n\r\nclass Channel {\r\n protected _lastSend: number;\r\n protected _timeoutHandle: any;\r\n\r\n protected _isDisabled: () => boolean;\r\n protected _getBatchSize: () => number;\r\n protected _getBatchIntervalMs: () => number;\r\n \r\n public _sender: Sender;\r\n public _buffer: Contracts.EnvelopeTelemetry[];\r\n\r\n constructor(isDisabled: () => boolean, getBatchSize: () => number, getBatchIntervalMs: () => number, sender: Sender) {\r\n this._buffer = [];\r\n this._lastSend = 0;\r\n this._isDisabled = isDisabled;\r\n this._getBatchSize = getBatchSize;\r\n this._getBatchIntervalMs = getBatchIntervalMs;\r\n this._sender = sender;\r\n }\r\n\r\n /**\r\n * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default)\r\n * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible.\r\n * @param value if true events that occurred while client is offline will be cached on disk\r\n * @param resendInterval The wait interval for resending cached events.\r\n * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled.\r\n * @returns {Configuration} this class\r\n */\r\n public setUseDiskRetryCaching(value: boolean, resendInterval?: number, maxBytesOnDisk?: number) {\r\n this._sender.setDiskRetryMode(value, resendInterval, maxBytesOnDisk);\r\n }\r\n\r\n /**\r\n * Add a telemetry item to the send buffer\r\n */\r\n public send(envelope: Contracts.EnvelopeTelemetry) {\r\n\r\n // if master off switch is set, don't send any data\r\n if (this._isDisabled()) {\r\n // Do not send/save data\r\n return;\r\n }\r\n\r\n // validate input\r\n if (!envelope) {\r\n Logging.warn(\"Cannot send null/undefined telemetry\");\r\n return;\r\n }\r\n\r\n // enqueue the payload\r\n this._buffer.push(envelope);\r\n\r\n // flush if we would exceed the max-size limit by adding this item\r\n if (this._buffer.length >= this._getBatchSize()) {\r\n this.triggerSend(false);\r\n return;\r\n }\r\n\r\n // ensure an invocation timeout is set if anything is in the buffer\r\n if (!this._timeoutHandle && this._buffer.length > 0) {\r\n this._timeoutHandle = setTimeout(() => {\r\n this._timeoutHandle = null;\r\n this.triggerSend(false);\r\n }, this._getBatchIntervalMs());\r\n }\r\n }\r\n\r\n /**\r\n * Immediately send buffered data\r\n */\r\n public triggerSend(isNodeCrashing: boolean, callback?: (v: string) => void) {\r\n let bufferIsEmpty = this._buffer.length < 1;\r\n if (!bufferIsEmpty) {\r\n // invoke send\r\n if (isNodeCrashing || Util.isNodeExit) {\r\n this._sender.saveOnCrash(this._buffer);\r\n if (typeof callback === \"function\") {\r\n callback(\"data saved on crash\");\r\n }\r\n } else {\r\n this._sender.send(this._buffer, callback);\r\n }\r\n }\r\n\r\n // update lastSend time to enable throttling\r\n this._lastSend = +new Date;\r\n\r\n // clear buffer\r\n this._buffer = [];\r\n clearTimeout(this._timeoutHandle);\r\n this._timeoutHandle = null;\r\n if (bufferIsEmpty && typeof callback === \"function\") {\r\n callback(\"no data to send\");\r\n }\r\n }\r\n}\r\n\r\nexport = Channel;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Config.d.ts b/node_modules/applicationinsights/out/Library/Config.d.ts new file mode 100644 index 0000000..b9b5886 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Config.d.ts @@ -0,0 +1,86 @@ +/// +import azureCoreAuth = require("@azure/core-auth"); +import http = require("http"); +import https = require("https"); +import { IConfig, IWebInstrumentationConfig } from "../Declarations/Interfaces"; +import { DistributedTracingModes } from "../applicationinsights"; +import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance"; +declare class Config implements IConfig { + static ENV_azurePrefix: string; + static ENV_iKey: string; + static legacy_ENV_iKey: string; + static ENV_profileQueryEndpoint: string; + static ENV_quickPulseHost: string; + endpointUrl: string; + maxBatchSize: number; + maxBatchIntervalMs: number; + disableAppInsights: boolean; + samplingPercentage: number; + correlationIdRetryIntervalMs: number; + correlationHeaderExcludedDomains: string[]; + proxyHttpUrl: string; + proxyHttpsUrl: string; + httpAgent: http.Agent; + httpsAgent: https.Agent; + ignoreLegacyHeaders: boolean; + aadTokenCredential?: azureCoreAuth.TokenCredential; + enableAutoCollectConsole: boolean; + enableAutoCollectExceptions: boolean; + enableAutoCollectPerformance: boolean; + enableAutoCollectExternalLoggers: boolean; + enableAutoCollectPreAggregatedMetrics: boolean; + enableAutoCollectHeartbeat: boolean; + enableAutoCollectRequests: boolean; + enableAutoCollectDependencies: boolean; + enableAutoDependencyCorrelation: boolean; + enableAutoCollectIncomingRequestAzureFunctions: boolean; + enableSendLiveMetrics: boolean; + enableUseDiskRetryCaching: boolean; + enableUseAsyncHooks: boolean; + distributedTracingMode: DistributedTracingModes; + enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics; + enableResendInterval: number; + enableMaxBytesOnDisk: number; + enableInternalDebugLogging: boolean; + enableInternalWarningLogging: boolean; + disableAllExtendedMetrics: boolean; + disableStatsbeat: boolean; + extendedMetricDisablers: string; + quickPulseHost: string; + enableWebInstrumentation: boolean; + webInstrumentationConfig: IWebInstrumentationConfig[]; + webInstrumentationSrc: string; + enableAutoWebSnippetInjection: boolean; + correlationId: string; + private _connectionString; + private _endpointBase; + private _profileQueryEndpoint; + private _instrumentationKey; + _webInstrumentationConnectionString: string; + constructor(setupString?: string); + set profileQueryEndpoint(endpoint: string); + get profileQueryEndpoint(): string; + set instrumentationKey(iKey: string); + get instrumentationKey(): string; + set webSnippetConnectionString(connectionString: string); + get webSnippetConnectionString(): string; + set webInstrumentationConnectionString(connectionString: string); + get webInstrumentationConnectionString(): string; + private _mergeConfig; + /** + * Validate UUID Format + * Specs taken from breeze repo + * The definition of a VALID instrumentation key is as follows: + * Not none + * Not empty + * Every character is a hex character [0-9a-f] + * 32 characters are separated into 5 sections via 4 dashes + * First section has 8 characters + * Second section has 4 characters + * Third section has 4 characters + * Fourth section has 4 characters + * Fifth section has 12 characters + */ + private static _validateInstrumentationKey; +} +export = Config; diff --git a/node_modules/applicationinsights/out/Library/Config.js b/node_modules/applicationinsights/out/Library/Config.js new file mode 100644 index 0000000..19601c7 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Config.js @@ -0,0 +1,168 @@ +"use strict"; +var CorrelationIdManager = require("./CorrelationIdManager"); +var ConnectionStringParser = require("./ConnectionStringParser"); +var Logging = require("./Logging"); +var Constants = require("../Declarations/Constants"); +var url = require("url"); +var JsonConfig_1 = require("./JsonConfig"); +var Config = /** @class */ (function () { + function Config(setupString) { + this._endpointBase = Constants.DEFAULT_BREEZE_ENDPOINT; + // Load config values from env variables and JSON if available + this._mergeConfig(); + var connectionStringEnv = this._connectionString; + var csCode = ConnectionStringParser.parse(setupString); + var csEnv = ConnectionStringParser.parse(connectionStringEnv); + var iKeyCode = !csCode.instrumentationkey && Object.keys(csCode).length > 0 + ? null // CS was valid but instrumentation key was not provided, null and grab from env var + : setupString; // CS was invalid, so it must be an ikey + var instrumentationKeyEnv = this._instrumentationKey; + this.instrumentationKey = csCode.instrumentationkey || iKeyCode /* === instrumentationKey */ || csEnv.instrumentationkey || instrumentationKeyEnv; + var endpoint = "" + (this.endpointUrl || csCode.ingestionendpoint || csEnv.ingestionendpoint || this._endpointBase); + if (endpoint.endsWith("/")) { + // Remove extra '/' if present + endpoint = endpoint.slice(0, -1); + } + this.endpointUrl = endpoint + "/v2.1/track"; + this.maxBatchSize = this.maxBatchSize || 250; + this.maxBatchIntervalMs = this.maxBatchIntervalMs || 15000; + this.disableAppInsights = this.disableAppInsights || false; + this.samplingPercentage = this.samplingPercentage || 100; + this.correlationIdRetryIntervalMs = this.correlationIdRetryIntervalMs || 30 * 1000; + this.enableWebInstrumentation = this.enableWebInstrumentation || this.enableAutoWebSnippetInjection || false; + this.webInstrumentationConfig = this.webInstrumentationConfig || null; + this.enableAutoWebSnippetInjection = this.enableWebInstrumentation; + this.correlationHeaderExcludedDomains = + this.correlationHeaderExcludedDomains || + [ + "*.core.windows.net", + "*.core.chinacloudapi.cn", + "*.core.cloudapi.de", + "*.core.usgovcloudapi.net", + "*.core.microsoft.scloud", + "*.core.eaglex.ic.gov" + ]; + this.ignoreLegacyHeaders = this.ignoreLegacyHeaders || false; + this.profileQueryEndpoint = csCode.ingestionendpoint || csEnv.ingestionendpoint || process.env[Config.ENV_profileQueryEndpoint] || this._endpointBase; + this.quickPulseHost = this.quickPulseHost || csCode.liveendpoint || csEnv.liveendpoint || process.env[Config.ENV_quickPulseHost] || Constants.DEFAULT_LIVEMETRICS_HOST; + this.webInstrumentationConnectionString = this.webInstrumentationConnectionString || this._webInstrumentationConnectionString || ""; + this.webSnippetConnectionString = this.webInstrumentationConnectionString; + // Parse quickPulseHost if it starts with http(s):// + if (this.quickPulseHost.match(/^https?:\/\//)) { + this.quickPulseHost = new url.URL(this.quickPulseHost).host; + } + } + Object.defineProperty(Config.prototype, "profileQueryEndpoint", { + get: function () { + return this._profileQueryEndpoint; + }, + set: function (endpoint) { + this._profileQueryEndpoint = endpoint; + this.correlationId = CorrelationIdManager.correlationIdPrefix; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Config.prototype, "instrumentationKey", { + get: function () { + return this._instrumentationKey; + }, + set: function (iKey) { + if (!Config._validateInstrumentationKey(iKey)) { + Logging.warn("An invalid instrumentation key was provided. There may be resulting telemetry loss", this.instrumentationKey); + } + this._instrumentationKey = iKey; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Config.prototype, "webSnippetConnectionString", { + get: function () { + return this._webInstrumentationConnectionString; + }, + set: function (connectionString) { + this._webInstrumentationConnectionString = connectionString; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Config.prototype, "webInstrumentationConnectionString", { + get: function () { + return this._webInstrumentationConnectionString; + }, + set: function (connectionString) { + this._webInstrumentationConnectionString = connectionString; + }, + enumerable: false, + configurable: true + }); + Config.prototype._mergeConfig = function () { + var jsonConfig = JsonConfig_1.JsonConfig.getInstance(); + this._connectionString = jsonConfig.connectionString; + this._instrumentationKey = jsonConfig.instrumentationKey; + this.correlationHeaderExcludedDomains = jsonConfig.correlationHeaderExcludedDomains; + this.correlationIdRetryIntervalMs = jsonConfig.correlationIdRetryIntervalMs; + this.disableAllExtendedMetrics = jsonConfig.disableAllExtendedMetrics; + this.disableAppInsights = jsonConfig.disableAppInsights; + this.disableStatsbeat = jsonConfig.disableStatsbeat; + this.distributedTracingMode = jsonConfig.distributedTracingMode; + this.enableAutoCollectConsole = jsonConfig.enableAutoCollectConsole; + this.enableAutoCollectDependencies = jsonConfig.enableAutoCollectDependencies; + this.enableAutoCollectIncomingRequestAzureFunctions = jsonConfig.enableAutoCollectIncomingRequestAzureFunctions; + this.enableAutoCollectExceptions = jsonConfig.enableAutoCollectExceptions; + this.enableAutoCollectExtendedMetrics = jsonConfig.enableAutoCollectExtendedMetrics; + this.enableAutoCollectExternalLoggers = jsonConfig.enableAutoCollectExternalLoggers; + this.enableAutoCollectHeartbeat = jsonConfig.enableAutoCollectHeartbeat; + this.enableAutoCollectPerformance = jsonConfig.enableAutoCollectPerformance; + this.enableAutoCollectPreAggregatedMetrics = jsonConfig.enableAutoCollectPreAggregatedMetrics; + this.enableAutoCollectRequests = jsonConfig.enableAutoCollectRequests; + this.enableAutoDependencyCorrelation = jsonConfig.enableAutoDependencyCorrelation; + this.enableInternalDebugLogging = jsonConfig.enableInternalDebugLogging; + this.enableInternalWarningLogging = jsonConfig.enableInternalWarningLogging; + this.enableResendInterval = jsonConfig.enableResendInterval; + this.enableMaxBytesOnDisk = jsonConfig.enableMaxBytesOnDisk; + this.enableSendLiveMetrics = jsonConfig.enableSendLiveMetrics; + this.enableUseAsyncHooks = jsonConfig.enableUseAsyncHooks; + this.enableUseDiskRetryCaching = jsonConfig.enableUseDiskRetryCaching; + this.endpointUrl = jsonConfig.endpointUrl; + this.extendedMetricDisablers = jsonConfig.extendedMetricDisablers; + this.ignoreLegacyHeaders = jsonConfig.ignoreLegacyHeaders; + this.maxBatchIntervalMs = jsonConfig.maxBatchIntervalMs; + this.maxBatchSize = jsonConfig.maxBatchSize; + this.proxyHttpUrl = jsonConfig.proxyHttpUrl; + this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl; + this.quickPulseHost = jsonConfig.quickPulseHost; + this.samplingPercentage = jsonConfig.samplingPercentage; + this.enableWebInstrumentation = jsonConfig.enableWebInstrumentation; + this._webInstrumentationConnectionString = jsonConfig.webInstrumentationConnectionString; + this.webInstrumentationConfig = jsonConfig.webInstrumentationConfig; + this.webInstrumentationSrc = jsonConfig.webInstrumentationSrc; + }; + /** + * Validate UUID Format + * Specs taken from breeze repo + * The definition of a VALID instrumentation key is as follows: + * Not none + * Not empty + * Every character is a hex character [0-9a-f] + * 32 characters are separated into 5 sections via 4 dashes + * First section has 8 characters + * Second section has 4 characters + * Third section has 4 characters + * Fourth section has 4 characters + * Fifth section has 12 characters + */ + Config._validateInstrumentationKey = function (iKey) { + var UUID_Regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; + var regexp = new RegExp(UUID_Regex); + return regexp.test(iKey); + }; + Config.ENV_azurePrefix = "APPSETTING_"; // Azure adds this prefix to all environment variables + Config.ENV_iKey = "APPINSIGHTS_INSTRUMENTATIONKEY"; // This key is provided in the readme + Config.legacy_ENV_iKey = "APPINSIGHTS_INSTRUMENTATION_KEY"; + Config.ENV_profileQueryEndpoint = "APPINSIGHTS_PROFILE_QUERY_ENDPOINT"; + Config.ENV_quickPulseHost = "APPINSIGHTS_QUICKPULSE_HOST"; + return Config; +}()); +module.exports = Config; +//# sourceMappingURL=Config.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Config.js.map b/node_modules/applicationinsights/out/Library/Config.js.map new file mode 100644 index 0000000..6fa2b48 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Config.js","sourceRoot":"","sources":["../../Library/Config.ts"],"names":[],"mappings":";AAEA,6DAAgE;AAChE,iEAAoE;AACpE,mCAAsC;AACtC,qDAAwD;AAGxD,yBAA4B;AAC5B,2CAA0C;AAK1C;IA0DI,gBAAY,WAAoB;QALxB,kBAAa,GAAW,SAAS,CAAC,uBAAuB,CAAC;QAM9D,8DAA8D;QAC9D,IAAI,CAAC,YAAY,EAAE,CAAC;QACpB,IAAM,mBAAmB,GAAuB,IAAI,CAAC,iBAAiB,CAAC;QACvE,IAAM,MAAM,GAAG,sBAAsB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC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\r\nimport ConnectionStringParser = require(\"./ConnectionStringParser\");\r\nimport Logging = require(\"./Logging\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport url = require(\"url\");\r\nimport { JsonConfig } from \"./JsonConfig\";\r\nimport { IConfig, IWebInstrumentationConfig } from \"../Declarations/Interfaces\";\r\nimport { DistributedTracingModes } from \"../applicationinsights\";\r\nimport { IDisabledExtendedMetrics } from \"../AutoCollection/NativePerformance\";\r\n\r\nclass Config implements IConfig {\r\n\r\n public static ENV_azurePrefix = \"APPSETTING_\"; // Azure adds this prefix to all environment variables\r\n public static ENV_iKey = \"APPINSIGHTS_INSTRUMENTATIONKEY\"; // This key is provided in the readme\r\n public static legacy_ENV_iKey = \"APPINSIGHTS_INSTRUMENTATION_KEY\";\r\n public static ENV_profileQueryEndpoint = \"APPINSIGHTS_PROFILE_QUERY_ENDPOINT\";\r\n public static ENV_quickPulseHost = \"APPINSIGHTS_QUICKPULSE_HOST\";\r\n\r\n // IConfig properties\r\n public endpointUrl: string;\r\n public maxBatchSize: number;\r\n public maxBatchIntervalMs: number;\r\n public disableAppInsights: boolean;\r\n public samplingPercentage: number;\r\n public correlationIdRetryIntervalMs: number;\r\n public correlationHeaderExcludedDomains: string[];\r\n public proxyHttpUrl: string;\r\n public proxyHttpsUrl: string;\r\n public httpAgent: http.Agent;\r\n public httpsAgent: https.Agent;\r\n public ignoreLegacyHeaders: boolean;\r\n public aadTokenCredential?: azureCoreAuth.TokenCredential;\r\n public enableAutoCollectConsole: boolean;\r\n public enableAutoCollectExceptions: boolean;\r\n public enableAutoCollectPerformance: boolean;\r\n public enableAutoCollectExternalLoggers: boolean;\r\n public enableAutoCollectPreAggregatedMetrics: boolean;\r\n public enableAutoCollectHeartbeat: boolean;\r\n public enableAutoCollectRequests: boolean;\r\n public enableAutoCollectDependencies: boolean;\r\n public enableAutoDependencyCorrelation: boolean;\r\n public enableAutoCollectIncomingRequestAzureFunctions: boolean;\r\n public enableSendLiveMetrics: boolean;\r\n public enableUseDiskRetryCaching: boolean;\r\n public enableUseAsyncHooks: boolean;\r\n public distributedTracingMode: DistributedTracingModes;\r\n public enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics;\r\n public enableResendInterval: number;\r\n public enableMaxBytesOnDisk: number;\r\n public enableInternalDebugLogging: boolean;\r\n public enableInternalWarningLogging: boolean;\r\n public disableAllExtendedMetrics: boolean;\r\n public disableStatsbeat: boolean;\r\n public extendedMetricDisablers: string;\r\n public quickPulseHost: string;\r\n public enableWebInstrumentation: boolean;\r\n public webInstrumentationConfig: IWebInstrumentationConfig[];\r\n public webInstrumentationSrc: string;\r\n // To Be deprecated.\r\n public enableAutoWebSnippetInjection: boolean;\r\n\r\n public correlationId: string; // TODO: Should be private\r\n private _connectionString: string;\r\n private _endpointBase: string = Constants.DEFAULT_BREEZE_ENDPOINT;\r\n private _profileQueryEndpoint: string;\r\n private _instrumentationKey: string;\r\n public _webInstrumentationConnectionString: string;\r\n \r\n constructor(setupString?: string) {\r\n // Load config values from env variables and JSON if available\r\n this._mergeConfig();\r\n const connectionStringEnv: string | undefined = this._connectionString;\r\n const csCode = ConnectionStringParser.parse(setupString);\r\n const csEnv = ConnectionStringParser.parse(connectionStringEnv);\r\n const iKeyCode = !csCode.instrumentationkey && Object.keys(csCode).length > 0\r\n ? null // CS was valid but instrumentation key was not provided, null and grab from env var\r\n : setupString; // CS was invalid, so it must be an ikey\r\n\r\n const instrumentationKeyEnv: string | undefined = this._instrumentationKey;\r\n this.instrumentationKey = csCode.instrumentationkey || iKeyCode /* === instrumentationKey */ || csEnv.instrumentationkey || instrumentationKeyEnv;\r\n let endpoint = `${this.endpointUrl || csCode.ingestionendpoint || csEnv.ingestionendpoint || this._endpointBase}`;\r\n if (endpoint.endsWith(\"/\")) {\r\n // Remove extra '/' if present\r\n endpoint = endpoint.slice(0, -1);\r\n }\r\n this.endpointUrl = `${endpoint}/v2.1/track`;\r\n this.maxBatchSize = this.maxBatchSize || 250;\r\n this.maxBatchIntervalMs = this.maxBatchIntervalMs || 15000;\r\n this.disableAppInsights = this.disableAppInsights || false;\r\n this.samplingPercentage = this.samplingPercentage || 100;\r\n this.correlationIdRetryIntervalMs = this.correlationIdRetryIntervalMs || 30 * 1000;\r\n this.enableWebInstrumentation = this.enableWebInstrumentation || this.enableAutoWebSnippetInjection || false;\r\n this.webInstrumentationConfig = this.webInstrumentationConfig || null;\r\n this.enableAutoWebSnippetInjection = this.enableWebInstrumentation;\r\n this.correlationHeaderExcludedDomains =\r\n this.correlationHeaderExcludedDomains ||\r\n [\r\n \"*.core.windows.net\",\r\n \"*.core.chinacloudapi.cn\",\r\n \"*.core.cloudapi.de\",\r\n \"*.core.usgovcloudapi.net\",\r\n \"*.core.microsoft.scloud\",\r\n \"*.core.eaglex.ic.gov\"\r\n ];\r\n\r\n this.ignoreLegacyHeaders = this.ignoreLegacyHeaders || false;\r\n this.profileQueryEndpoint = csCode.ingestionendpoint || csEnv.ingestionendpoint || process.env[Config.ENV_profileQueryEndpoint] || this._endpointBase;\r\n this.quickPulseHost = this.quickPulseHost || csCode.liveendpoint || csEnv.liveendpoint || process.env[Config.ENV_quickPulseHost] || Constants.DEFAULT_LIVEMETRICS_HOST;\r\n this.webInstrumentationConnectionString = this.webInstrumentationConnectionString || this._webInstrumentationConnectionString || \"\";\r\n this.webSnippetConnectionString = this.webInstrumentationConnectionString;\r\n // Parse quickPulseHost if it starts with http(s)://\r\n if (this.quickPulseHost.match(/^https?:\\/\\//)) {\r\n this.quickPulseHost = new url.URL(this.quickPulseHost).host;\r\n }\r\n }\r\n\r\n public set profileQueryEndpoint(endpoint: string) {\r\n this._profileQueryEndpoint = endpoint;\r\n this.correlationId = CorrelationIdManager.correlationIdPrefix;\r\n }\r\n\r\n public get profileQueryEndpoint() {\r\n return this._profileQueryEndpoint;\r\n }\r\n\r\n public set instrumentationKey(iKey: string) {\r\n if (!Config._validateInstrumentationKey(iKey)) {\r\n Logging.warn(\"An invalid instrumentation key was provided. There may be resulting telemetry loss\", this.instrumentationKey);\r\n }\r\n this._instrumentationKey = iKey;\r\n }\r\n\r\n public get instrumentationKey(): string {\r\n return this._instrumentationKey;\r\n }\r\n\r\n public set webSnippetConnectionString(connectionString: string) {\r\n this._webInstrumentationConnectionString = connectionString;\r\n }\r\n\r\n public get webSnippetConnectionString(): string {\r\n return this._webInstrumentationConnectionString;\r\n }\r\n\r\n public set webInstrumentationConnectionString(connectionString: string) {\r\n this._webInstrumentationConnectionString = connectionString;\r\n }\r\n\r\n public get webInstrumentationConnectionString() {\r\n return this._webInstrumentationConnectionString;\r\n }\r\n\r\n private _mergeConfig() {\r\n let jsonConfig = JsonConfig.getInstance();\r\n this._connectionString = jsonConfig.connectionString;\r\n this._instrumentationKey = jsonConfig.instrumentationKey;\r\n this.correlationHeaderExcludedDomains = jsonConfig.correlationHeaderExcludedDomains;\r\n this.correlationIdRetryIntervalMs = jsonConfig.correlationIdRetryIntervalMs;\r\n this.disableAllExtendedMetrics = jsonConfig.disableAllExtendedMetrics;\r\n this.disableAppInsights = jsonConfig.disableAppInsights;\r\n this.disableStatsbeat = jsonConfig.disableStatsbeat;\r\n this.distributedTracingMode = jsonConfig.distributedTracingMode;\r\n this.enableAutoCollectConsole = jsonConfig.enableAutoCollectConsole;\r\n this.enableAutoCollectDependencies = jsonConfig.enableAutoCollectDependencies;\r\n this.enableAutoCollectIncomingRequestAzureFunctions = jsonConfig.enableAutoCollectIncomingRequestAzureFunctions;\r\n this.enableAutoCollectExceptions = jsonConfig.enableAutoCollectExceptions;\r\n this.enableAutoCollectExtendedMetrics = jsonConfig.enableAutoCollectExtendedMetrics;\r\n this.enableAutoCollectExternalLoggers = jsonConfig.enableAutoCollectExternalLoggers;\r\n this.enableAutoCollectHeartbeat = jsonConfig.enableAutoCollectHeartbeat;\r\n this.enableAutoCollectPerformance = jsonConfig.enableAutoCollectPerformance;\r\n this.enableAutoCollectPreAggregatedMetrics = jsonConfig.enableAutoCollectPreAggregatedMetrics;\r\n this.enableAutoCollectRequests = jsonConfig.enableAutoCollectRequests;\r\n this.enableAutoDependencyCorrelation = jsonConfig.enableAutoDependencyCorrelation;\r\n this.enableInternalDebugLogging = jsonConfig.enableInternalDebugLogging;\r\n this.enableInternalWarningLogging = jsonConfig.enableInternalWarningLogging;\r\n this.enableResendInterval = jsonConfig.enableResendInterval;\r\n this.enableMaxBytesOnDisk = jsonConfig.enableMaxBytesOnDisk;\r\n this.enableSendLiveMetrics = jsonConfig.enableSendLiveMetrics;\r\n this.enableUseAsyncHooks = jsonConfig.enableUseAsyncHooks;\r\n this.enableUseDiskRetryCaching = jsonConfig.enableUseDiskRetryCaching;\r\n this.endpointUrl = jsonConfig.endpointUrl;\r\n this.extendedMetricDisablers = jsonConfig.extendedMetricDisablers;\r\n this.ignoreLegacyHeaders = jsonConfig.ignoreLegacyHeaders;\r\n this.maxBatchIntervalMs = jsonConfig.maxBatchIntervalMs;\r\n this.maxBatchSize = jsonConfig.maxBatchSize;\r\n this.proxyHttpUrl = jsonConfig.proxyHttpUrl;\r\n this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl;\r\n this.quickPulseHost = jsonConfig.quickPulseHost;\r\n this.samplingPercentage = jsonConfig.samplingPercentage;\r\n this.enableWebInstrumentation = jsonConfig.enableWebInstrumentation;\r\n this._webInstrumentationConnectionString = jsonConfig.webInstrumentationConnectionString;\r\n this.webInstrumentationConfig = jsonConfig.webInstrumentationConfig;\r\n this.webInstrumentationSrc = jsonConfig.webInstrumentationSrc;\r\n }\r\n\r\n /**\r\n * Validate UUID Format\r\n * Specs taken from breeze repo\r\n * The definition of a VALID instrumentation key is as follows:\r\n * Not none\r\n * Not empty\r\n * Every character is a hex character [0-9a-f]\r\n * 32 characters are separated into 5 sections via 4 dashes\r\n * First section has 8 characters\r\n * Second section has 4 characters\r\n * Third section has 4 characters\r\n * Fourth section has 4 characters\r\n * Fifth section has 12 characters\r\n */\r\n private static _validateInstrumentationKey(iKey: string): boolean {\r\n const UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\r\n const regexp = new RegExp(UUID_Regex);\r\n return regexp.test(iKey);\r\n }\r\n}\r\n\r\nexport = Config;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/ConnectionStringParser.d.ts b/node_modules/applicationinsights/out/Library/ConnectionStringParser.d.ts new file mode 100644 index 0000000..ee41898 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/ConnectionStringParser.d.ts @@ -0,0 +1,8 @@ +import { ConnectionString } from "../Declarations/Contracts"; +declare class ConnectionStringParser { + private static _FIELDS_SEPARATOR; + private static _FIELD_KEY_VALUE_SEPARATOR; + static parse(connectionString?: string): ConnectionString; + static isIkeyValid(iKey: string): boolean; +} +export = ConnectionStringParser; diff --git a/node_modules/applicationinsights/out/Library/ConnectionStringParser.js b/node_modules/applicationinsights/out/Library/ConnectionStringParser.js new file mode 100644 index 0000000..a1e62c6 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/ConnectionStringParser.js @@ -0,0 +1,46 @@ +"use strict"; +var Constants = require("../Declarations/Constants"); +var ConnectionStringParser = /** @class */ (function () { + function ConnectionStringParser() { + } + ConnectionStringParser.parse = function (connectionString) { + if (!connectionString) { + return {}; + } + var kvPairs = connectionString.split(ConnectionStringParser._FIELDS_SEPARATOR); + var result = kvPairs.reduce(function (fields, kv) { + var kvParts = kv.split(ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR); + if (kvParts.length === 2) { // only save fields with valid formats + var key = kvParts[0].toLowerCase(); + var value = kvParts[1]; + fields[key] = value; + } + return fields; + }, {}); + if (Object.keys(result).length > 0) { + // this is a valid connection string, so parse the results + if (result.endpointsuffix) { + // use endpoint suffix where overrides are not provided + var locationPrefix = result.location ? result.location + "." : ""; + result.ingestionendpoint = result.ingestionendpoint || ("https://" + locationPrefix + "dc." + result.endpointsuffix); + result.liveendpoint = result.liveendpoint || ("https://" + locationPrefix + "live." + result.endpointsuffix); + } + // apply the default endpoints + result.ingestionendpoint = result.ingestionendpoint || Constants.DEFAULT_BREEZE_ENDPOINT; + result.liveendpoint = result.liveendpoint || Constants.DEFAULT_LIVEMETRICS_ENDPOINT; + } + return result; + }; + ConnectionStringParser.isIkeyValid = function (iKey) { + if (!iKey || iKey == "") + return false; + var UUID_Regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; + var regexp = new RegExp(UUID_Regex); + return regexp.test(iKey); + }; + ConnectionStringParser._FIELDS_SEPARATOR = ";"; + ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR = "="; + return ConnectionStringParser; +}()); +module.exports = ConnectionStringParser; +//# sourceMappingURL=ConnectionStringParser.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/ConnectionStringParser.js.map b/node_modules/applicationinsights/out/Library/ConnectionStringParser.js.map new file mode 100644 index 0000000..3e1d9db --- /dev/null +++ b/node_modules/applicationinsights/out/Library/ConnectionStringParser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ConnectionStringParser.js","sourceRoot":"","sources":["../../Library/ConnectionStringParser.ts"],"names":[],"mappings":";AACA,qDAAwD;AAExD;IAAA;IA8CA,CAAC;IA1CiB,4BAAK,GAAnB,UAAoB,gBAAyB;QACzC,IAAI,CAAC,gBAAgB,EAAE;YACnB,OAAO,EAAE,CAAC;SACb;QAED,IAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,CAAC;QAEjF,IAAM,MAAM,GAAqB,OAAO,CAAC,MAAM,CAAC,UAAC,MAAwB,EAAE,EAAU;YACjF,IAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,sBAAsB,CAAC,0BAA0B,CAAC,CAAC;YAE5E,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,sCAAsC;gBAC9D,IA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,IAAI,CAAC,CAAC;IAC7B,CAAC;IA5Cc,wCAAiB,GAAG,GAAG,CAAC;IACxB,iDAA0B,GAAG,GAAG,CAAC;IA4CpD,6BAAC;CAAA,AA9CD,IA8CC;AAED,iBAAS,sBAAsB,CAAC","sourcesContent":["import { ConnectionString, ConnectionStringKey } from \"../Declarations/Contracts\";\r\nimport Constants = require(\"../Declarations/Constants\");\r\n\r\nclass ConnectionStringParser {\r\n private static _FIELDS_SEPARATOR = \";\";\r\n private static _FIELD_KEY_VALUE_SEPARATOR = \"=\";\r\n\r\n public static parse(connectionString?: string): ConnectionString {\r\n if (!connectionString) {\r\n return {};\r\n }\r\n\r\n const kvPairs = connectionString.split(ConnectionStringParser._FIELDS_SEPARATOR);\r\n\r\n const result: ConnectionString = kvPairs.reduce((fields: ConnectionString, kv: string) => {\r\n const kvParts = kv.split(ConnectionStringParser._FIELD_KEY_VALUE_SEPARATOR);\r\n\r\n if (kvParts.length === 2) { // only save fields with valid formats\r\n const key = kvParts[0].toLowerCase() as ConnectionStringKey;\r\n const value = kvParts[1];\r\n fields[key] = value as string;\r\n }\r\n return fields;\r\n }, {});\r\n\r\n if (Object.keys(result).length > 0) {\r\n // this is a valid connection string, so parse the results\r\n\r\n if (result.endpointsuffix) {\r\n // use endpoint suffix where overrides are not provided\r\n const locationPrefix = result.location ? result.location + \".\" : \"\";\r\n result.ingestionendpoint = result.ingestionendpoint || (\"https://\" + locationPrefix + \"dc.\" + result.endpointsuffix);\r\n result.liveendpoint = result.liveendpoint || (\"https://\" + locationPrefix + \"live.\" + result.endpointsuffix);\r\n }\r\n\r\n // apply the default endpoints\r\n result.ingestionendpoint = result.ingestionendpoint || Constants.DEFAULT_BREEZE_ENDPOINT;\r\n result.liveendpoint = result.liveendpoint || Constants.DEFAULT_LIVEMETRICS_ENDPOINT;\r\n }\r\n\r\n return result;\r\n }\r\n\r\n public static isIkeyValid(iKey: string): boolean {\r\n if (!iKey || iKey == \"\") return false;\r\n const UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\r\n const regexp = new RegExp(UUID_Regex);\r\n return regexp.test(iKey);\r\n }\r\n}\r\n\r\nexport = ConnectionStringParser;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Context.d.ts b/node_modules/applicationinsights/out/Library/Context.d.ts new file mode 100644 index 0000000..a1231bc --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Context.d.ts @@ -0,0 +1,17 @@ +import Contracts = require("../Declarations/Contracts"); +declare class Context { + keys: Contracts.ContextTagKeys; + tags: { + [key: string]: string; + }; + static DefaultRoleName: string; + static appVersion: { + [path: string]: string; + }; + static sdkVersion: string; + constructor(packageJsonPath?: string); + private _loadApplicationContext; + private _loadDeviceContext; + private _loadInternalContext; +} +export = Context; diff --git a/node_modules/applicationinsights/out/Library/Context.js b/node_modules/applicationinsights/out/Library/Context.js new file mode 100644 index 0000000..89b0b57 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Context.js @@ -0,0 +1,52 @@ +"use strict"; +var os = require("os"); +var fs = require("fs"); +var path = require("path"); +var Contracts = require("../Declarations/Contracts"); +var Constants_1 = require("../Declarations/Constants"); +var Logging = require("./Logging"); +var Context = /** @class */ (function () { + function Context(packageJsonPath) { + this.keys = new Contracts.ContextTagKeys(); + this.tags = {}; + this._loadApplicationContext(packageJsonPath); + this._loadDeviceContext(); + this._loadInternalContext(); + } + Context.prototype._loadApplicationContext = function (packageJsonPath) { + // note: this should return the host package.json + packageJsonPath = packageJsonPath || path.resolve(__dirname, "../../../../package.json"); + if (!Context.appVersion[packageJsonPath]) { + Context.appVersion[packageJsonPath] = "unknown"; + try { + var packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")); + if (packageJson && typeof packageJson.version === "string") { + Context.appVersion[packageJsonPath] = packageJson.version; + } + } + catch (exception) { + Logging.info("unable to read app version: ", exception); + } + } + this.tags[this.keys.applicationVersion] = Context.appVersion[packageJsonPath]; + }; + Context.prototype._loadDeviceContext = function () { + this.tags[this.keys.deviceId] = ""; + this.tags[this.keys.cloudRoleInstance] = os && os.hostname(); + this.tags[this.keys.deviceOSVersion] = os && (os.type() + " " + os.release()); + this.tags[this.keys.cloudRole] = Context.DefaultRoleName; + // not yet supported tags + this.tags["ai.device.osArchitecture"] = os && os.arch(); + this.tags["ai.device.osPlatform"] = os && os.platform(); + }; + Context.prototype._loadInternalContext = function () { + Context.sdkVersion = Constants_1.APPLICATION_INSIGHTS_SDK_VERSION; + this.tags[this.keys.internalSdkVersion] = "node:" + Context.sdkVersion; + }; + Context.DefaultRoleName = "Web"; + Context.appVersion = {}; + Context.sdkVersion = null; + return Context; +}()); +module.exports = Context; +//# sourceMappingURL=Context.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Context.js.map b/node_modules/applicationinsights/out/Library/Context.js.map new file mode 100644 index 0000000..3b9eca3 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Context.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Context.js","sourceRoot":"","sources":["../../Library/Context.ts"],"names":[],"mappings":";AAAA,uBAA0B;AAC1B,uBAA0B;AAC1B,2BAA8B;AAE9B,qDAAwD;AACxD,uDAA6E;AAC7E,mCAAsC;AAEtC;IAQI,iBAAY,eAAwB;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,SAAS,CAAC,cAAc,EAAE,CAAC;QAC3C,IAAI,CAAC,IAAI,GAA8B,EAAE,CAAC;QAE1C,IAAI,CAAC,uBAAuB,CAAC,eAAe,CAAC,CAAC;QAC9C,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAC1B,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAChC,CAAC;IAEO,yCAAuB,GAA/B,UAAgC,eAAwB;QACpD,iDAAiD;QACjD,eAAe,GAAG,eAAe,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,0BAA0B,CAAC,CAAC;QAEzF,IAAI,CA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I,CAAC,sBAAsB,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,QAAQ,EAAE,CAAC;IAC5D,CAAC;IAEO,sCAAoB,GAA5B;QACI,OAAO,CAAC,UAAU,GAAG,4CAAgC,CAAC;QACtD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC;IAC3E,CAAC;IA9Ca,uBAAe,GAAW,KAAK,CAAC;IAChC,kBAAU,GAA+B,EAAE,CAAC;IAC5C,kBAAU,GAAW,IAAI,CAAC;IA6C5C,cAAC;CAAA,AAnDD,IAmDC;AAED,iBAAS,OAAO,CAAC","sourcesContent":["import os = require(\"os\");\r\nimport fs = require(\"fs\");\r\nimport path = require(\"path\");\r\n\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport { APPLICATION_INSIGHTS_SDK_VERSION } from \"../Declarations/Constants\";\r\nimport Logging = require(\"./Logging\");\r\n\r\nclass Context {\r\n\r\n public keys: Contracts.ContextTagKeys;\r\n public tags: { [key: string]: string };\r\n public static DefaultRoleName: string = \"Web\";\r\n public static appVersion: { [path: string]: string } = {};\r\n public static sdkVersion: string = null;\r\n\r\n constructor(packageJsonPath?: string) {\r\n this.keys = new Contracts.ContextTagKeys();\r\n this.tags = <{ [key: string]: string }>{};\r\n\r\n this._loadApplicationContext(packageJsonPath);\r\n this._loadDeviceContext();\r\n this._loadInternalContext();\r\n }\r\n\r\n private _loadApplicationContext(packageJsonPath?: string) {\r\n // note: this should return the host package.json\r\n packageJsonPath = packageJsonPath || path.resolve(__dirname, \"../../../../package.json\");\r\n\r\n if (!Context.appVersion[packageJsonPath]) {\r\n Context.appVersion[packageJsonPath] = \"unknown\";\r\n try {\r\n let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\r\n if (packageJson && typeof packageJson.version === \"string\") {\r\n Context.appVersion[packageJsonPath] = packageJson.version;\r\n }\r\n } catch (exception) {\r\n Logging.info(\"unable to read app version: \", exception);\r\n }\r\n }\r\n\r\n this.tags[this.keys.applicationVersion] = Context.appVersion[packageJsonPath];\r\n }\r\n\r\n private _loadDeviceContext() {\r\n this.tags[this.keys.deviceId] = \"\";\r\n this.tags[this.keys.cloudRoleInstance] = os && os.hostname();\r\n this.tags[this.keys.deviceOSVersion] = os && (os.type() + \" \" + os.release());\r\n this.tags[this.keys.cloudRole] = Context.DefaultRoleName;\r\n\r\n // not yet supported tags\r\n this.tags[\"ai.device.osArchitecture\"] = os && os.arch();\r\n this.tags[\"ai.device.osPlatform\"] = os && os.platform();\r\n }\r\n\r\n private _loadInternalContext() {\r\n Context.sdkVersion = APPLICATION_INSIGHTS_SDK_VERSION;\r\n this.tags[this.keys.internalSdkVersion] = \"node:\" + Context.sdkVersion;\r\n }\r\n}\r\n\r\nexport = Context;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/CorrelationIdManager.d.ts b/node_modules/applicationinsights/out/Library/CorrelationIdManager.d.ts new file mode 100644 index 0000000..9656500 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/CorrelationIdManager.d.ts @@ -0,0 +1,24 @@ +import Config = require("./Config"); +declare class CorrelationIdManager { + static correlationIdPrefix: string; + static w3cEnabled: boolean; + static HTTP_TIMEOUT: number; + private static requestIdMaxLength; + private static currentRootId; + static queryCorrelationId(config: Config, callback: (correlationId: string) => void): void; + static cancelCorrelationIdQuery(config: Config, callback: (correlationId: string) => void): void; + /** + * Generate a request Id according to https://github.com/lmolkova/correlation/blob/master/hierarchical_request_id.md + * @param parentId + */ + static generateRequestId(parentId: string): string; + /** + * Given a hierarchical identifier of the form |X.* + * return the root identifier X + * @param id + */ + static getRootId(id: string): string; + private static generateRootId; + private static appendSuffix; +} +export = CorrelationIdManager; diff --git a/node_modules/applicationinsights/out/Library/CorrelationIdManager.js b/node_modules/applicationinsights/out/Library/CorrelationIdManager.js new file mode 100644 index 0000000..64fc47a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/CorrelationIdManager.js @@ -0,0 +1,79 @@ +"use strict"; +var Util = require("./Util"); +var CorrelationIdManager = /** @class */ (function () { + function CorrelationIdManager() { + } + CorrelationIdManager.queryCorrelationId = function (config, callback) { + // No Op, App ID Exchange not required in SDK anymore + }; + CorrelationIdManager.cancelCorrelationIdQuery = function (config, callback) { + // No Op, App ID Exchange not required in SDK anymore + }; + /** + * Generate a request Id according to https://github.com/lmolkova/correlation/blob/master/hierarchical_request_id.md + * @param parentId + */ + CorrelationIdManager.generateRequestId = function (parentId) { + if (parentId) { + parentId = parentId[0] == "|" ? parentId : "|" + parentId; + if (parentId[parentId.length - 1] !== ".") { + parentId += "."; + } + var suffix = (CorrelationIdManager.currentRootId++).toString(16); + return CorrelationIdManager.appendSuffix(parentId, suffix, "_"); + } + else { + return CorrelationIdManager.generateRootId(); + } + }; + /** + * Given a hierarchical identifier of the form |X.* + * return the root identifier X + * @param id + */ + CorrelationIdManager.getRootId = function (id) { + var endIndex = id.indexOf("."); + if (endIndex < 0) { + endIndex = id.length; + } + var startIndex = id[0] === "|" ? 1 : 0; + return id.substring(startIndex, endIndex); + }; + CorrelationIdManager.generateRootId = function () { + return "|" + Util.w3cTraceId() + "."; + }; + CorrelationIdManager.appendSuffix = function (parentId, suffix, delimiter) { + if (parentId.length + suffix.length < CorrelationIdManager.requestIdMaxLength) { + return parentId + suffix + delimiter; + } + // Combined identifier would be too long, so we must truncate it. + // We need 9 characters of space: 8 for the overflow ID, 1 for the + // overflow delimiter '#' + var trimPosition = CorrelationIdManager.requestIdMaxLength - 9; + if (parentId.length > trimPosition) { + for (; trimPosition > 1; --trimPosition) { + var c = parentId[trimPosition - 1]; + if (c === "." || c === "_") { + break; + } + } + } + if (trimPosition <= 1) { + // parentId is not a valid ID + return CorrelationIdManager.generateRootId(); + } + suffix = Util.randomu32().toString(16); + while (suffix.length < 8) { + suffix = "0" + suffix; + } + return parentId.substring(0, trimPosition) + suffix + "#"; + }; + CorrelationIdManager.correlationIdPrefix = "cid-v1:"; + CorrelationIdManager.w3cEnabled = true; + CorrelationIdManager.HTTP_TIMEOUT = 2500; // 2.5 seconds + CorrelationIdManager.requestIdMaxLength = 1024; + CorrelationIdManager.currentRootId = Util.randomu32(); + return CorrelationIdManager; +}()); +module.exports = CorrelationIdManager; +//# sourceMappingURL=CorrelationIdManager.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/CorrelationIdManager.js.map b/node_modules/applicationinsights/out/Library/CorrelationIdManager.js.map new file mode 100644 index 0000000..9a1b7a8 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/CorrelationIdManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"CorrelationIdManager.js","sourceRoot":"","sources":["../../Library/CorrelationIdManager.ts"],"names":[],"mappings":";AAAA,6BAAgC;AAGhC;IAAA;IAoFA,CAAC;IA3EiB,uCAAkB,GAAhC,UAAiC,MAAc,EAAE,QAAyC;QACtF,qDAAqD;IACzD,CAAC;IAEa,6CAAwB,GAAtC,UAAuC,MAAc,EAAE,QAAyC;QAC5F,qDAAqD;IACzD,CAAC;IAED;;;OAGG;IACW,sCAAiB,GAA/B,UAAgC,QAAgB;QAC5C,IAAI,QAAQ,EAAE;YACV,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,GAAG,QAAQ,CAAC;YAC1D,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;gBACvC,QAAQ,IAAI,GAAG,CAAC;aACnB;YAED,IAAM,MAAM,GAAG,CAAC,oBAAoB,CAAC,aAAa,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YAEnE,OAAO,oBAAoB,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,CAAA;SAClE;aAAM;YACH,OAAO,oBAAoB,CAAC,cAAc,EAAE,CA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AAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;YACtB,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC;SACzB;QACD,OAAO,QAAQ,CAAC,SAAS,CAAC,CAAC,EAAE,YAAY,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC;IAC9D,CAAC;IAlFa,wCAAmB,GAAG,SAAS,CAAC;IAChC,+BAAU,GAAG,IAAI,CAAC;IAClB,iCAAY,GAAW,IAAI,CAAC,CAAC,cAAc;IAG1C,uCAAkB,GAAG,IAAI,CAAC;IAC1B,kCAAa,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IA6EpD,2BAAC;CAAA,AApFD,IAoFC;AAED,iBAAS,oBAAoB,CAAC","sourcesContent":["import Util = require(\"./Util\");\r\nimport Config = require(\"./Config\");\r\n\r\nclass CorrelationIdManager {\r\n public static correlationIdPrefix = \"cid-v1:\";\r\n public static w3cEnabled = true;\r\n public static HTTP_TIMEOUT: number = 2500; // 2.5 seconds\r\n\r\n\r\n private static requestIdMaxLength = 1024;\r\n private static currentRootId = Util.randomu32();\r\n\r\n public static queryCorrelationId(config: Config, callback: (correlationId: string) => void) {\r\n // No Op, App ID Exchange not required in SDK anymore\r\n }\r\n\r\n public static cancelCorrelationIdQuery(config: Config, callback: (correlationId: string) => void) {\r\n // No Op, App ID Exchange not required in SDK anymore\r\n }\r\n\r\n /**\r\n * Generate a request Id according to https://github.com/lmolkova/correlation/blob/master/hierarchical_request_id.md\r\n * @param parentId\r\n */\r\n public static generateRequestId(parentId: string): string {\r\n if (parentId) {\r\n parentId = parentId[0] == \"|\" ? parentId : \"|\" + parentId;\r\n if (parentId[parentId.length - 1] !== \".\") {\r\n parentId += \".\";\r\n }\r\n\r\n const suffix = (CorrelationIdManager.currentRootId++).toString(16);\r\n\r\n return CorrelationIdManager.appendSuffix(parentId, suffix, \"_\")\r\n } else {\r\n return CorrelationIdManager.generateRootId();\r\n }\r\n }\r\n\r\n /**\r\n * Given a hierarchical identifier of the form |X.*\r\n * return the root identifier X\r\n * @param id\r\n */\r\n public static getRootId(id: string): string {\r\n let endIndex = id.indexOf(\".\");\r\n if (endIndex < 0) {\r\n endIndex = id.length;\r\n }\r\n\r\n const startIndex = id[0] === \"|\" ? 1 : 0;\r\n return id.substring(startIndex, endIndex);\r\n }\r\n\r\n private static generateRootId(): string {\r\n return \"|\" + Util.w3cTraceId() + \".\";\r\n }\r\n\r\n private static appendSuffix(parentId: string, suffix: string, delimiter: string): string {\r\n if (parentId.length + suffix.length < CorrelationIdManager.requestIdMaxLength) {\r\n return parentId + suffix + delimiter;\r\n }\r\n\r\n // Combined identifier would be too long, so we must truncate it.\r\n // We need 9 characters of space: 8 for the overflow ID, 1 for the\r\n // overflow delimiter '#'\r\n let trimPosition = CorrelationIdManager.requestIdMaxLength - 9;\r\n if (parentId.length > trimPosition) {\r\n for (; trimPosition > 1; --trimPosition) {\r\n const c = parentId[trimPosition - 1];\r\n if (c === \".\" || c === \"_\") {\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (trimPosition <= 1) {\r\n // parentId is not a valid ID\r\n return CorrelationIdManager.generateRootId();\r\n }\r\n\r\n suffix = Util.randomu32().toString(16);\r\n while (suffix.length < 8) {\r\n suffix = \"0\" + suffix;\r\n }\r\n return parentId.substring(0, trimPosition) + suffix + \"#\";\r\n }\r\n}\r\n\r\nexport = CorrelationIdManager;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/EnvelopeFactory.d.ts b/node_modules/applicationinsights/out/Library/EnvelopeFactory.d.ts new file mode 100644 index 0000000..6cda6e8 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/EnvelopeFactory.d.ts @@ -0,0 +1,31 @@ +import Contracts = require("../Declarations/Contracts"); +import Config = require("./Config"); +import Context = require("./Context"); +/** + * Manages the logic of creating envelopes from Telemetry objects + */ +declare class EnvelopeFactory { + /** + * Creates envelope ready to be sent by Channel + * @param telemetry Telemetry data + * @param telemetryType Type of telemetry + * @param commonProperties Bag of custom common properties to be added to the envelope + * @param context Client context + * @param config Client configuration + */ + static createEnvelope(telemetry: Contracts.Telemetry, telemetryType: Contracts.TelemetryType, commonProperties?: { + [key: string]: string; + }, context?: Context, config?: Config): Contracts.Envelope; + private static addAzureFunctionsCorrelationProperties; + private static createTraceData; + private static createDependencyData; + private static createEventData; + private static createExceptionData; + private static createRequestData; + private static createMetricData; + private static createAvailabilityData; + private static createPageViewData; + private static getTags; + private static parseStack; +} +export = EnvelopeFactory; diff --git a/node_modules/applicationinsights/out/Library/EnvelopeFactory.js b/node_modules/applicationinsights/out/Library/EnvelopeFactory.js new file mode 100644 index 0000000..e4d46bf --- /dev/null +++ b/node_modules/applicationinsights/out/Library/EnvelopeFactory.js @@ -0,0 +1,361 @@ +"use strict"; +var Contracts = require("../Declarations/Contracts"); +var Util = require("./Util"); +var CorrelationContextManager_1 = require("../AutoCollection/CorrelationContextManager"); +/** + * Manages the logic of creating envelopes from Telemetry objects + */ +var EnvelopeFactory = /** @class */ (function () { + function EnvelopeFactory() { + } + /** + * Creates envelope ready to be sent by Channel + * @param telemetry Telemetry data + * @param telemetryType Type of telemetry + * @param commonProperties Bag of custom common properties to be added to the envelope + * @param context Client context + * @param config Client configuration + */ + EnvelopeFactory.createEnvelope = function (telemetry, telemetryType, commonProperties, context, config) { + var data = null; + switch (telemetryType) { + case Contracts.TelemetryType.Trace: + data = EnvelopeFactory.createTraceData(telemetry); + break; + case Contracts.TelemetryType.Dependency: + data = EnvelopeFactory.createDependencyData(telemetry); + break; + case Contracts.TelemetryType.Event: + data = EnvelopeFactory.createEventData(telemetry); + break; + case Contracts.TelemetryType.Exception: + data = EnvelopeFactory.createExceptionData(telemetry); + break; + case Contracts.TelemetryType.Request: + data = EnvelopeFactory.createRequestData(telemetry); + break; + case Contracts.TelemetryType.Metric: + data = EnvelopeFactory.createMetricData(telemetry); + break; + case Contracts.TelemetryType.Availability: + data = EnvelopeFactory.createAvailabilityData(telemetry); + break; + case Contracts.TelemetryType.PageView: + data = EnvelopeFactory.createPageViewData(telemetry); + break; + } + if (data && data.baseData) { + if (Contracts.domainSupportsProperties(data.baseData)) { // Do instanceof check. TS will automatically cast and allow the properties property + if (commonProperties) { + // if no properties are specified just add the common ones + if (!data.baseData.properties) { + data.baseData.properties = commonProperties; + } + else { + // otherwise, check each of the common ones + for (var name in commonProperties) { + // only override if the property `name` has not been set on this item + if (!data.baseData.properties[name]) { + data.baseData.properties[name] = commonProperties[name]; + } + } + } + } + EnvelopeFactory.addAzureFunctionsCorrelationProperties(data.baseData.properties); + if (data.baseData.properties) { + // sanitize properties + data.baseData.properties = Util.validateStringMap(data.baseData.properties); + } + } + } + var iKey = config ? config.instrumentationKey || "" : ""; + var envelope = new Contracts.Envelope(); + envelope.data = data; + envelope.iKey = iKey; + // this is kind of a hack, but the envelope name is always the same as the data name sans the chars "data" + envelope.name = + "Microsoft.ApplicationInsights." + + iKey.replace(/-/g, "") + + "." + + data.baseType.substr(0, data.baseType.length - 4); + envelope.tags = this.getTags(context, telemetry.tagOverrides); + envelope.time = (new Date()).toISOString(); + envelope.ver = 1; + envelope.sampleRate = config ? config.samplingPercentage : 100; + // Exclude metrics from sampling by default + if (telemetryType === Contracts.TelemetryType.Metric) { + envelope.sampleRate = 100; + } + return envelope; + }; + EnvelopeFactory.addAzureFunctionsCorrelationProperties = function (properties) { + var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + if (correlationContext && correlationContext.customProperties && correlationContext.customProperties["getProperty"] instanceof Function) { + properties = properties || {}; // Initialize properties if not present + var property = correlationContext.customProperties.getProperty("InvocationId"); + if (property) { + properties["InvocationId"] = property; + } + property = correlationContext.customProperties.getProperty("ProcessId"); + if (property) { + properties["ProcessId"] = property; + } + property = correlationContext.customProperties.getProperty("LogLevel"); + if (property) { + properties["LogLevel"] = property; + } + property = correlationContext.customProperties.getProperty("Category"); + if (property) { + properties["Category"] = property; + } + property = correlationContext.customProperties.getProperty("HostInstanceId"); + if (property) { + properties["HostInstanceId"] = property; + } + property = correlationContext.customProperties.getProperty("AzFuncLiveLogsSessionId"); + if (property) { + properties["AzFuncLiveLogsSessionId"] = property; + } + } + }; + EnvelopeFactory.createTraceData = function (telemetry) { + var trace = new Contracts.MessageData(); + trace.message = telemetry.message; + trace.properties = telemetry.properties; + if (!isNaN(telemetry.severity)) { + trace.severityLevel = telemetry.severity; + } + else { + trace.severityLevel = Contracts.SeverityLevel.Information; + } + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Trace); + data.baseData = trace; + return data; + }; + EnvelopeFactory.createDependencyData = function (telemetry) { + var remoteDependency = new Contracts.RemoteDependencyData(); + if (typeof telemetry.name === "string") { + remoteDependency.name = telemetry.name.length > 1024 ? telemetry.name.slice(0, 1021) + "..." : telemetry.name; + } + remoteDependency.data = telemetry.data; + remoteDependency.target = telemetry.target; + remoteDependency.duration = Util.msToTimeSpan(telemetry.duration); + remoteDependency.success = telemetry.success; + remoteDependency.type = telemetry.dependencyTypeName; + remoteDependency.properties = telemetry.properties; + remoteDependency.resultCode = (telemetry.resultCode ? telemetry.resultCode.toString() : "0"); + if (telemetry.id) { + remoteDependency.id = telemetry.id; + } + else { + remoteDependency.id = Util.w3cTraceId(); + } + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Dependency); + data.baseData = remoteDependency; + return data; + }; + EnvelopeFactory.createEventData = function (telemetry) { + var event = new Contracts.EventData(); + event.name = telemetry.name; + event.properties = telemetry.properties; + event.measurements = telemetry.measurements; + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Event); + data.baseData = event; + return data; + }; + EnvelopeFactory.createExceptionData = function (telemetry) { + var exception = new Contracts.ExceptionData(); + exception.properties = telemetry.properties; + if (!isNaN(telemetry.severity)) { + exception.severityLevel = telemetry.severity; + } + else { + exception.severityLevel = Contracts.SeverityLevel.Error; + } + exception.measurements = telemetry.measurements; + exception.exceptions = []; + var stack = telemetry.exception["stack"]; + var exceptionDetails = new Contracts.ExceptionDetails(); + exceptionDetails.message = telemetry.exception.message; + exceptionDetails.typeName = telemetry.exception.name; + exceptionDetails.parsedStack = this.parseStack(stack); + exceptionDetails.hasFullStack = Util.isArray(exceptionDetails.parsedStack) && exceptionDetails.parsedStack.length > 0; + exception.exceptions.push(exceptionDetails); + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Exception); + data.baseData = exception; + return data; + }; + EnvelopeFactory.createRequestData = function (telemetry) { + var requestData = new Contracts.RequestData(); + if (telemetry.id) { + requestData.id = telemetry.id; + } + else { + requestData.id = Util.w3cTraceId(); + } + requestData.name = telemetry.name; + requestData.url = telemetry.url; + requestData.source = telemetry.source; + requestData.duration = Util.msToTimeSpan(telemetry.duration); + requestData.responseCode = (telemetry.resultCode ? telemetry.resultCode.toString() : "0"); + requestData.success = telemetry.success; + requestData.properties = telemetry.properties; + requestData.measurements = telemetry.measurements; + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Request); + data.baseData = requestData; + return data; + }; + EnvelopeFactory.createMetricData = function (telemetry) { + var metrics = new Contracts.MetricData(); // todo: enable client-batching of these + metrics.metrics = []; + var metric = new Contracts.DataPoint(); + metric.count = !isNaN(telemetry.count) ? telemetry.count : 1; + metric.kind = Contracts.DataPointType.Aggregation; + metric.max = !isNaN(telemetry.max) ? telemetry.max : telemetry.value; + metric.min = !isNaN(telemetry.min) ? telemetry.min : telemetry.value; + metric.name = telemetry.name; + metric.stdDev = !isNaN(telemetry.stdDev) ? telemetry.stdDev : 0; + metric.value = telemetry.value; + metric.ns = telemetry.namespace; + metrics.metrics.push(metric); + metrics.properties = telemetry.properties; + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Metric); + data.baseData = metrics; + return data; + }; + EnvelopeFactory.createAvailabilityData = function (telemetry) { + var availabilityData = new Contracts.AvailabilityData(); + if (telemetry.id) { + availabilityData.id = telemetry.id; + } + else { + availabilityData.id = Util.w3cTraceId(); + } + availabilityData.name = telemetry.name; + availabilityData.duration = Util.msToTimeSpan(telemetry.duration); + availabilityData.success = telemetry.success; + availabilityData.runLocation = telemetry.runLocation; + availabilityData.message = telemetry.message; + availabilityData.measurements = telemetry.measurements; + availabilityData.properties = telemetry.properties; + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Availability); + data.baseData = availabilityData; + return data; + }; + EnvelopeFactory.createPageViewData = function (telemetry) { + var pageViewData = new Contracts.PageViewData(); + pageViewData.name = telemetry.name; + pageViewData.duration = Util.msToTimeSpan(telemetry.duration); + pageViewData.url = telemetry.url; + pageViewData.measurements = telemetry.measurements; + pageViewData.properties = telemetry.properties; + var data = new Contracts.Data(); + data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.PageView); + data.baseData = pageViewData; + return data; + }; + EnvelopeFactory.getTags = function (context, tagOverrides) { + var correlationContext = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + // Make a copy of context tags so we don't alter the actual object + // Also perform tag overriding + var newTags = {}; + if (context && context.tags) { + for (var key in context.tags) { + newTags[key] = context.tags[key]; + } + } + if (tagOverrides) { + for (var key in tagOverrides) { + newTags[key] = tagOverrides[key]; + } + } + // Fill in internally-populated values if not already set + if (correlationContext) { + newTags[context.keys.operationId] = newTags[context.keys.operationId] || correlationContext.operation.id; + newTags[context.keys.operationName] = newTags[context.keys.operationName] || correlationContext.operation.name; + newTags[context.keys.operationParentId] = newTags[context.keys.operationParentId] || correlationContext.operation.parentId; + } + return newTags; + }; + EnvelopeFactory.parseStack = function (stack) { + var parsedStack = undefined; + if (typeof stack === "string") { + var frames = stack.split("\n"); + parsedStack = []; + var level = 0; + var totalSizeInBytes = 0; + for (var i = 0; i <= frames.length; i++) { + var frame = frames[i]; + if (_StackFrame.regex.test(frame)) { + var parsedFrame = new _StackFrame(frames[i], level++); + totalSizeInBytes += parsedFrame.sizeInBytes; + parsedStack.push(parsedFrame); + } + } + // DP Constraint - exception parsed stack must be < 32KB + // remove frames from the middle to meet the threshold + var exceptionParsedStackThreshold = 32 * 1024; + if (totalSizeInBytes > exceptionParsedStackThreshold) { + var left = 0; + var right = parsedStack.length - 1; + var size = 0; + var acceptedLeft = left; + var acceptedRight = right; + while (left < right) { + // check size + var lSize = parsedStack[left].sizeInBytes; + var rSize = parsedStack[right].sizeInBytes; + size += lSize + rSize; + if (size > exceptionParsedStackThreshold) { + // remove extra frames from the middle + var howMany = acceptedRight - acceptedLeft + 1; + parsedStack.splice(acceptedLeft, howMany); + break; + } + // update pointers + acceptedLeft = left; + acceptedRight = right; + left++; + right--; + } + } + } + return parsedStack; + }; + return EnvelopeFactory; +}()); +var _StackFrame = /** @class */ (function () { + function _StackFrame(frame, level) { + this.sizeInBytes = 0; + this.level = level; + this.method = ""; + this.assembly = Util.trim(frame); + var matches = frame.match(_StackFrame.regex); + if (matches && matches.length >= 5) { + this.method = Util.trim(matches[2]) || this.method; + this.fileName = Util.trim(matches[4]) || ""; + this.line = parseInt(matches[5]) || 0; + } + this.sizeInBytes += this.method.length; + this.sizeInBytes += this.fileName.length; + this.sizeInBytes += this.assembly.length; + // todo: these might need to be removed depending on how the back-end settles on their size calculation + this.sizeInBytes += _StackFrame.baseSize; + this.sizeInBytes += this.level.toString().length; + this.sizeInBytes += this.line.toString().length; + } + // regex to match stack frames from ie/chrome/ff + // methodName=$2, fileName=$4, lineNo=$5, column=$6 + _StackFrame.regex = /^(\s+at)?(.*?)(\@|\s\(|\s)([^\(\n]+):(\d+):(\d+)(\)?)$/; + _StackFrame.baseSize = 58; //'{"method":"","level":,"assembly":"","fileName":"","line":}'.length + return _StackFrame; +}()); +module.exports = EnvelopeFactory; +//# sourceMappingURL=EnvelopeFactory.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/EnvelopeFactory.js.map b/node_modules/applicationinsights/out/Library/EnvelopeFactory.js.map new file mode 100644 index 0000000..06b70cf --- /dev/null +++ b/node_modules/applicationinsights/out/Library/EnvelopeFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"EnvelopeFactory.js","sourceRoot":"","sources":["../../Library/EnvelopeFactory.ts"],"names":[],"mappings":";AAAA,qDAAuD;AACvD,6BAA+B;AAG/B,yFAAwF;AAGxF;;GAEG;AACH;IAAA;IA2XA,CAAC;IAxXG;;;;;;;OAOG;IACW,8BAAc,GAA5B,UACI,SAA8B,EAC9B,aAAsC,EACtC,gBAA6C,EAC7C,OAAiB,EACjB,MAAe;QAEf,IAAI,IAAI,GAAG,IAAI,CAAC;QAGhB,QAAQ,aAAa,EAAE;YACnB,KAAK,SAAS,CAAC,aAAa,CAAC,KAAK;gBAC9B,IAAI,GAAG,eAAe,CAAC,eAAe,CAA2B,SAAS,CAAC,CAAC;gBAC5E,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC,UAAU;gBACnC,IAAI,GAAG,eAAe,CAAC,oBAAoB,CAAgC,SAAS,CAAC,CAAC;gBACtF,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC,KAAK;gBAC9B,IAAI,GAAG,eAAe,CAAC,eAAe,CAA2B,SAAS,CAAC,CAAC;gBAC5E,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC,SAAS;gBAClC,IAAI,GAAG,eAAe,CAAC,mBAAmB,CAA+B,SAAS,CAAC,CAAC;gBACpF,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC,OAAO;gBAChC,IAAI,GAAG,eAAe,CAAC,iBAAiB,CAA6B,SAAS,CAAC,CAAC;gBAChF,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC,MAAM;gBAC/B,IAAI,GAAG,eAAe,CAAC,gBAAgB,CAA4B,SAAS,CAAC,CAAC;gBAC9E,MAAM;YACV,KAAK,SAAS,CAAC,aAAa,CAAC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CAAC,WAAW,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;QACjD,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC;IACpD,CAAC;IA9BD,gDAAgD;IAChD,mDAAmD;IACrC,iBAAK,GAAG,wDAAwD,CAAC;IACjE,oBAAQ,GAAG,EAAE,CAAC,CAAC,qEAAqE;IA4BtG,kBAAC;CAAA,AAjCD,IAiCC;AAED,iBAAS,eAAe,CAAC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\")\r\nimport Util = require(\"./Util\")\r\nimport Config = require(\"./Config\");\r\nimport Context = require(\"./Context\");\r\nimport { CorrelationContextManager } from \"../AutoCollection/CorrelationContextManager\";\r\n\r\n\r\n/**\r\n * Manages the logic of creating envelopes from Telemetry objects\r\n */\r\nclass EnvelopeFactory {\r\n\r\n\r\n /**\r\n * Creates envelope ready to be sent by Channel\r\n * @param telemetry Telemetry data\r\n * @param telemetryType Type of telemetry\r\n * @param commonProperties Bag of custom common properties to be added to the envelope\r\n * @param context Client context\r\n * @param config Client configuration\r\n */\r\n public static createEnvelope(\r\n telemetry: Contracts.Telemetry,\r\n telemetryType: Contracts.TelemetryType,\r\n commonProperties?: { [key: string]: string; },\r\n context?: Context,\r\n config?: Config): Contracts.Envelope {\r\n\r\n var data = null;\r\n\r\n\r\n switch (telemetryType) {\r\n case Contracts.TelemetryType.Trace:\r\n data = EnvelopeFactory.createTraceData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Dependency:\r\n data = EnvelopeFactory.createDependencyData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Event:\r\n data = EnvelopeFactory.createEventData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Exception:\r\n data = EnvelopeFactory.createExceptionData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Request:\r\n data = EnvelopeFactory.createRequestData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Metric:\r\n data = EnvelopeFactory.createMetricData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.Availability:\r\n data = EnvelopeFactory.createAvailabilityData(telemetry);\r\n break;\r\n case Contracts.TelemetryType.PageView:\r\n data = EnvelopeFactory.createPageViewData(telemetry);\r\n break;\r\n }\r\n\r\n if (data && data.baseData) {\r\n if (Contracts.domainSupportsProperties(data.baseData)) { // Do instanceof check. TS will automatically cast and allow the properties property\r\n if (commonProperties) {\r\n // if no properties are specified just add the common ones\r\n if (!data.baseData.properties) {\r\n data.baseData.properties = commonProperties;\r\n } else {\r\n // otherwise, check each of the common ones\r\n for (var name in commonProperties) {\r\n // only override if the property `name` has not been set on this item\r\n if (!data.baseData.properties[name]) {\r\n data.baseData.properties[name] = commonProperties[name];\r\n }\r\n }\r\n }\r\n }\r\n EnvelopeFactory.addAzureFunctionsCorrelationProperties(data.baseData.properties);\r\n if (data.baseData.properties) {\r\n // sanitize properties\r\n data.baseData.properties = Util.validateStringMap(data.baseData.properties);\r\n }\r\n }\r\n }\r\n\r\n var iKey = config ? config.instrumentationKey || \"\" : \"\";\r\n var envelope = new Contracts.Envelope();\r\n envelope.data = data;\r\n envelope.iKey = iKey;\r\n\r\n // this is kind of a hack, but the envelope name is always the same as the data name sans the chars \"data\"\r\n envelope.name =\r\n \"Microsoft.ApplicationInsights.\" +\r\n iKey.replace(/-/g, \"\") +\r\n \".\" +\r\n data.baseType.substr(0, data.baseType.length - 4);\r\n envelope.tags = this.getTags(context, telemetry.tagOverrides);\r\n envelope.time = (new Date()).toISOString();\r\n envelope.ver = 1;\r\n envelope.sampleRate = config ? config.samplingPercentage : 100;\r\n\r\n // Exclude metrics from sampling by default\r\n if (telemetryType === Contracts.TelemetryType.Metric) {\r\n envelope.sampleRate = 100;\r\n }\r\n\r\n return envelope;\r\n }\r\n\r\n private static addAzureFunctionsCorrelationProperties(properties: { [key: string]: string; }) {\r\n var correlationContext = CorrelationContextManager.getCurrentContext();\r\n if (correlationContext && correlationContext.customProperties && correlationContext.customProperties[\"getProperty\"] instanceof Function) {\r\n properties = properties || {}; // Initialize properties if not present\r\n let property = correlationContext.customProperties.getProperty(\"InvocationId\");\r\n if (property) {\r\n properties[\"InvocationId\"] = property;\r\n }\r\n property = correlationContext.customProperties.getProperty(\"ProcessId\");\r\n if (property) {\r\n properties[\"ProcessId\"] = property;\r\n }\r\n property = correlationContext.customProperties.getProperty(\"LogLevel\");\r\n if (property) {\r\n properties[\"LogLevel\"] = property;\r\n }\r\n property = correlationContext.customProperties.getProperty(\"Category\");\r\n if (property) {\r\n properties[\"Category\"] = property;\r\n }\r\n property = correlationContext.customProperties.getProperty(\"HostInstanceId\");\r\n if (property) {\r\n properties[\"HostInstanceId\"] = property;\r\n }\r\n property = correlationContext.customProperties.getProperty(\"AzFuncLiveLogsSessionId\");\r\n if (property) {\r\n properties[\"AzFuncLiveLogsSessionId\"] = property;\r\n }\r\n }\r\n }\r\n\r\n private static createTraceData(telemetry: Contracts.TraceTelemetry): Contracts.Data {\r\n var trace = new Contracts.MessageData();\r\n trace.message = telemetry.message;\r\n trace.properties = telemetry.properties;\r\n if (!isNaN(telemetry.severity)) {\r\n trace.severityLevel = telemetry.severity;\r\n } else {\r\n trace.severityLevel = Contracts.SeverityLevel.Information;\r\n }\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Trace);\r\n data.baseData = trace;\r\n return data;\r\n }\r\n\r\n private static createDependencyData(telemetry: Contracts.DependencyTelemetry & Contracts.Identified): Contracts.Data {\r\n var remoteDependency = new Contracts.RemoteDependencyData();\r\n if (typeof telemetry.name === \"string\") {\r\n remoteDependency.name = telemetry.name.length > 1024 ? telemetry.name.slice(0, 1021) + \"...\" : telemetry.name;\r\n }\r\n remoteDependency.data = telemetry.data;\r\n remoteDependency.target = telemetry.target;\r\n remoteDependency.duration = Util.msToTimeSpan(telemetry.duration);\r\n remoteDependency.success = telemetry.success;\r\n remoteDependency.type = telemetry.dependencyTypeName;\r\n remoteDependency.properties = telemetry.properties;\r\n remoteDependency.resultCode = (telemetry.resultCode ? telemetry.resultCode.toString() : \"0\");\r\n\r\n if (telemetry.id) {\r\n remoteDependency.id = telemetry.id;\r\n }\r\n else {\r\n remoteDependency.id = Util.w3cTraceId();\r\n }\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Dependency);\r\n data.baseData = remoteDependency;\r\n return data;\r\n }\r\n\r\n private static createEventData(telemetry: Contracts.EventTelemetry): Contracts.Data {\r\n var event = new Contracts.EventData();\r\n event.name = telemetry.name;\r\n event.properties = telemetry.properties;\r\n event.measurements = telemetry.measurements;\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Event);\r\n data.baseData = event;\r\n return data;\r\n }\r\n\r\n private static createExceptionData(telemetry: Contracts.ExceptionTelemetry): Contracts.Data {\r\n var exception = new Contracts.ExceptionData();\r\n exception.properties = telemetry.properties;\r\n if (!isNaN(telemetry.severity)) {\r\n exception.severityLevel = telemetry.severity;\r\n } else {\r\n exception.severityLevel = Contracts.SeverityLevel.Error;\r\n }\r\n exception.measurements = telemetry.measurements;\r\n exception.exceptions = [];\r\n\r\n var stack = telemetry.exception[\"stack\"];\r\n var exceptionDetails = new Contracts.ExceptionDetails();\r\n exceptionDetails.message = telemetry.exception.message;\r\n exceptionDetails.typeName = telemetry.exception.name;\r\n exceptionDetails.parsedStack = this.parseStack(stack);\r\n exceptionDetails.hasFullStack = Util.isArray(exceptionDetails.parsedStack) && exceptionDetails.parsedStack.length > 0;\r\n exception.exceptions.push(exceptionDetails);\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Exception);\r\n data.baseData = exception;\r\n return data;\r\n }\r\n\r\n private static createRequestData(telemetry: Contracts.RequestTelemetry & Contracts.Identified): Contracts.Data {\r\n var requestData = new Contracts.RequestData();\r\n if (telemetry.id) {\r\n requestData.id = telemetry.id;\r\n }\r\n else {\r\n requestData.id = Util.w3cTraceId();\r\n }\r\n requestData.name = telemetry.name;\r\n requestData.url = telemetry.url;\r\n requestData.source = telemetry.source;\r\n requestData.duration = Util.msToTimeSpan(telemetry.duration);\r\n requestData.responseCode = (telemetry.resultCode ? telemetry.resultCode.toString() : \"0\");\r\n requestData.success = telemetry.success\r\n requestData.properties = telemetry.properties;\r\n requestData.measurements = telemetry.measurements;\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Request);\r\n data.baseData = requestData;\r\n return data;\r\n }\r\n\r\n private static createMetricData(telemetry: Contracts.MetricTelemetry): Contracts.Data {\r\n var metrics = new Contracts.MetricData(); // todo: enable client-batching of these\r\n metrics.metrics = [];\r\n\r\n var metric = new Contracts.DataPoint();\r\n metric.count = !isNaN(telemetry.count) ? telemetry.count : 1;\r\n metric.kind = Contracts.DataPointType.Aggregation;\r\n metric.max = !isNaN(telemetry.max) ? telemetry.max : telemetry.value;\r\n metric.min = !isNaN(telemetry.min) ? telemetry.min : telemetry.value;\r\n metric.name = telemetry.name;\r\n metric.stdDev = !isNaN(telemetry.stdDev) ? telemetry.stdDev : 0;\r\n metric.value = telemetry.value;\r\n metric.ns = telemetry.namespace;\r\n\r\n metrics.metrics.push(metric);\r\n\r\n metrics.properties = telemetry.properties;\r\n\r\n var data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Metric);\r\n data.baseData = metrics;\r\n return data;\r\n }\r\n\r\n private static createAvailabilityData(\r\n telemetry: Contracts.AvailabilityTelemetry & Contracts.Identified\r\n ): Contracts.Data {\r\n let availabilityData = new Contracts.AvailabilityData();\r\n\r\n if (telemetry.id) {\r\n availabilityData.id = telemetry.id;\r\n } else {\r\n availabilityData.id = Util.w3cTraceId();\r\n }\r\n availabilityData.name = telemetry.name;\r\n availabilityData.duration = Util.msToTimeSpan(telemetry.duration);\r\n availabilityData.success = telemetry.success;\r\n availabilityData.runLocation = telemetry.runLocation;\r\n availabilityData.message = telemetry.message;\r\n availabilityData.measurements = telemetry.measurements;\r\n availabilityData.properties = telemetry.properties;\r\n\r\n let data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.Availability);\r\n data.baseData = availabilityData;\r\n\r\n return data;\r\n }\r\n\r\n private static createPageViewData(\r\n telemetry: Contracts.PageViewTelemetry & Contracts.Identified\r\n ): Contracts.Data {\r\n let pageViewData = new Contracts.PageViewData();\r\n\r\n pageViewData.name = telemetry.name;\r\n pageViewData.duration = Util.msToTimeSpan(telemetry.duration);\r\n pageViewData.url = telemetry.url;\r\n pageViewData.measurements = telemetry.measurements;\r\n pageViewData.properties = telemetry.properties;\r\n\r\n let data = new Contracts.Data();\r\n data.baseType = Contracts.telemetryTypeToBaseType(Contracts.TelemetryType.PageView);\r\n data.baseData = pageViewData;\r\n\r\n return data;\r\n }\r\n\r\n private static getTags(context: Context, tagOverrides?: { [key: string]: string; }) {\r\n var correlationContext = CorrelationContextManager.getCurrentContext();\r\n\r\n // Make a copy of context tags so we don't alter the actual object\r\n // Also perform tag overriding\r\n var newTags = <{ [key: string]: string }>{};\r\n\r\n if (context && context.tags) {\r\n for (var key in context.tags) {\r\n newTags[key] = context.tags[key];\r\n }\r\n }\r\n if (tagOverrides) {\r\n for (var key in tagOverrides) {\r\n newTags[key] = tagOverrides[key];\r\n }\r\n }\r\n\r\n // Fill in internally-populated values if not already set\r\n if (correlationContext) {\r\n newTags[context.keys.operationId] = newTags[context.keys.operationId] || correlationContext.operation.id;\r\n newTags[context.keys.operationName] = newTags[context.keys.operationName] || correlationContext.operation.name;\r\n newTags[context.keys.operationParentId] = newTags[context.keys.operationParentId] || correlationContext.operation.parentId;\r\n }\r\n\r\n return newTags;\r\n }\r\n\r\n\r\n private static parseStack(stack: any): _StackFrame[] {\r\n var parsedStack: _StackFrame[] = undefined;\r\n if (typeof stack === \"string\") {\r\n var frames = stack.split(\"\\n\");\r\n parsedStack = [];\r\n var level = 0;\r\n\r\n var totalSizeInBytes = 0;\r\n for (var i = 0; i <= frames.length; i++) {\r\n var frame = frames[i];\r\n if (_StackFrame.regex.test(frame)) {\r\n var parsedFrame = new _StackFrame(frames[i], level++);\r\n totalSizeInBytes += parsedFrame.sizeInBytes;\r\n parsedStack.push(parsedFrame);\r\n }\r\n }\r\n\r\n // DP Constraint - exception parsed stack must be < 32KB\r\n // remove frames from the middle to meet the threshold\r\n var exceptionParsedStackThreshold = 32 * 1024;\r\n if (totalSizeInBytes > exceptionParsedStackThreshold) {\r\n var left = 0;\r\n var right = parsedStack.length - 1;\r\n var size = 0;\r\n var acceptedLeft = left;\r\n var acceptedRight = right;\r\n\r\n while (left < right) {\r\n // check size\r\n var lSize = parsedStack[left].sizeInBytes;\r\n var rSize = parsedStack[right].sizeInBytes;\r\n size += lSize + rSize;\r\n\r\n if (size > exceptionParsedStackThreshold) {\r\n\r\n // remove extra frames from the middle\r\n var howMany = acceptedRight - acceptedLeft + 1;\r\n parsedStack.splice(acceptedLeft, howMany);\r\n break;\r\n }\r\n\r\n // update pointers\r\n acceptedLeft = left;\r\n acceptedRight = right;\r\n\r\n left++;\r\n right--;\r\n }\r\n }\r\n }\r\n\r\n return parsedStack;\r\n }\r\n\r\n}\r\n\r\nclass _StackFrame {\r\n\r\n // regex to match stack frames from ie/chrome/ff\r\n // methodName=$2, fileName=$4, lineNo=$5, column=$6\r\n public static regex = /^(\\s+at)?(.*?)(\\@|\\s\\(|\\s)([^\\(\\n]+):(\\d+):(\\d+)(\\)?)$/;\r\n public static baseSize = 58; //'{\"method\":\"\",\"level\":,\"assembly\":\"\",\"fileName\":\"\",\"line\":}'.length\r\n public sizeInBytes = 0;\r\n public level: number;\r\n public method: string;\r\n public assembly: string;\r\n public fileName: string;\r\n public line: number;\r\n\r\n constructor(frame: string, level: number) {\r\n this.level = level;\r\n this.method = \"\";\r\n this.assembly = Util.trim(frame);\r\n var matches = frame.match(_StackFrame.regex);\r\n if (matches && matches.length >= 5) {\r\n this.method = Util.trim(matches[2]) || this.method;\r\n this.fileName = Util.trim(matches[4]) || \"\";\r\n this.line = parseInt(matches[5]) || 0;\r\n }\r\n\r\n this.sizeInBytes += this.method.length;\r\n this.sizeInBytes += this.fileName.length;\r\n this.sizeInBytes += this.assembly.length;\r\n\r\n // todo: these might need to be removed depending on how the back-end settles on their size calculation\r\n this.sizeInBytes += _StackFrame.baseSize;\r\n this.sizeInBytes += this.level.toString().length;\r\n this.sizeInBytes += this.line.toString().length;\r\n }\r\n}\r\n\r\nexport = EnvelopeFactory;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FileAccessControl.d.ts b/node_modules/applicationinsights/out/Library/FileAccessControl.d.ts new file mode 100644 index 0000000..4b832bf --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileAccessControl.d.ts @@ -0,0 +1,18 @@ +export declare class FileAccessControl { + private static TAG; + private static ICACLS_PATH; + private static POWERSHELL_PATH; + private static ACLED_DIRECTORIES; + private static ACL_IDENTITY; + private static OS_FILE_PROTECTION_CHECKED; + static OS_PROVIDES_FILE_PROTECTION: boolean; + static USE_ICACLS: boolean; + static checkFileProtection(): void; + static applyACLRules(directory: string): Promise; + static applyACLRulesSync(directory: string): void; + private static _runICACLS; + private static _runICACLSSync; + private static _getACLIdentity; + private static _getACLIdentitySync; + private static _getACLArguments; +} diff --git a/node_modules/applicationinsights/out/Library/FileAccessControl.js b/node_modules/applicationinsights/out/Library/FileAccessControl.js new file mode 100644 index 0000000..392ec46 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileAccessControl.js @@ -0,0 +1,216 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileAccessControl = void 0; +var fs = require("fs"); +var os = require("os"); +var child_process = require("child_process"); +var Logging = require("./Logging"); +var FileAccessControl = /** @class */ (function () { + function FileAccessControl() { + } + // Check if file access control could be enabled + FileAccessControl.checkFileProtection = function () { + if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION && !FileAccessControl.OS_FILE_PROTECTION_CHECKED) { + FileAccessControl.OS_FILE_PROTECTION_CHECKED = true; + // Node's chmod levels do not appropriately restrict file access on Windows + // Use the built-in command line tool ICACLS on Windows to properly restrict + // access to the temporary directory used for disk retry mode. + if (FileAccessControl.USE_ICACLS) { + // This should be async - but it's currently safer to have this synchronous + // This guarantees we can immediately fail setDiskRetryMode if we need to + try { + FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(FileAccessControl.ICACLS_PATH); + } + catch (e) { + // Ignore errors + } + if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) { + Logging.warn(FileAccessControl.TAG, "Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows."); + } + } + else { + // chmod works everywhere else + FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true; + } + } + }; + FileAccessControl.applyACLRules = function (directory) { + return __awaiter(this, void 0, void 0, function () { + var identity, ex_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!FileAccessControl.USE_ICACLS) return [3 /*break*/, 7]; + if (!(FileAccessControl.ACLED_DIRECTORIES[directory] === undefined)) return [3 /*break*/, 6]; + // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately + // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk + // This is better than the alternative of potentially infinitely spawned processes + FileAccessControl.ACLED_DIRECTORIES[directory] = false; + _a.label = 1; + case 1: + _a.trys.push([1, 4, , 5]); + return [4 /*yield*/, this._getACLIdentity()]; + case 2: + identity = _a.sent(); + return [4 /*yield*/, this._runICACLS(this._getACLArguments(directory, identity))]; + case 3: + _a.sent(); + FileAccessControl.ACLED_DIRECTORIES[directory] = true; + return [3 /*break*/, 5]; + case 4: + ex_1 = _a.sent(); + FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is "not yet tried") + throw ex_1; + case 5: return [3 /*break*/, 7]; + case 6: + if (!FileAccessControl.ACLED_DIRECTORIES[directory]) { + throw new Error("Setting ACL restrictions did not succeed (cached result)"); + } + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + FileAccessControl.applyACLRulesSync = function (directory) { + if (FileAccessControl.USE_ICACLS) { + // For performance, only run ACL rules if we haven't already during this session + if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) { + this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync())); + FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures + return; + } + else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) { // falsy but not undefined + throw new Error("Setting ACL restrictions did not succeed (cached result)"); + } + } + }; + FileAccessControl._runICACLS = function (args) { + return new Promise(function (resolve, reject) { + var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, { windowsHide: true }); + aclProc.on("error", function (e) { return reject(e); }); + aclProc.on("close", function (code, signal) { + if (code === 0) { + resolve(); + } + else { + reject(new Error("Setting ACL restrictions did not succeed (ICACLS returned code " + code + ")")); + } + }); + }); + }; + FileAccessControl._runICACLSSync = function (args) { + // Some very old versions of Node (< 0.11) don't have this + if (child_process.spawnSync) { + var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, { windowsHide: true }); + if (aclProc.error) { + throw aclProc.error; + } + else if (aclProc.status !== 0) { + throw new Error("Setting ACL restrictions did not succeed (ICACLS returned code " + aclProc.status + ")"); + } + } + else { + throw new Error("Could not synchronously call ICACLS under current version of Node.js"); + } + }; + FileAccessControl._getACLIdentity = function () { + return new Promise(function (resolve, reject) { + if (FileAccessControl.ACL_IDENTITY) { + resolve(FileAccessControl.ACL_IDENTITY); + } + var psProc = child_process.spawn(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], { + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"] // Needed to prevent hanging on Win 7 + }); + var data = ""; + psProc.stdout.on("data", function (d) { return data += d; }); + psProc.on("error", function (e) { return reject(e); }); + psProc.on("close", function (code, signal) { + FileAccessControl.ACL_IDENTITY = data && data.trim(); + if (code === 0) { + resolve(FileAccessControl.ACL_IDENTITY); + } + else { + reject(new Error("Getting ACL identity did not succeed (PS returned code " + code + ")")); + } + }); + }); + }; + FileAccessControl._getACLIdentitySync = function () { + if (FileAccessControl.ACL_IDENTITY) { + return FileAccessControl.ACL_IDENTITY; + } + // Some very old versions of Node (< 0.11) don't have this + if (child_process.spawnSync) { + var psProc = child_process.spawnSync(FileAccessControl.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], { + windowsHide: true, + stdio: ["ignore", "pipe", "pipe"] // Needed to prevent hanging on Win 7 + }); + if (psProc.error) { + throw psProc.error; + } + else if (psProc.status !== 0) { + throw new Error("Getting ACL identity did not succeed (PS returned code " + psProc.status + ")"); + } + FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim(); + return FileAccessControl.ACL_IDENTITY; + } + else { + throw new Error("Could not synchronously get ACL identity under current version of Node.js"); + } + }; + FileAccessControl._getACLArguments = function (directory, identity) { + return [directory, + "/grant", "*S-1-5-32-544:(OI)(CI)F", + "/grant", identity + ":(OI)(CI)F", // Full permission for current user + "/inheritance:r"]; // Remove all inherited permissions + }; + FileAccessControl.TAG = "FileAccessControl"; + FileAccessControl.ICACLS_PATH = process.env.systemdrive + "/windows/system32/icacls.exe"; + FileAccessControl.POWERSHELL_PATH = process.env.systemdrive + "/windows/system32/windowspowershell/v1.0/powershell.exe"; + FileAccessControl.ACLED_DIRECTORIES = {}; + FileAccessControl.ACL_IDENTITY = null; + FileAccessControl.OS_FILE_PROTECTION_CHECKED = false; + FileAccessControl.OS_PROVIDES_FILE_PROTECTION = false; + FileAccessControl.USE_ICACLS = os.type() === "Windows_NT"; + return FileAccessControl; +}()); +exports.FileAccessControl = FileAccessControl; +//# sourceMappingURL=FileAccessControl.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FileAccessControl.js.map b/node_modules/applicationinsights/out/Library/FileAccessControl.js.map new file mode 100644 index 0000000..de45d55 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileAccessControl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileAccessControl.js","sourceRoot":"","sources":["../../Library/FileAccessControl.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uBAA0B;AAC1B,uBAA0B;AAC1B,6CAAgD;AAEhD,mCAAsC;AAGtC;IAAA;IA8JA,CAAC;IAlJG,gDAAgD;IAClC,qCAAmB,GAAjC;QACI,IAAI,CAAC,iBAAiB,CAAC,2BAA2B,IAAI,CAAC,iBAAiB,CAAC,0BAA0B,EAAE;YACjG,iBAAiB,CAAC,0BAA0B,GAAG,IAAI,CAAC;YACpD,2EAA2E;YAC3E,4EAA4E;YAC5E,8DAA8D;YAC9D,IAAI,iBAAiB,CAAC,UAAU,EAAE;gBAC9B,2EAA2E;gBAC3E,yEAAyE;gBACzE,IAAI;oBACA,iBAAiB,CAAC,2BAA2B,GAAG,EAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;iBAChG;gBAAC,OAAO,CAAC,EAAE;oBACR,gBAAgB;iBAClB;gBACF,IAAI,CAAC,iBAAiB,CAAC,2BAA2B,EAAE;oBAChD,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,kGAAkG,CAAC,CAAA;iBAC1I;aACJ;iBAAM;gBACH,8BAA8B;gBAC9B,iBAAiB,CAAC,2BAA2B,GAAG,IAAI,CAAC;aACxD;SACJ;IACL,CAAC;IAEmB,+BAAa,GAAjC,UAAkC,SAAiB;;;;;;6BAC3C,iBAAiB,CAAC,UAAU,EAA5B,wBAA4B;6BACxB,CAAA,iBAAiB,CAAC,iBAAiB,CAAC,SAAS,CAAC,KAAK,SAAS,CAAA,EAA5D,wBAA4D;wBAC5D,2GAA2G;w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C,qCAAqC;aAC1E,CAAC,CAAC;YACP,IAAI,MAAM,CAAC,KAAK,EAAE;gBACd,MAAM,MAAM,CAAC,KAAK,CAAC;aACtB;iBAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC5B,MAAM,IAAI,KAAK,CAAC,4DAA0D,MAAM,CAAC,MAAM,MAAG,CAAC,CAAC;aAC/F;YACD,iBAAiB,CAAC,YAAY,GAAG,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;YAClF,OAAO,iBAAiB,CAAC,YAAY,CAAC;SACzC;aAAM;YACH,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;SAChG;IACL,CAAC;IAEc,kCAAgB,GAA/B,UAAgC,SAAiB,EAAE,QAAgB;QAC/D,OAAO,CAAC,SAAS;YACb,QAAQ,EAAE,yBAAyB;YACnC,QAAQ,EAAK,QAAQ,eAAY,EAAE,mCAAmC;YACtE,gBAAgB,CAAC,CAAC,CAAC,mCAAmC;IAC9D,CAAC;IA5Jc,qBAAG,GAAG,mBAAmB,CAAC;IAE1B,6BAAW,GAAM,OAAO,CAAC,GAAG,CAAC,WAAW,iCAA8B,CAAC;IACvE,iCAAe,GAAM,OAAO,CAAC,GAAG,CAAC,WAAW,4DAAyD,CAAC;IACtG,mCAAiB,GAA8B,EAAE,CAAC;IAClD,8BAAY,GAAW,IAAI,CAAC;IAC5B,4CAA0B,GAAG,KAAK,CAAC;IACpC,6CAA2B,GAAG,KAAK,CAAC;IACpC,4BAAU,GAAG,EAAE,CAAC,IAAI,EAAE,KAAK,YAAY,CAAC;IAqJ1D,wBAAC;CAAA,AA9JD,IA8JC;AA9JY,8CAAiB","sourcesContent":["import fs = require(\"fs\");\r\nimport os = require(\"os\");\r\nimport child_process = require(\"child_process\");\r\n\r\nimport Logging = require(\"./Logging\");\r\n\r\n\r\nexport class FileAccessControl {\r\n private static TAG = \"FileAccessControl\";\r\n\r\n private static ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;\r\n private static POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;\r\n private static ACLED_DIRECTORIES: { [id: string]: boolean } = {};\r\n private static ACL_IDENTITY: string = null;\r\n private static OS_FILE_PROTECTION_CHECKED = false;\r\n public static OS_PROVIDES_FILE_PROTECTION = false;\r\n public static USE_ICACLS = os.type() === \"Windows_NT\";\r\n\r\n\r\n // Check if file access control could be enabled\r\n public static checkFileProtection() {\r\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION && !FileAccessControl.OS_FILE_PROTECTION_CHECKED) {\r\n FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;\r\n // Node's chmod levels do not appropriately restrict file access on Windows\r\n // Use the built-in command line tool ICACLS on Windows to properly restrict\r\n // access to the temporary directory used for disk retry mode.\r\n if (FileAccessControl.USE_ICACLS) {\r\n // This should be async - but it's currently safer to have this synchronous\r\n // This guarantees we can immediately fail setDiskRetryMode if we need to\r\n try {\r\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(FileAccessControl.ICACLS_PATH);\r\n } catch (e) {\r\n // Ignore errors\r\n }\r\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\r\n Logging.warn(FileAccessControl.TAG, \"Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.\")\r\n }\r\n } else {\r\n // chmod works everywhere else\r\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;\r\n }\r\n }\r\n }\r\n\r\n public static async applyACLRules(directory: string): Promise {\r\n if (FileAccessControl.USE_ICACLS) {\r\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\r\n // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately\r\n // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk\r\n // This is better than the alternative of potentially infinitely spawned processes\r\n FileAccessControl.ACLED_DIRECTORIES[directory] = false;\r\n try {\r\n // Restrict this directory to only current user and administrator access\r\n let identity = await this._getACLIdentity();\r\n await this._runICACLS(this._getACLArguments(directory, identity));\r\n FileAccessControl.ACLED_DIRECTORIES[directory] = true;\r\n }\r\n catch (ex) {\r\n FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is \"not yet tried\")\r\n throw ex;\r\n }\r\n } else {\r\n if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\r\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\r\n }\r\n }\r\n }\r\n }\r\n\r\n public static applyACLRulesSync(directory: string) {\r\n if (FileAccessControl.USE_ICACLS) {\r\n // For performance, only run ACL rules if we haven't already during this session\r\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\r\n this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));\r\n FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures\r\n return;\r\n } else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) { // falsy but not undefined\r\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\r\n }\r\n }\r\n }\r\n\r\n private static _runICACLS(args: string[]): Promise {\r\n return new Promise((resolve, reject) => {\r\n var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, { windowsHide: true });\r\n aclProc.on(\"error\", (e: Error) => reject(e));\r\n aclProc.on(\"close\", (code: number, signal: string) => {\r\n if (code === 0) {\r\n resolve();\r\n }\r\n else {\r\n reject(new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`));\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static _runICACLSSync(args: string[]) {\r\n // Some very old versions of Node (< 0.11) don't have this\r\n if (child_process.spawnSync) {\r\n var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, { windowsHide: true });\r\n if (aclProc.error) {\r\n throw aclProc.error;\r\n } else if (aclProc.status !== 0) {\r\n throw new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`);\r\n }\r\n } else {\r\n throw new Error(\"Could not synchronously call ICACLS under current version of Node.js\");\r\n }\r\n }\r\n\r\n private static _getACLIdentity(): Promise {\r\n return new Promise((resolve, reject) => {\r\n if (FileAccessControl.ACL_IDENTITY) {\r\n resolve(FileAccessControl.ACL_IDENTITY);\r\n }\r\n var psProc = child_process.spawn(FileAccessControl.POWERSHELL_PATH,\r\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"], {\r\n windowsHide: true,\r\n stdio: [\"ignore\", \"pipe\", \"pipe\"] // Needed to prevent hanging on Win 7\r\n });\r\n let data = \"\";\r\n psProc.stdout.on(\"data\", (d: string) => data += d);\r\n psProc.on(\"error\", (e: Error) => reject(e));\r\n psProc.on(\"close\", (code: number, signal: string) => {\r\n FileAccessControl.ACL_IDENTITY = data && data.trim();\r\n if (code === 0) {\r\n resolve(FileAccessControl.ACL_IDENTITY);\r\n }\r\n else {\r\n reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));\r\n }\r\n });\r\n });\r\n }\r\n\r\n private static _getACLIdentitySync() {\r\n if (FileAccessControl.ACL_IDENTITY) {\r\n return FileAccessControl.ACL_IDENTITY;\r\n }\r\n // Some very old versions of Node (< 0.11) don't have this\r\n if (child_process.spawnSync) {\r\n var psProc = child_process.spawnSync(FileAccessControl.POWERSHELL_PATH,\r\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"], {\r\n windowsHide: true,\r\n stdio: [\"ignore\", \"pipe\", \"pipe\"] // Needed to prevent hanging on Win 7\r\n });\r\n if (psProc.error) {\r\n throw psProc.error;\r\n } else if (psProc.status !== 0) {\r\n throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);\r\n }\r\n FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();\r\n return FileAccessControl.ACL_IDENTITY;\r\n } else {\r\n throw new Error(\"Could not synchronously get ACL identity under current version of Node.js\");\r\n }\r\n }\r\n\r\n private static _getACLArguments(directory: string, identity: string) {\r\n return [directory,\r\n \"/grant\", \"*S-1-5-32-544:(OI)(CI)F\", // Full permission for Administrators\r\n \"/grant\", `${identity}:(OI)(CI)F`, // Full permission for current user\r\n \"/inheritance:r\"]; // Remove all inherited permissions\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FileSystemHelper.d.ts b/node_modules/applicationinsights/out/Library/FileSystemHelper.d.ts new file mode 100644 index 0000000..62ee390 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileSystemHelper.d.ts @@ -0,0 +1,27 @@ +/// +import * as fs from "fs"; +export declare const statAsync: typeof fs.stat.__promisify__; +export declare const lstatAsync: typeof fs.lstat.__promisify__; +export declare const mkdirAsync: typeof fs.mkdir.__promisify__; +export declare const accessAsync: typeof fs.access.__promisify__; +export declare const appendFileAsync: typeof fs.appendFile.__promisify__; +export declare const writeFileAsync: typeof fs.writeFile.__promisify__; +export declare const readFileAsync: typeof fs.readFile.__promisify__; +export declare const readdirAsync: typeof fs.readdir.__promisify__; +export declare const unlinkAsync: typeof fs.unlink.__promisify__; +/** + * Validate directory exists. + */ +export declare const confirmDirExists: (directory: string) => Promise; +/** + * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously. + */ +export declare const getShallowDirectorySize: (directory: string) => Promise; +/** +* Computes the size (in bytes) of all files in a directory at the root level. Synchronously. +*/ +export declare const getShallowDirectorySizeSync: (directory: string) => number; +/** +* Computes the size (in bytes) of a file asynchronously. +*/ +export declare const getShallowFileSize: (filePath: string) => Promise; diff --git a/node_modules/applicationinsights/out/Library/FileSystemHelper.js b/node_modules/applicationinsights/out/Library/FileSystemHelper.js new file mode 100644 index 0000000..5b301a2 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileSystemHelper.js @@ -0,0 +1,152 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getShallowFileSize = exports.getShallowDirectorySizeSync = exports.getShallowDirectorySize = exports.confirmDirExists = exports.unlinkAsync = exports.readdirAsync = exports.readFileAsync = exports.writeFileAsync = exports.appendFileAsync = exports.accessAsync = exports.mkdirAsync = exports.lstatAsync = exports.statAsync = void 0; +var fs = require("fs"); +var path = require("path"); +var util_1 = require("util"); +exports.statAsync = util_1.promisify(fs.stat); +exports.lstatAsync = util_1.promisify(fs.lstat); +exports.mkdirAsync = util_1.promisify(fs.mkdir); +exports.accessAsync = util_1.promisify(fs.access); +exports.appendFileAsync = util_1.promisify(fs.appendFile); +exports.writeFileAsync = util_1.promisify(fs.writeFile); +exports.readFileAsync = util_1.promisify(fs.readFile); +exports.readdirAsync = util_1.promisify(fs.readdir); +exports.unlinkAsync = util_1.promisify(fs.unlink); +/** + * Validate directory exists. + */ +var confirmDirExists = function (directory) { return __awaiter(void 0, void 0, void 0, function () { + var stats, err_1, mkdirErr_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 7]); + return [4 /*yield*/, exports.lstatAsync(directory)]; + case 1: + stats = _a.sent(); + if (!stats.isDirectory()) { + throw new Error("Path existed but was not a directory"); + } + return [3 /*break*/, 7]; + case 2: + err_1 = _a.sent(); + if (!(err_1 && err_1.code === "ENOENT")) return [3 /*break*/, 6]; + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, exports.mkdirAsync(directory)]; + case 4: + _a.sent(); + return [3 /*break*/, 6]; + case 5: + mkdirErr_1 = _a.sent(); + if (mkdirErr_1 && mkdirErr_1.code !== "EEXIST") { + // Handle race condition by ignoring EEXIST + throw mkdirErr_1; + } + return [3 /*break*/, 6]; + case 6: return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); +}); }; +exports.confirmDirExists = confirmDirExists; +/** + * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously. + */ +var getShallowDirectorySize = function (directory) { return __awaiter(void 0, void 0, void 0, function () { + var files, totalSize, _i, files_1, file, fileStats; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, exports.readdirAsync(directory)]; + case 1: + files = _a.sent(); + totalSize = 0; + _i = 0, files_1 = files; + _a.label = 2; + case 2: + if (!(_i < files_1.length)) return [3 /*break*/, 5]; + file = files_1[_i]; + return [4 /*yield*/, exports.statAsync(path.join(directory, file))]; + case 3: + fileStats = _a.sent(); + if (fileStats.isFile()) { + totalSize += fileStats.size; + } + _a.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: return [2 /*return*/, totalSize]; + } + }); +}); }; +exports.getShallowDirectorySize = getShallowDirectorySize; +/** +* Computes the size (in bytes) of all files in a directory at the root level. Synchronously. +*/ +var getShallowDirectorySizeSync = function (directory) { + var files = fs.readdirSync(directory); + var totalSize = 0; + for (var i = 0; i < files.length; i++) { + totalSize += fs.statSync(path.join(directory, files[i])).size; + } + return totalSize; +}; +exports.getShallowDirectorySizeSync = getShallowDirectorySizeSync; +/** +* Computes the size (in bytes) of a file asynchronously. +*/ +var getShallowFileSize = function (filePath) { return __awaiter(void 0, void 0, void 0, function () { + var fileStats; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, exports.statAsync(filePath)]; + case 1: + fileStats = _a.sent(); + if (fileStats.isFile()) { + return [2 /*return*/, fileStats.size]; + } + return [2 /*return*/]; + } + }); +}); }; +exports.getShallowFileSize = getShallowFileSize; +//# sourceMappingURL=FileSystemHelper.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FileSystemHelper.js.map b/node_modules/applicationinsights/out/Library/FileSystemHelper.js.map new file mode 100644 index 0000000..9d90475 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FileSystemHelper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FileSystemHelper.js","sourceRoot":"","sources":["../../Library/FileSystemHelper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uBAAyB;AACzB,2BAA8B;AAC9B,6BAAiC;AAEpB,QAAA,SAAS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ify } from \"util\";\r\n\r\nexport const statAsync = promisify(fs.stat);\r\nexport const lstatAsync = promisify(fs.lstat);\r\nexport const mkdirAsync = promisify(fs.mkdir);\r\nexport const accessAsync = promisify(fs.access);\r\nexport const appendFileAsync = promisify(fs.appendFile);\r\nexport const writeFileAsync = promisify(fs.writeFile);\r\nexport const readFileAsync = promisify(fs.readFile);\r\nexport const readdirAsync = promisify(fs.readdir);\r\nexport const unlinkAsync = promisify(fs.unlink);\r\n\r\n/**\r\n * Validate directory exists.\r\n */\r\nexport const confirmDirExists = async (directory: string): Promise => {\r\n try {\r\n const stats = await lstatAsync(directory);\r\n if (!stats.isDirectory()) {\r\n throw new Error(\"Path existed but was not a directory\");\r\n }\r\n } catch (err) {\r\n if (err && err.code === \"ENOENT\") {\r\n try {\r\n await mkdirAsync(directory);\r\n } catch (mkdirErr) {\r\n if (mkdirErr && mkdirErr.code !== \"EEXIST\") {\r\n // Handle race condition by ignoring EEXIST\r\n throw mkdirErr;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.\r\n */\r\nexport const getShallowDirectorySize = async (directory: string): Promise => {\r\n // Get the directory listing\r\n const files = await readdirAsync(directory);\r\n let totalSize = 0;\r\n // Query all file sizes\r\n for (const file of files) {\r\n const fileStats = await statAsync(path.join(directory, file));\r\n if (fileStats.isFile()) {\r\n totalSize += fileStats.size;\r\n }\r\n }\r\n return totalSize;\r\n};\r\n\r\n/**\r\n* Computes the size (in bytes) of all files in a directory at the root level. Synchronously.\r\n*/\r\nexport const getShallowDirectorySizeSync = (directory: string): number => {\r\n let files = fs.readdirSync(directory);\r\n let totalSize = 0;\r\n for (let i = 0; i < files.length; i++) {\r\n totalSize += fs.statSync(path.join(directory, files[i])).size;\r\n }\r\n return totalSize;\r\n}\r\n\r\n/**\r\n* Computes the size (in bytes) of a file asynchronously.\r\n*/\r\nexport const getShallowFileSize = async (filePath: string): Promise => {\r\n const fileStats = await statAsync(filePath);\r\n if (fileStats.isFile()) {\r\n return fileStats.size;\r\n }\r\n}\r\n\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FlushOptions.d.ts b/node_modules/applicationinsights/out/Library/FlushOptions.d.ts new file mode 100644 index 0000000..16dfea6 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FlushOptions.d.ts @@ -0,0 +1,16 @@ +/** + * Encapsulates options passed into client.flush() function + */ +interface FlushOptions { + /** + * Flag indicating whether application is crashing. When this flag is set to true + * and storing data locally is enabled, Node.JS SDK will attempt to store data on disk + */ + isAppCrashing?: boolean; + /** + * Callback that will be invoked with the response from server, in case of isAppCrashing set to true, + * with immediate notification that data was stored + */ + callback?: (v: string) => void; +} +export = FlushOptions; diff --git a/node_modules/applicationinsights/out/Library/FlushOptions.js b/node_modules/applicationinsights/out/Library/FlushOptions.js new file mode 100644 index 0000000..4e42ad8 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FlushOptions.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FlushOptions.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/FlushOptions.js.map b/node_modules/applicationinsights/out/Library/FlushOptions.js.map new file mode 100644 index 0000000..6511b31 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/FlushOptions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FlushOptions.js","sourceRoot":"","sources":["../../Library/FlushOptions.ts"],"names":[],"mappings":"","sourcesContent":["/**\r\n * Encapsulates options passed into client.flush() function\r\n */\r\ninterface FlushOptions\r\n{\r\n /**\r\n * Flag indicating whether application is crashing. When this flag is set to true\r\n * and storing data locally is enabled, Node.JS SDK will attempt to store data on disk\r\n */\r\n isAppCrashing?:boolean\r\n \r\n /**\r\n * Callback that will be invoked with the response from server, in case of isAppCrashing set to true,\r\n * with immediate notification that data was stored\r\n */\r\n callback?: (v: string) => void;\r\n}\r\nexport = FlushOptions;"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Functions.d.ts b/node_modules/applicationinsights/out/Library/Functions.d.ts new file mode 100644 index 0000000..5184938 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Functions.d.ts @@ -0,0 +1,48 @@ +/** + * The context object can be used for writing logs, reading data from bindings, setting outputs and using + * the context.done callback when your exported function is synchronous. A context object is passed + * to your function from the Azure Functions runtime on function invocation. + */ +export interface Context { + /** + * A unique GUID per function invocation. + */ + invocationId?: string; + /** + * TraceContext information to enable distributed tracing scenarios. + */ + traceContext: TraceContext; + /** + * HTTP request object. Provided to your function when using HTTP Bindings. + */ + req?: HttpRequest; + /** + * HTTP response object. Provided to your function when using HTTP Bindings. + */ + res?: { + [key: string]: any; + }; +} +/** + * HTTP request object. Provided to your function when using HTTP Bindings. + */ +export interface HttpRequest { + method: string | null; + url: string; + headers: { + [key: string]: string; + }; +} +/** + * TraceContext information to enable distributed tracing scenarios. + */ +export interface TraceContext { + /** Describes the position of the incoming request in its trace graph in a portable, fixed-length format. */ + traceparent: string | null | undefined; + /** Extends traceparent with vendor-specific data. */ + tracestate: string | null | undefined; + /** Holds additional properties being sent as part of request telemetry. */ + attributes: { + [k: string]: string; + } | null | undefined; +} diff --git a/node_modules/applicationinsights/out/Library/Functions.js b/node_modules/applicationinsights/out/Library/Functions.js new file mode 100644 index 0000000..ea1f60a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Functions.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Functions.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Functions.js.map b/node_modules/applicationinsights/out/Library/Functions.js.map new file mode 100644 index 0000000..ae67d03 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Functions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Functions.js","sourceRoot":"","sources":["../../Library/Functions.ts"],"names":[],"mappings":"","sourcesContent":["/**\r\n * The context object can be used for writing logs, reading data from bindings, setting outputs and using\r\n * the context.done callback when your exported function is synchronous. A context object is passed\r\n * to your function from the Azure Functions runtime on function invocation.\r\n */\r\nexport interface Context {\r\n /**\r\n * A unique GUID per function invocation.\r\n */\r\n invocationId?: string;\r\n /**\r\n * TraceContext information to enable distributed tracing scenarios.\r\n */\r\n traceContext: TraceContext;\r\n /**\r\n * HTTP request object. Provided to your function when using HTTP Bindings.\r\n */\r\n req?: HttpRequest;\r\n /**\r\n * HTTP response object. Provided to your function when using HTTP Bindings.\r\n */\r\n res?: {\r\n [key: string]: any;\r\n };\r\n}\r\n\r\n/**\r\n * HTTP request object. Provided to your function when using HTTP Bindings.\r\n */\r\nexport interface HttpRequest {\r\n method: string | null;\r\n url: string;\r\n headers: {\r\n [key: string]: string;\r\n };\r\n}\r\n\r\n/**\r\n * TraceContext information to enable distributed tracing scenarios.\r\n */\r\nexport interface TraceContext {\r\n /** Describes the position of the incoming request in its trace graph in a portable, fixed-length format. */\r\n traceparent: string | null | undefined;\r\n /** Extends traceparent with vendor-specific data. */\r\n tracestate: string | null | undefined;\r\n /** Holds additional properties being sent as part of request telemetry. */\r\n attributes: {\r\n [k: string]: string;\r\n } | null | undefined;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/InternalAzureLogger.d.ts b/node_modules/applicationinsights/out/Library/InternalAzureLogger.d.ts new file mode 100644 index 0000000..4240e5e --- /dev/null +++ b/node_modules/applicationinsights/out/Library/InternalAzureLogger.d.ts @@ -0,0 +1,22 @@ +declare class InternalAzureLogger { + private static _instance; + maxHistory: number; + maxSizeBytes: number; + private TAG; + private _cleanupTimeOut; + private static _fileCleanupTimer; + private _tempDir; + _logFileName: string; + private _fileFullPath; + private _backUpNameFormat; + private _logToFile; + private _logToConsole; + constructor(); + info(message?: any, ...optionalParams: any[]): void; + warning(message?: any, ...optionalParams: any[]): void; + static getInstance(): InternalAzureLogger; + private _storeToDisk; + private _createBackupFile; + private _fileCleanupTask; +} +export = InternalAzureLogger; diff --git a/node_modules/applicationinsights/out/Library/InternalAzureLogger.js b/node_modules/applicationinsights/out/Library/InternalAzureLogger.js new file mode 100644 index 0000000..5c5863b --- /dev/null +++ b/node_modules/applicationinsights/out/Library/InternalAzureLogger.js @@ -0,0 +1,263 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var FileSystemHelper = require("./FileSystemHelper"); +var InternalAzureLogger = /** @class */ (function () { + function InternalAzureLogger() { + var _this = this; + this.TAG = "Logger"; + this._cleanupTimeOut = 60 * 30 * 1000; // 30 minutes; + this._logToFile = false; + this._logToConsole = true; + var logDestination = process.env.APPLICATIONINSIGHTS_LOG_DESTINATION; // destination can be one of file, console or file+console + if (logDestination == "file+console") { + this._logToFile = true; + } + if (logDestination == "file") { + this._logToFile = true; + this._logToConsole = false; + } + this.maxSizeBytes = 50000; + this.maxHistory = 1; + this._logFileName = "applicationinsights.log"; + // If custom path not provided use temp folder, /tmp for *nix and USERDIR/AppData/Local/Temp for Windows + var logFilePath = process.env.APPLICATIONINSIGHTS_LOGDIR; + if (!logFilePath) { + this._tempDir = path.join(os.tmpdir(), "appInsights-node"); + } + else { + if (path.isAbsolute(logFilePath)) { + this._tempDir = logFilePath; + } + else { + this._tempDir = path.join(process.cwd(), logFilePath); + } + } + this._fileFullPath = path.join(this._tempDir, this._logFileName); + this._backUpNameFormat = "." + this._logFileName; // {currentime}.applicationinsights.log + if (this._logToFile) { + if (!InternalAzureLogger._fileCleanupTimer) { + InternalAzureLogger._fileCleanupTimer = setInterval(function () { _this._fileCleanupTask(); }, this._cleanupTimeOut); + InternalAzureLogger._fileCleanupTimer.unref(); + } + } + } + InternalAzureLogger.prototype.info = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + var args = message ? __spreadArrays([message], optionalParams) : optionalParams; + if (this._logToFile) { + this._storeToDisk(args); + } + if (this._logToConsole) { + console.info.apply(console, args); + } + }; + InternalAzureLogger.prototype.warning = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + var args = message ? __spreadArrays([message], optionalParams) : optionalParams; + if (this._logToFile) { + this._storeToDisk(args); + } + if (this._logToConsole) { + console.warn.apply(console, args); + } + }; + InternalAzureLogger.getInstance = function () { + if (!InternalAzureLogger._instance) { + InternalAzureLogger._instance = new InternalAzureLogger(); + } + return InternalAzureLogger._instance; + }; + InternalAzureLogger.prototype._storeToDisk = function (args) { + return __awaiter(this, void 0, void 0, function () { + var data, err_1, appendError_1, err_2, size, err_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + data = args + "\r\n"; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, FileSystemHelper.confirmDirExists(this._tempDir)]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + console.log(this.TAG, "Failed to create directory for log file: " + (err_1 && err_1.message)); + return [2 /*return*/]; + case 4: + _a.trys.push([4, 6, , 11]); + return [4 /*yield*/, FileSystemHelper.accessAsync(this._fileFullPath, fs.constants.F_OK)]; + case 5: + _a.sent(); + return [3 /*break*/, 11]; + case 6: + appendError_1 = _a.sent(); + _a.label = 7; + case 7: + _a.trys.push([7, 9, , 10]); + return [4 /*yield*/, FileSystemHelper.appendFileAsync(this._fileFullPath, data)]; + case 8: + _a.sent(); + return [2 /*return*/]; + case 9: + err_2 = _a.sent(); + console.log(this.TAG, "Failed to put log into file: " + (appendError_1 && appendError_1.message)); + return [2 /*return*/]; + case 10: return [3 /*break*/, 11]; + case 11: + _a.trys.push([11, 17, , 18]); + return [4 /*yield*/, FileSystemHelper.getShallowFileSize(this._fileFullPath)]; + case 12: + size = _a.sent(); + if (!(size > this.maxSizeBytes)) return [3 /*break*/, 14]; + return [4 /*yield*/, this._createBackupFile(data)]; + case 13: + _a.sent(); + return [3 /*break*/, 16]; + case 14: return [4 /*yield*/, FileSystemHelper.appendFileAsync(this._fileFullPath, data)]; + case 15: + _a.sent(); + _a.label = 16; + case 16: return [3 /*break*/, 18]; + case 17: + err_3 = _a.sent(); + console.log(this.TAG, "Failed to create backup file: " + (err_3 && err_3.message)); + return [3 /*break*/, 18]; + case 18: return [2 /*return*/]; + } + }); + }); + }; + InternalAzureLogger.prototype._createBackupFile = function (data) { + return __awaiter(this, void 0, void 0, function () { + var buffer, backupPath, err_4; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, 4, 5]); + return [4 /*yield*/, FileSystemHelper.readFileAsync(this._fileFullPath)]; + case 1: + buffer = _a.sent(); + backupPath = path.join(this._tempDir, new Date().getTime() + "." + this._logFileName); + return [4 /*yield*/, FileSystemHelper.writeFileAsync(backupPath, buffer)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: + err_4 = _a.sent(); + console.log("Failed to generate backup log file", err_4); + return [3 /*break*/, 5]; + case 4: + // Store logs + FileSystemHelper.writeFileAsync(this._fileFullPath, data); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + InternalAzureLogger.prototype._fileCleanupTask = function () { + return __awaiter(this, void 0, void 0, function () { + var files, totalFiles, i, pathToDelete, err_5; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 6, , 7]); + return [4 /*yield*/, FileSystemHelper.readdirAsync(this._tempDir)]; + case 1: + files = _a.sent(); + // Filter only backup files + files = files.filter(function (f) { return path.basename(f).indexOf(_this._backUpNameFormat) > -1; }); + // Sort by creation date + files.sort(function (a, b) { + // Check expiration + var aCreationDate = new Date(parseInt(a.split(_this._backUpNameFormat)[0])); + var bCreationDate = new Date(parseInt(b.split(_this._backUpNameFormat)[0])); + if (aCreationDate < bCreationDate) { + return -1; + } + if (aCreationDate >= bCreationDate) { + return 1; + } + }); + totalFiles = files.length; + i = 0; + _a.label = 2; + case 2: + if (!(i < totalFiles - this.maxHistory)) return [3 /*break*/, 5]; + pathToDelete = path.join(this._tempDir, files[i]); + return [4 /*yield*/, FileSystemHelper.unlinkAsync(pathToDelete)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 7]; + case 6: + err_5 = _a.sent(); + console.log(this.TAG, "Failed to cleanup log files: " + (err_5 && err_5.message)); + return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + InternalAzureLogger._fileCleanupTimer = null; + return InternalAzureLogger; +}()); +module.exports = InternalAzureLogger; +//# sourceMappingURL=InternalAzureLogger.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/InternalAzureLogger.js.map b/node_modules/applicationinsights/out/Library/InternalAzureLogger.js.map new file mode 100644 index 0000000..7cd249a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/InternalAzureLogger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"InternalAzureLogger.js","sourceRoot":"","sources":["../../Library/InternalAzureLogger.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uBAA0B;AAC1B,uBAA0B;AAC1B,2BAA8B;AAC9B,qDAAwD;AAGxD;IAiBI;QAAA,iBAmCC;QA9CO,QAAG,GAAG,QAAQ,CAAC;QACf,oBAAe,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,cAAc;QAMhD,eAAU,GAAG,KAAK,CAAC;QACnB,kBAAa,GAAG,IAAI,CAAC;QAIzB,IAAI,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC,0DAA0D;QAChI,IAAI,cAAc,IAAI,cAAc,EAAE;YAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAA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B,CAAC,GAAG,CAAC;;;6BAAE,CAAA,CAAC,GAAG,UAAU,GAAG,IAAI,CAAC,UAAU,CAAA;wBACxC,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;wBACtD,qBAAM,gBAAgB,CAAC,WAAW,CAAC,YAAY,CAAC,EAAA;;wBAAhD,SAAgD,CAAC;;;wBAFH,CAAC,EAAE,CAAA;;;;;wBAMrD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,+BAA+B,GAAG,CAAC,KAAG,IAAI,KAAG,CAAC,OAAO,CAAC,CAAC,CAAC;;;;;;KAErF;IAzJc,qCAAiB,GAAiB,IAAI,CAAC;IA0J1D,0BAAC;CAAA,AAlKD,IAkKC;AAED,iBAAS,mBAAmB,CAAC","sourcesContent":["import fs = require(\"fs\");\r\nimport os = require(\"os\");\r\nimport path = require(\"path\");\r\nimport FileSystemHelper = require(\"./FileSystemHelper\");\r\n\r\n\r\nclass InternalAzureLogger {\r\n\r\n private static _instance: InternalAzureLogger;\r\n public maxHistory: number;\r\n public maxSizeBytes: number;\r\n\r\n private TAG = \"Logger\";\r\n private _cleanupTimeOut = 60 * 30 * 1000; // 30 minutes;\r\n private static _fileCleanupTimer: NodeJS.Timer = null;\r\n private _tempDir: string;\r\n public _logFileName: string;\r\n private _fileFullPath: string;\r\n private _backUpNameFormat: string;\r\n private _logToFile = false;\r\n private _logToConsole = true;\r\n\r\n\r\n constructor() {\r\n let logDestination = process.env.APPLICATIONINSIGHTS_LOG_DESTINATION; // destination can be one of file, console or file+console\r\n if (logDestination == \"file+console\") {\r\n this._logToFile = true;\r\n }\r\n if (logDestination == \"file\") {\r\n this._logToFile = true;\r\n this._logToConsole = false;\r\n }\r\n this.maxSizeBytes = 50000;\r\n this.maxHistory = 1;\r\n this._logFileName = \"applicationinsights.log\";\r\n\r\n // If custom path not provided use temp folder, /tmp for *nix and USERDIR/AppData/Local/Temp for Windows\r\n let logFilePath = process.env.APPLICATIONINSIGHTS_LOGDIR;\r\n if (!logFilePath) {\r\n this._tempDir = path.join(os.tmpdir(), \"appInsights-node\");\r\n }\r\n else {\r\n if (path.isAbsolute(logFilePath)) {\r\n this._tempDir = logFilePath;\r\n }\r\n else {\r\n this._tempDir = path.join(process.cwd(), logFilePath);\r\n }\r\n }\r\n this._fileFullPath = path.join(this._tempDir, this._logFileName);\r\n this._backUpNameFormat = \".\" + this._logFileName; // {currentime}.applicationinsights.log\r\n\r\n if (this._logToFile) {\r\n if (!InternalAzureLogger._fileCleanupTimer) {\r\n InternalAzureLogger._fileCleanupTimer = setInterval(() => { this._fileCleanupTask(); }, this._cleanupTimeOut);\r\n InternalAzureLogger._fileCleanupTimer.unref();\r\n }\r\n }\r\n }\r\n\r\n public info(message?: any, ...optionalParams: any[]) {\r\n let args = message ? [message, ...optionalParams] : optionalParams;\r\n if (this._logToFile) {\r\n this._storeToDisk(args);\r\n }\r\n if (this._logToConsole) {\r\n console.info(...args);\r\n }\r\n }\r\n\r\n public warning(message?: any, ...optionalParams: any[]) {\r\n let args = message ? [message, ...optionalParams] : optionalParams;\r\n if (this._logToFile) {\r\n this._storeToDisk(args);\r\n }\r\n if (this._logToConsole) {\r\n console.warn(...args);\r\n }\r\n }\r\n\r\n static getInstance() {\r\n if (!InternalAzureLogger._instance) {\r\n InternalAzureLogger._instance = new InternalAzureLogger();\r\n }\r\n return InternalAzureLogger._instance;\r\n }\r\n\r\n private async _storeToDisk(args: any): Promise {\r\n let data = args + \"\\r\\n\";\r\n\r\n try {\r\n await FileSystemHelper.confirmDirExists(this._tempDir);\r\n }\r\n catch (err) {\r\n console.log(this.TAG, \"Failed to create directory for log file: \" + (err && err.message));\r\n return;\r\n }\r\n try {\r\n await FileSystemHelper.accessAsync(this._fileFullPath, fs.constants.F_OK);\r\n }\r\n catch (appendError) {\r\n // No file create one\r\n try {\r\n await FileSystemHelper.appendFileAsync(this._fileFullPath, data);\r\n return;\r\n }\r\n catch (err) {\r\n console.log(this.TAG, \"Failed to put log into file: \" + (appendError && appendError.message));\r\n return;\r\n }\r\n }\r\n try {\r\n // Check size\r\n let size = await FileSystemHelper.getShallowFileSize(this._fileFullPath);\r\n if (size > this.maxSizeBytes) {\r\n await this._createBackupFile(data);\r\n }\r\n else {\r\n await FileSystemHelper.appendFileAsync(this._fileFullPath, data);\r\n }\r\n }\r\n catch (err) {\r\n console.log(this.TAG, \"Failed to create backup file: \" + (err && err.message));\r\n }\r\n }\r\n\r\n private async _createBackupFile(data: string): Promise {\r\n try {\r\n let buffer = await FileSystemHelper.readFileAsync(this._fileFullPath);\r\n let backupPath = path.join(this._tempDir, new Date().getTime() + \".\" + this._logFileName);\r\n await FileSystemHelper.writeFileAsync(backupPath, buffer);\r\n }\r\n catch (err) {\r\n console.log(\"Failed to generate backup log file\", err);\r\n }\r\n finally {\r\n // Store logs\r\n FileSystemHelper.writeFileAsync(this._fileFullPath, data);\r\n }\r\n }\r\n\r\n private async _fileCleanupTask(): Promise {\r\n try {\r\n let files = await FileSystemHelper.readdirAsync(this._tempDir);\r\n // Filter only backup files\r\n files = files.filter(f => path.basename(f).indexOf(this._backUpNameFormat) > -1);\r\n // Sort by creation date\r\n files.sort((a: string, b: String) => {\r\n // Check expiration\r\n let aCreationDate: Date = new Date(parseInt(a.split(this._backUpNameFormat)[0]));\r\n let bCreationDate: Date = new Date(parseInt(b.split(this._backUpNameFormat)[0]));\r\n if (aCreationDate < bCreationDate) {\r\n return -1;\r\n }\r\n if (aCreationDate >= bCreationDate) {\r\n return 1;\r\n }\r\n });\r\n let totalFiles = files.length;\r\n for (let i = 0; i < totalFiles - this.maxHistory; i++) {\r\n let pathToDelete = path.join(this._tempDir, files[i]);\r\n await FileSystemHelper.unlinkAsync(pathToDelete);\r\n }\r\n }\r\n catch (err) {\r\n console.log(this.TAG, \"Failed to cleanup log files: \" + (err && err.message));\r\n }\r\n }\r\n}\r\n\r\nexport = InternalAzureLogger;"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/JsonConfig.d.ts b/node_modules/applicationinsights/out/Library/JsonConfig.d.ts new file mode 100644 index 0000000..e701e80 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/JsonConfig.d.ts @@ -0,0 +1,53 @@ +import { IJsonConfig } from "../Declarations/Interfaces"; +import { DistributedTracingModes } from "../applicationinsights"; +import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance"; +export declare class JsonConfig implements IJsonConfig { + private static _instance; + connectionString: string; + instrumentationKey: string; + endpointUrl: string; + maxBatchSize: number; + maxBatchIntervalMs: number; + disableAppInsights: boolean; + samplingPercentage: number; + correlationIdRetryIntervalMs: number; + correlationHeaderExcludedDomains: string[]; + proxyHttpUrl: string; + proxyHttpsUrl: string; + ignoreLegacyHeaders: boolean; + distributedTracingMode: DistributedTracingModes; + enableAutoCollectExternalLoggers: boolean; + enableAutoCollectConsole: boolean; + enableAutoCollectExceptions: boolean; + enableAutoCollectPerformance: boolean; + enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics; + enableAutoCollectPreAggregatedMetrics: boolean; + enableAutoCollectHeartbeat: boolean; + enableAutoCollectRequests: boolean; + enableAutoCollectDependencies: boolean; + enableAutoDependencyCorrelation: boolean; + enableAutoCollectIncomingRequestAzureFunctions: boolean; + enableUseAsyncHooks: boolean; + enableUseDiskRetryCaching: boolean; + enableResendInterval: number; + enableMaxBytesOnDisk: number; + enableInternalDebugLogging: boolean; + enableInternalWarningLogging: boolean; + enableSendLiveMetrics: boolean; + disableAllExtendedMetrics: boolean; + extendedMetricDisablers: string; + disableStatsbeat: boolean; + noDiagnosticChannel: boolean; + noPatchModules: string; + noHttpAgentKeepAlive: boolean; + quickPulseHost: string; + enableWebInstrumentation: boolean; + webInstrumentationConnectionString: string; + webInstrumentationConfig: any; + webInstrumentationSrc: string; + enableAutoWebSnippetInjection: boolean; + webSnippetConnectionString: string; + static getInstance(): JsonConfig; + constructor(); + private _loadJsonFile; +} diff --git a/node_modules/applicationinsights/out/Library/JsonConfig.js b/node_modules/applicationinsights/out/Library/JsonConfig.js new file mode 100644 index 0000000..6ef2f8a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/JsonConfig.js @@ -0,0 +1,168 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonConfig = void 0; +var fs = require("fs"); +var path = require("path"); +var Logging = require("./Logging"); +var ENV_CONFIGURATION_FILE = "APPLICATIONINSIGHTS_CONFIGURATION_FILE"; +// Azure Connection String +var ENV_connectionString = "APPLICATIONINSIGHTS_CONNECTION_STRING"; +// Instrumentation Key +var ENV_azurePrefix = "APPSETTING_"; // Azure adds this prefix to all environment variables +var ENV_instrumentationKey = "APPINSIGHTS_INSTRUMENTATIONKEY"; +var ENV_legacyInstrumentationKey = "APPINSIGHTS_INSTRUMENTATION_KEY"; +// Native Metrics Opt Outs +var ENV_nativeMetricsDisablers = "APPLICATION_INSIGHTS_DISABLE_EXTENDED_METRIC"; +var ENV_nativeMetricsDisableAll = "APPLICATION_INSIGHTS_DISABLE_ALL_EXTENDED_METRICS"; +var ENV_http_proxy = "http_proxy"; +var ENV_https_proxy = "https_proxy"; +var ENV_noDiagnosticChannel = "APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL"; +var ENV_noStatsbeat = "APPLICATION_INSIGHTS_NO_STATSBEAT"; +var ENV_noHttpAgentKeepAlive = "APPLICATION_INSIGHTS_NO_HTTP_AGENT_KEEP_ALIVE"; +var ENV_noPatchModules = "APPLICATION_INSIGHTS_NO_PATCH_MODULES"; +var ENV_webInstrumentationEnable = "APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_ENABLED"; +var ENV_webInstrumentation_connectionString = "APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_CONNECTION_STRING"; +var ENV_webInstrumentation_source = "APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE"; +// Old web instrumentation env variables are to be deprecated +// Those env variables will NOT be exposed in doc after version 2.3.5 +var ENV_webSnippetEnable = "APPLICATIONINSIGHTS_WEB_SNIPPET_ENABLED"; +var ENV_webSnippet_connectionString = "APPLICATIONINSIGHTS_WEB_SNIPPET_CONNECTION_STRING"; +var JsonConfig = /** @class */ (function () { + function JsonConfig() { + // Load env variables first + this.connectionString = process.env[ENV_connectionString]; + this.instrumentationKey = process.env[ENV_instrumentationKey] + || process.env[ENV_azurePrefix + ENV_instrumentationKey] + || process.env[ENV_legacyInstrumentationKey] + || process.env[ENV_azurePrefix + ENV_legacyInstrumentationKey]; + if (!this.connectionString && this.instrumentationKey) { + Logging.warn("APPINSIGHTS_INSTRUMENTATIONKEY is in path of deprecation, please use APPLICATIONINSIGHTS_CONNECTION_STRING env variable to setup the SDK."); + } + this.disableAllExtendedMetrics = !!process.env[ENV_nativeMetricsDisableAll]; + this.extendedMetricDisablers = process.env[ENV_nativeMetricsDisablers]; + this.proxyHttpUrl = process.env[ENV_http_proxy]; + this.proxyHttpsUrl = process.env[ENV_https_proxy]; + this.noDiagnosticChannel = !!process.env[ENV_noDiagnosticChannel]; + this.disableStatsbeat = !!process.env[ENV_noStatsbeat]; + this.noHttpAgentKeepAlive = !!process.env[ENV_noHttpAgentKeepAlive]; + this.noPatchModules = process.env[ENV_noPatchModules] || ""; + this.enableWebInstrumentation = !!process.env[ENV_webInstrumentationEnable] || !!process.env[ENV_webSnippetEnable]; + this.webInstrumentationSrc = process.env[ENV_webInstrumentation_source] || ""; + this.webInstrumentationConnectionString = process.env[ENV_webInstrumentation_connectionString] || process.env[ENV_webSnippet_connectionString] || ""; + this.enableAutoWebSnippetInjection = this.enableWebInstrumentation; + this.webSnippetConnectionString = this.webInstrumentationConnectionString; + this._loadJsonFile(); + } + JsonConfig.getInstance = function () { + if (!JsonConfig._instance) { + JsonConfig._instance = new JsonConfig(); + } + return JsonConfig._instance; + }; + JsonConfig.prototype._loadJsonFile = function () { + var configFileName = "applicationinsights.json"; + var rootPath = path.join(__dirname, "../../"); // Root of applicationinsights folder (__dirname = ../out/Library) + var tempDir = path.join(rootPath, configFileName); // default + var configFile = process.env[ENV_CONFIGURATION_FILE]; + if (configFile) { + if (path.isAbsolute(configFile)) { + tempDir = configFile; + } + else { + tempDir = path.join(rootPath, configFile); // Relative path to applicationinsights folder + } + } + try { + var jsonConfig = JSON.parse(fs.readFileSync(tempDir, "utf8")); + if (jsonConfig.disableStatsbeat != undefined) { + this.disableStatsbeat = jsonConfig.disableStatsbeat; + } + if (jsonConfig.disableAllExtendedMetrics != undefined) { + this.disableAllExtendedMetrics = jsonConfig.disableStatsbeat; + } + if (jsonConfig.noDiagnosticChannel != undefined) { + this.noDiagnosticChannel = jsonConfig.noDiagnosticChannel; + } + if (jsonConfig.noHttpAgentKeepAlive != undefined) { + this.noHttpAgentKeepAlive = jsonConfig.noHttpAgentKeepAlive; + } + if (jsonConfig.connectionString != undefined) { + this.connectionString = jsonConfig.connectionString; + } + if (jsonConfig.extendedMetricDisablers != undefined) { + this.extendedMetricDisablers = jsonConfig.extendedMetricDisablers; + } + if (jsonConfig.noDiagnosticChannel != undefined) { + this.noDiagnosticChannel = jsonConfig.noDiagnosticChannel; + } + if (jsonConfig.proxyHttpUrl != undefined) { + this.proxyHttpUrl = jsonConfig.proxyHttpUrl; + } + if (jsonConfig.proxyHttpsUrl != undefined) { + this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl; + } + if (jsonConfig.proxyHttpsUrl != undefined) { + this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl; + } + if (jsonConfig.noPatchModules != undefined) { + this.noPatchModules = jsonConfig.noPatchModules; + } + if (jsonConfig.enableAutoWebSnippetInjection != undefined) { + this.enableWebInstrumentation = jsonConfig.enableAutoWebSnippetInjection; + this.enableAutoWebSnippetInjection = this.enableWebInstrumentation; + } + if (jsonConfig.enableWebInstrumentation != undefined) { + this.enableWebInstrumentation = jsonConfig.enableWebInstrumentation; + this.enableAutoWebSnippetInjection = this.enableWebInstrumentation; + } + if (jsonConfig.webSnippetConnectionString != undefined) { + this.webInstrumentationConnectionString = jsonConfig.webSnippetConnectionString; + this.webSnippetConnectionString = this.webInstrumentationConnectionString; + } + if (jsonConfig.webInstrumentationConnectionString != undefined) { + this.webInstrumentationConnectionString = jsonConfig.webInstrumentationConnectionString; + this.webSnippetConnectionString = this.webInstrumentationConnectionString; + } + if (jsonConfig.webInstrumentationConfig != undefined) { + this.webInstrumentationConfig = jsonConfig.webInstrumentationConfig; + } + if (jsonConfig.webInstrumentationSrc != undefined) { + this.webInstrumentationSrc = jsonConfig.webInstrumentationSrc; + } + this.endpointUrl = jsonConfig.endpointUrl; + this.maxBatchSize = jsonConfig.maxBatchSize; + this.maxBatchIntervalMs = jsonConfig.maxBatchIntervalMs; + this.disableAppInsights = jsonConfig.disableAppInsights; + this.samplingPercentage = jsonConfig.samplingPercentage; + this.correlationIdRetryIntervalMs = jsonConfig.correlationIdRetryIntervalMs; + this.correlationHeaderExcludedDomains = jsonConfig.correlationHeaderExcludedDomains; + this.ignoreLegacyHeaders = jsonConfig.ignoreLegacyHeaders; + this.distributedTracingMode = jsonConfig.distributedTracingMode; + this.enableAutoCollectExternalLoggers = jsonConfig.enableAutoCollectExternalLoggers; + this.enableAutoCollectConsole = jsonConfig.enableAutoCollectConsole; + this.enableAutoCollectExceptions = jsonConfig.enableAutoCollectExceptions; + this.enableAutoCollectPerformance = jsonConfig.enableAutoCollectPerformance; + this.enableAutoCollectExtendedMetrics = jsonConfig.enableAutoCollectExtendedMetrics; + this.enableAutoCollectPreAggregatedMetrics = jsonConfig.enableAutoCollectPreAggregatedMetrics; + this.enableAutoCollectHeartbeat = jsonConfig.enableAutoCollectHeartbeat; + this.enableAutoCollectRequests = jsonConfig.enableAutoCollectRequests; + this.enableAutoCollectDependencies = jsonConfig.enableAutoCollectDependencies; + this.enableAutoDependencyCorrelation = jsonConfig.enableAutoDependencyCorrelation; + this.enableAutoCollectIncomingRequestAzureFunctions = jsonConfig.enableAutoCollectIncomingRequestAzureFunctions; + this.enableUseAsyncHooks = jsonConfig.enableUseAsyncHooks; + this.enableUseDiskRetryCaching = jsonConfig.enableUseDiskRetryCaching; + this.enableResendInterval = jsonConfig.enableResendInterval; + this.enableMaxBytesOnDisk = jsonConfig.enableMaxBytesOnDisk; + this.enableInternalDebugLogging = jsonConfig.enableInternalDebugLogging; + this.enableInternalWarningLogging = jsonConfig.enableInternalWarningLogging; + this.enableSendLiveMetrics = jsonConfig.enableSendLiveMetrics; + this.quickPulseHost = jsonConfig.quickPulseHost; + } + catch (err) { + Logging.info("Missing or invalid JSON config file: ", err); + } + }; + return JsonConfig; +}()); +exports.JsonConfig = JsonConfig; +//# sourceMappingURL=JsonConfig.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/JsonConfig.js.map b/node_modules/applicationinsights/out/Library/JsonConfig.js.map new file mode 100644 index 0000000..e682339 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/JsonConfig.js.map @@ -0,0 +1 @@ +{"version":3,"file":"JsonConfig.js","sourceRoot":"","sources":["../../Library/JsonConfig.ts"],"names":[],"mappings":";;;AAAA,uBAA0B;AAC1B,2BAA8B;AAE9B,mCAAsC;AAKtC,IAAM,sBAAsB,GAAG,wCAAwC,CAAC;AACxE,0BAA0B;AAC1B,IAAM,oBAAoB,GAAG,uCAAuC,CAAC;AACrE,sBAAsB;AACtB,IAAM,eAAe,GAAG,aAAa,CAAC,CAAC,sDAAsD;AAC7F,IAAM,sBAAsB,GAAG,gCAAgC,CAAC;AAChE,IAAM,4BAA4B,GAAG,iCAAiC,CAAA;AACtE,0BAA0B;AAC1B,IAAM,0BAA0B,GAAG,8CAA8C,CAAC;AAClF,IAAM,2BAA2B,GAAG,mDAAmD,CAAA;AACvF,IAAM,cAAc,GAAG,YAAY,CAAC;AACpC,IAAM,eAAe,GAAG,aAAa,CAAC;AACtC,IAAM,uBAAuB,GAAG,4CAA4C,CAAA;AAC5E,IAAM,eAAe,GAAG,mCAAmC,CAAC;AAC5D,IAAM,wBAAwB,G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C,CAAC;YAChH,IAAI,CAAC,mBAAmB,GAAG,UAAU,CAAC,mBAAmB,CAAC;YAC1D,IAAI,CAAC,yBAAyB,GAAG,UAAU,CAAC,yBAAyB,CAAC;YACtE,IAAI,CAAC,oBAAoB,GAAG,UAAU,CAAC,oBAAoB,CAAC;YAC5D,IAAI,CAAC,oBAAoB,GAAG,UAAU,CAAC,oBAAoB,CAAC;YAC5D,IAAI,CAAC,0BAA0B,GAAG,UAAU,CAAC,0BAA0B,CAAC;YACxE,IAAI,CAAC,4BAA4B,GAAG,UAAU,CAAC,4BAA4B,CAAC;YAC5E,IAAI,CAAC,qBAAqB,GAAG,UAAU,CAAC,qBAAqB,CAAC;YAC9D,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;SACnD;QACD,OAAO,GAAG,EAAE;YACR,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,GAAG,CAAC,CAAC;SAC9D;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AA7LD,IA6LC;AA7LY,gCAAU","sourcesContent":["import fs = require(\"fs\");\r\nimport path = require(\"path\");\r\n\r\nimport Logging = require(\"./Logging\");\r\nimport { IJsonConfig } from \"../Declarations/Interfaces\";\r\nimport { DistributedTracingModes } from \"../applicationinsights\";\r\nimport { IDisabledExtendedMetrics } from \"../AutoCollection/NativePerformance\";\r\n\r\nconst ENV_CONFIGURATION_FILE = \"APPLICATIONINSIGHTS_CONFIGURATION_FILE\";\r\n// Azure Connection String\r\nconst ENV_connectionString = \"APPLICATIONINSIGHTS_CONNECTION_STRING\";\r\n// Instrumentation Key\r\nconst ENV_azurePrefix = \"APPSETTING_\"; // Azure adds this prefix to all environment variables\r\nconst ENV_instrumentationKey = \"APPINSIGHTS_INSTRUMENTATIONKEY\";\r\nconst ENV_legacyInstrumentationKey = \"APPINSIGHTS_INSTRUMENTATION_KEY\"\r\n// Native Metrics Opt Outs\r\nconst ENV_nativeMetricsDisablers = \"APPLICATION_INSIGHTS_DISABLE_EXTENDED_METRIC\";\r\nconst ENV_nativeMetricsDisableAll = \"APPLICATION_INSIGHTS_DISABLE_ALL_EXTENDED_METRICS\"\r\nconst ENV_http_proxy = \"http_proxy\";\r\nconst ENV_https_proxy = \"https_proxy\";\r\nconst ENV_noDiagnosticChannel = \"APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL\"\r\nconst ENV_noStatsbeat = \"APPLICATION_INSIGHTS_NO_STATSBEAT\";\r\nconst ENV_noHttpAgentKeepAlive = \"APPLICATION_INSIGHTS_NO_HTTP_AGENT_KEEP_ALIVE\";\r\nconst ENV_noPatchModules = \"APPLICATION_INSIGHTS_NO_PATCH_MODULES\";\r\nconst ENV_webInstrumentationEnable = \"APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_ENABLED\";\r\nconst ENV_webInstrumentation_connectionString = \"APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_CONNECTION_STRING\";\r\nconst ENV_webInstrumentation_source = \"APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE\";\r\n\r\n// Old web instrumentation env variables are to be deprecated\r\n// Those env variables will NOT be exposed in doc after version 2.3.5\r\nconst ENV_webSnippetEnable = \"APPLICATIONINSIGHTS_WEB_SNIPPET_ENABLED\";\r\nconst ENV_webSnippet_connectionString = \"APPLICATIONINSIGHTS_WEB_SNIPPET_CONNECTION_STRING\";\r\n\r\nexport class JsonConfig implements IJsonConfig {\r\n private static _instance: JsonConfig;\r\n\r\n public connectionString: string;\r\n public instrumentationKey: string;\r\n public endpointUrl: string;\r\n public maxBatchSize: number;\r\n public maxBatchIntervalMs: number;\r\n public disableAppInsights: boolean;\r\n public samplingPercentage: number;\r\n public correlationIdRetryIntervalMs: number;\r\n public correlationHeaderExcludedDomains: string[];\r\n public proxyHttpUrl: string;\r\n public proxyHttpsUrl: string;\r\n public ignoreLegacyHeaders: boolean;\r\n public distributedTracingMode: DistributedTracingModes;\r\n public enableAutoCollectExternalLoggers: boolean;\r\n public enableAutoCollectConsole: boolean;\r\n public enableAutoCollectExceptions: boolean;\r\n public enableAutoCollectPerformance: boolean;\r\n public enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics;\r\n public enableAutoCollectPreAggregatedMetrics: boolean;\r\n public enableAutoCollectHeartbeat: boolean;\r\n public enableAutoCollectRequests: boolean;\r\n public enableAutoCollectDependencies: boolean;\r\n public enableAutoDependencyCorrelation: boolean;\r\n public enableAutoCollectIncomingRequestAzureFunctions: boolean;\r\n public enableUseAsyncHooks: boolean;\r\n public enableUseDiskRetryCaching: boolean;\r\n public enableResendInterval: number;\r\n public enableMaxBytesOnDisk: number;\r\n public enableInternalDebugLogging: boolean;\r\n public enableInternalWarningLogging: boolean;\r\n public enableSendLiveMetrics: boolean;\r\n public disableAllExtendedMetrics: boolean;\r\n public extendedMetricDisablers: string;\r\n public disableStatsbeat: boolean;\r\n public noDiagnosticChannel: boolean;\r\n public noPatchModules: string;\r\n public noHttpAgentKeepAlive: boolean;\r\n public quickPulseHost: string;\r\n public enableWebInstrumentation: boolean;\r\n public webInstrumentationConnectionString: string;\r\n public webInstrumentationConfig: any;\r\n public webInstrumentationSrc: string;\r\n\r\n // the following features are to be deprecated\r\n // Those env variables will NOT be exposed in doc after version 2.3.5\r\n public enableAutoWebSnippetInjection: boolean;\r\n public webSnippetConnectionString: string;\r\n\r\n static getInstance() {\r\n if (!JsonConfig._instance) {\r\n JsonConfig._instance = new JsonConfig();\r\n }\r\n return JsonConfig._instance;\r\n }\r\n\r\n constructor() {\r\n // Load env variables first\r\n this.connectionString = process.env[ENV_connectionString];\r\n this.instrumentationKey = process.env[ENV_instrumentationKey]\r\n || process.env[ENV_azurePrefix + ENV_instrumentationKey]\r\n || process.env[ENV_legacyInstrumentationKey]\r\n || process.env[ENV_azurePrefix + ENV_legacyInstrumentationKey];\r\n\r\n if (!this.connectionString && this.instrumentationKey) {\r\n Logging.warn(\"APPINSIGHTS_INSTRUMENTATIONKEY is in path of deprecation, please use APPLICATIONINSIGHTS_CONNECTION_STRING env variable to setup the SDK.\");\r\n }\r\n this.disableAllExtendedMetrics = !!process.env[ENV_nativeMetricsDisableAll];\r\n this.extendedMetricDisablers = process.env[ENV_nativeMetricsDisablers];\r\n this.proxyHttpUrl = process.env[ENV_http_proxy];\r\n this.proxyHttpsUrl = process.env[ENV_https_proxy];\r\n this.noDiagnosticChannel = !!process.env[ENV_noDiagnosticChannel];\r\n this.disableStatsbeat = !!process.env[ENV_noStatsbeat];\r\n this.noHttpAgentKeepAlive = !!process.env[ENV_noHttpAgentKeepAlive];\r\n this.noPatchModules = process.env[ENV_noPatchModules] || \"\";\r\n this.enableWebInstrumentation = !!process.env[ENV_webInstrumentationEnable] || !!process.env[ENV_webSnippetEnable];\r\n this.webInstrumentationSrc = process.env[ENV_webInstrumentation_source] || \"\";\r\n this.webInstrumentationConnectionString = process.env[ENV_webInstrumentation_connectionString] || process.env[ENV_webSnippet_connectionString] || \"\";\r\n this.enableAutoWebSnippetInjection = this.enableWebInstrumentation;\r\n this.webSnippetConnectionString = this.webInstrumentationConnectionString;\r\n this._loadJsonFile();\r\n }\r\n\r\n private _loadJsonFile() {\r\n let configFileName = \"applicationinsights.json\";\r\n let rootPath = path.join(__dirname, \"../../\"); // Root of applicationinsights folder (__dirname = ../out/Library)\r\n let tempDir = path.join(rootPath, configFileName); // default\r\n let configFile = process.env[ENV_CONFIGURATION_FILE];\r\n if (configFile) {\r\n if (path.isAbsolute(configFile)) {\r\n tempDir = configFile;\r\n }\r\n else {\r\n tempDir = path.join(rootPath, configFile);// Relative path to applicationinsights folder\r\n }\r\n }\r\n try {\r\n const jsonConfig: IJsonConfig = JSON.parse(fs.readFileSync(tempDir, \"utf8\"));\r\n if (jsonConfig.disableStatsbeat != undefined) {\r\n this.disableStatsbeat = jsonConfig.disableStatsbeat;\r\n }\r\n if (jsonConfig.disableAllExtendedMetrics != undefined) {\r\n this.disableAllExtendedMetrics = jsonConfig.disableStatsbeat;\r\n }\r\n if (jsonConfig.noDiagnosticChannel != undefined) {\r\n this.noDiagnosticChannel = jsonConfig.noDiagnosticChannel;\r\n }\r\n if (jsonConfig.noHttpAgentKeepAlive != undefined) {\r\n this.noHttpAgentKeepAlive = jsonConfig.noHttpAgentKeepAlive;\r\n }\r\n if (jsonConfig.connectionString != undefined) {\r\n this.connectionString = jsonConfig.connectionString;\r\n }\r\n if (jsonConfig.extendedMetricDisablers != undefined) {\r\n this.extendedMetricDisablers = jsonConfig.extendedMetricDisablers;\r\n }\r\n if (jsonConfig.noDiagnosticChannel != undefined) {\r\n this.noDiagnosticChannel = jsonConfig.noDiagnosticChannel;\r\n }\r\n if (jsonConfig.proxyHttpUrl != undefined) {\r\n this.proxyHttpUrl = jsonConfig.proxyHttpUrl;\r\n }\r\n if (jsonConfig.proxyHttpsUrl != undefined) {\r\n this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl;\r\n }\r\n if (jsonConfig.proxyHttpsUrl != undefined) {\r\n this.proxyHttpsUrl = jsonConfig.proxyHttpsUrl;\r\n }\r\n if (jsonConfig.noPatchModules != undefined) {\r\n this.noPatchModules = jsonConfig.noPatchModules;\r\n }\r\n if (jsonConfig.enableAutoWebSnippetInjection != undefined) {\r\n this.enableWebInstrumentation = jsonConfig.enableAutoWebSnippetInjection;\r\n this.enableAutoWebSnippetInjection = this.enableWebInstrumentation;\r\n }\r\n if (jsonConfig.enableWebInstrumentation != undefined) {\r\n this.enableWebInstrumentation = jsonConfig.enableWebInstrumentation;\r\n this.enableAutoWebSnippetInjection = this.enableWebInstrumentation;\r\n }\r\n if (jsonConfig.webSnippetConnectionString != undefined) {\r\n this.webInstrumentationConnectionString = jsonConfig.webSnippetConnectionString;\r\n this.webSnippetConnectionString = this.webInstrumentationConnectionString;\r\n }\r\n if (jsonConfig.webInstrumentationConnectionString != undefined) {\r\n this.webInstrumentationConnectionString = jsonConfig.webInstrumentationConnectionString;\r\n this.webSnippetConnectionString = this.webInstrumentationConnectionString;\r\n }\r\n if (jsonConfig.webInstrumentationConfig != undefined) {\r\n this.webInstrumentationConfig = jsonConfig.webInstrumentationConfig;\r\n }\r\n if (jsonConfig.webInstrumentationSrc != undefined) {\r\n this.webInstrumentationSrc = jsonConfig.webInstrumentationSrc;\r\n }\r\n\r\n this.endpointUrl = jsonConfig.endpointUrl;\r\n this.maxBatchSize = jsonConfig.maxBatchSize;\r\n this.maxBatchIntervalMs = jsonConfig.maxBatchIntervalMs;\r\n this.disableAppInsights = jsonConfig.disableAppInsights;\r\n this.samplingPercentage = jsonConfig.samplingPercentage;\r\n this.correlationIdRetryIntervalMs = jsonConfig.correlationIdRetryIntervalMs;\r\n this.correlationHeaderExcludedDomains = jsonConfig.correlationHeaderExcludedDomains;\r\n this.ignoreLegacyHeaders = jsonConfig.ignoreLegacyHeaders;\r\n this.distributedTracingMode = jsonConfig.distributedTracingMode;\r\n this.enableAutoCollectExternalLoggers = jsonConfig.enableAutoCollectExternalLoggers;\r\n this.enableAutoCollectConsole = jsonConfig.enableAutoCollectConsole;\r\n this.enableAutoCollectExceptions = jsonConfig.enableAutoCollectExceptions;\r\n this.enableAutoCollectPerformance = jsonConfig.enableAutoCollectPerformance;\r\n this.enableAutoCollectExtendedMetrics = jsonConfig.enableAutoCollectExtendedMetrics;\r\n this.enableAutoCollectPreAggregatedMetrics = jsonConfig.enableAutoCollectPreAggregatedMetrics;\r\n this.enableAutoCollectHeartbeat = jsonConfig.enableAutoCollectHeartbeat;\r\n this.enableAutoCollectRequests = jsonConfig.enableAutoCollectRequests;\r\n this.enableAutoCollectDependencies = jsonConfig.enableAutoCollectDependencies;\r\n this.enableAutoDependencyCorrelation = jsonConfig.enableAutoDependencyCorrelation;\r\n this.enableAutoCollectIncomingRequestAzureFunctions = jsonConfig.enableAutoCollectIncomingRequestAzureFunctions;\r\n this.enableUseAsyncHooks = jsonConfig.enableUseAsyncHooks;\r\n this.enableUseDiskRetryCaching = jsonConfig.enableUseDiskRetryCaching;\r\n this.enableResendInterval = jsonConfig.enableResendInterval;\r\n this.enableMaxBytesOnDisk = jsonConfig.enableMaxBytesOnDisk;\r\n this.enableInternalDebugLogging = jsonConfig.enableInternalDebugLogging;\r\n this.enableInternalWarningLogging = jsonConfig.enableInternalWarningLogging;\r\n this.enableSendLiveMetrics = jsonConfig.enableSendLiveMetrics;\r\n this.quickPulseHost = jsonConfig.quickPulseHost;\r\n }\r\n catch (err) {\r\n Logging.info(\"Missing or invalid JSON config file: \", err);\r\n }\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Logging.d.ts b/node_modules/applicationinsights/out/Library/Logging.d.ts new file mode 100644 index 0000000..3cbd42b --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Logging.d.ts @@ -0,0 +1,8 @@ +declare class Logging { + static enableDebug: boolean; + static disableWarnings: boolean; + private static TAG; + static info(message?: any, ...optionalParams: any[]): void; + static warn(message?: any, ...optionalParams: any[]): void; +} +export = Logging; diff --git a/node_modules/applicationinsights/out/Library/Logging.js b/node_modules/applicationinsights/out/Library/Logging.js new file mode 100644 index 0000000..2e4dafc --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Logging.js @@ -0,0 +1,30 @@ +"use strict"; +var InternalAzureLogger = require("./InternalAzureLogger"); +var Logging = /** @class */ (function () { + function Logging() { + } + Logging.info = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + if (this.enableDebug) { + InternalAzureLogger.getInstance().info(this.TAG + message, optionalParams); + } + }; + Logging.warn = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + if (!this.disableWarnings) { + InternalAzureLogger.getInstance().warning(this.TAG + message, optionalParams); + } + }; + Logging.enableDebug = false; + Logging.disableWarnings = false; + Logging.TAG = "ApplicationInsights:"; + return Logging; +}()); +module.exports = Logging; +//# sourceMappingURL=Logging.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Logging.js.map b/node_modules/applicationinsights/out/Library/Logging.js.map new file mode 100644 index 0000000..7fc2437 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Logging.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Logging.js","sourceRoot":"","sources":["../../Library/Logging.ts"],"names":[],"mappings":";AAAA,2DAA8D;AAE9D;IAAA;IAiBA,CAAC;IAXiB,YAAI,GAAlB,UAAmB,OAAa;QAAE,wBAAwB;aAAxB,UAAwB,EAAxB,qBAAwB,EAAxB,IAAwB;YAAxB,uCAAwB;;QACtD,IAAI,IAAI,CAAC,WAAW,EAAE;YAClB,mBAAmB,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,EAAE,cAAc,CAAC,CAAC;SAC9E;IACL,CAAC;IAEa,YAAI,GAAlB,UAAmB,OAAa;QAAE,wBAAwB;aAAxB,UAAwB,EAAxB,qBAAwB,EAAxB,IAAwB;YAAxB,uCAAwB;;QACtD,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACvB,mBAAmB,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,EAAE,cAAc,CAAC,CAAC;SACjF;IACL,CAAC;IAfa,mBAAW,GAAG,KAAK,CAAC;IACpB,uBAAe,GAAG,KAAK,CAAC;IAEvB,WAAG,GAAG,sBAAsB,CAAC;IAahD,cAAC;CAAA,AAjBD,IAiBC;AAED,iBAAS,OAAO,CAAC","sourcesContent":["import InternalAzureLogger = require(\"./InternalAzureLogger\");\r\n\r\nclass Logging {\r\n public static enableDebug = false;\r\n public static disableWarnings = false;\r\n\r\n private static TAG = \"ApplicationInsights:\";\r\n\r\n public static info(message?: any, ...optionalParams: any[]) {\r\n if (this.enableDebug) {\r\n InternalAzureLogger.getInstance().info(this.TAG + message, optionalParams);\r\n }\r\n }\r\n\r\n public static warn(message?: any, ...optionalParams: any[]) {\r\n if (!this.disableWarnings) {\r\n InternalAzureLogger.getInstance().warning(this.TAG + message, optionalParams);\r\n }\r\n }\r\n}\r\n\r\nexport = Logging;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/NodeClient.d.ts b/node_modules/applicationinsights/out/Library/NodeClient.d.ts new file mode 100644 index 0000000..2b75a5c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/NodeClient.d.ts @@ -0,0 +1,30 @@ +import TelemetryClient = require("./TelemetryClient"); +import Contracts = require("../Declarations/Contracts"); +/** + * Application Insights Telemetry Client for Node.JS. Provides the Application Insights TelemetryClient API + * in addition to Node-specific helper functions. + * Construct a new TelemetryClient to have an instance with a different configuration than the default client. + * In most cases, `appInsights.defaultClient` should be used instead. + */ +declare class NodeClient extends TelemetryClient { + /** + * Log RequestTelemetry from HTTP request and response. This method will log immediately without waiting for request completion + * and it requires duration parameter to be specified on NodeHttpRequestTelemetry object. + * Use trackNodeHttpRequest function to log the telemetry after request completion + * @param telemetry Object encapsulating incoming request, response and duration information + */ + trackNodeHttpRequestSync(telemetry: Contracts.NodeHttpRequestTelemetry): void; + /** + * Log RequestTelemetry from HTTP request and response. This method will `follow` the request to completion. + * Use trackNodeHttpRequestSync function to log telemetry immediately without waiting for request completion + * @param telemetry Object encapsulating incoming request and response information + */ + trackNodeHttpRequest(telemetry: Contracts.NodeHttpRequestTelemetry): void; + /** + * Log DependencyTelemetry from outgoing HTTP request. This method will instrument the outgoing request and append + * the specified headers and will log the telemetry when outgoing request is complete + * @param telemetry Object encapsulating outgoing request information + */ + trackNodeHttpDependency(telemetry: Contracts.NodeHttpDependencyTelemetry): void; +} +export = NodeClient; diff --git a/node_modules/applicationinsights/out/Library/NodeClient.js b/node_modules/applicationinsights/out/Library/NodeClient.js new file mode 100644 index 0000000..79fa50c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/NodeClient.js @@ -0,0 +1,76 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var TelemetryClient = require("./TelemetryClient"); +var ServerRequestTracking = require("../AutoCollection/HttpRequests"); +var ClientRequestTracking = require("../AutoCollection/HttpDependencies"); +var Logging = require("./Logging"); +/** + * Application Insights Telemetry Client for Node.JS. Provides the Application Insights TelemetryClient API + * in addition to Node-specific helper functions. + * Construct a new TelemetryClient to have an instance with a different configuration than the default client. + * In most cases, `appInsights.defaultClient` should be used instead. + */ +var NodeClient = /** @class */ (function (_super) { + __extends(NodeClient, _super); + function NodeClient() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Log RequestTelemetry from HTTP request and response. This method will log immediately without waiting for request completion + * and it requires duration parameter to be specified on NodeHttpRequestTelemetry object. + * Use trackNodeHttpRequest function to log the telemetry after request completion + * @param telemetry Object encapsulating incoming request, response and duration information + */ + NodeClient.prototype.trackNodeHttpRequestSync = function (telemetry) { + if (telemetry && telemetry.request && telemetry.response && telemetry.duration) { + ServerRequestTracking.trackRequestSync(this, telemetry); + } + else { + Logging.warn("trackNodeHttpRequestSync requires NodeHttpRequestTelemetry object with request, response and duration specified."); + } + }; + /** + * Log RequestTelemetry from HTTP request and response. This method will `follow` the request to completion. + * Use trackNodeHttpRequestSync function to log telemetry immediately without waiting for request completion + * @param telemetry Object encapsulating incoming request and response information + */ + NodeClient.prototype.trackNodeHttpRequest = function (telemetry) { + if (telemetry.duration || telemetry.error) { + Logging.warn("trackNodeHttpRequest will ignore supplied duration and error parameters. These values are collected from the request and response objects."); + } + if (telemetry && telemetry.request && telemetry.response) { + ServerRequestTracking.trackRequest(this, telemetry); + } + else { + Logging.warn("trackNodeHttpRequest requires NodeHttpRequestTelemetry object with request and response specified."); + } + }; + /** + * Log DependencyTelemetry from outgoing HTTP request. This method will instrument the outgoing request and append + * the specified headers and will log the telemetry when outgoing request is complete + * @param telemetry Object encapsulating outgoing request information + */ + NodeClient.prototype.trackNodeHttpDependency = function (telemetry) { + if (telemetry && telemetry.request) { + ClientRequestTracking.trackRequest(this, telemetry); + } + else { + Logging.warn("trackNodeHttpDependency requires NodeHttpDependencyTelemetry object with request specified."); + } + }; + return NodeClient; +}(TelemetryClient)); +module.exports = NodeClient; +//# sourceMappingURL=NodeClient.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/NodeClient.js.map b/node_modules/applicationinsights/out/Library/NodeClient.js.map new file mode 100644 index 0000000..dd18649 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/NodeClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"NodeClient.js","sourceRoot":"","sources":["../../Library/NodeClient.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAEA,mDAAsD;AACtD,sEAAyE;AACzE,0EAA6E;AAC7E,mCAAsC;AAGtC;;;;;GAKG;AACH;IAAyB,8BAAe;IAAxC;;IA6CA,CAAC;IA3CG;;;;;OAKG;IACI,6CAAwB,GAA/B,UAAgC,SAA6C;QACzE,IAAI,SAAS,IAAI,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,QAAQ,IAAI,SAAS,CAAC,QAAQ,EAAE;YAC5E,qBAAqB,CAAC,gBAAgB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAC3D;aAAM;YACH,OAAO,CAAC,IAAI,CAAC,kHAAkH,CAAC,CAAC;SACpI;IACL,CAAC;IAED;;;;OAIG;IACI,yCAAoB,GAA3B,UAA4B,SAA6C;QACrE,IAAI,SAAS,CAAC,QAAQ,IAAI,SAAS,CAAC,KAAK,EAAE;YACvC,OAAO,CAAC,IAAI,CAAC,4IAA4I,CAAC,CAAC;SAC9J;QACD,IAAI,SAAS,IAAI,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,QAAQ,EAAE;YACtD,qBAAqB,CAAC,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACvD;aAAM;YACH,OAAO,CAAC,IAAI,CAAC,oGAAoG,CAAC,CAAC;SACtH;IACL,CAAC;IAED;;;;OAIG;IACI,4CAAuB,GAA9B,UAA+B,SAAgD;QAC3E,IAAI,SAAS,IAAI,SAAS,CAAC,OAAO,EAAE;YAChC,qBAAqB,CAAC,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SACvD;aACI;YACD,OAAO,CAAC,IAAI,CAAC,6FAA6F,CAAC,CAAC;SAC/G;IACL,CAAC;IACL,iBAAC;AAAD,CAAC,AA7CD,CAAyB,eAAe,GA6CvC;AAED,iBAAS,UAAU,CAAA","sourcesContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport TelemetryClient = require(\"./TelemetryClient\");\r\nimport ServerRequestTracking = require(\"../AutoCollection/HttpRequests\");\r\nimport ClientRequestTracking = require(\"../AutoCollection/HttpDependencies\");\r\nimport Logging = require(\"./Logging\");\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\n\r\n/**\r\n * Application Insights Telemetry Client for Node.JS. Provides the Application Insights TelemetryClient API\r\n * in addition to Node-specific helper functions.\r\n * Construct a new TelemetryClient to have an instance with a different configuration than the default client.\r\n * In most cases, `appInsights.defaultClient` should be used instead.\r\n */\r\nclass NodeClient extends TelemetryClient {\r\n\r\n /**\r\n * Log RequestTelemetry from HTTP request and response. This method will log immediately without waiting for request completion\r\n * and it requires duration parameter to be specified on NodeHttpRequestTelemetry object.\r\n * Use trackNodeHttpRequest function to log the telemetry after request completion\r\n * @param telemetry Object encapsulating incoming request, response and duration information\r\n */\r\n public trackNodeHttpRequestSync(telemetry: Contracts.NodeHttpRequestTelemetry) {\r\n if (telemetry && telemetry.request && telemetry.response && telemetry.duration) {\r\n ServerRequestTracking.trackRequestSync(this, telemetry);\r\n } else {\r\n Logging.warn(\"trackNodeHttpRequestSync requires NodeHttpRequestTelemetry object with request, response and duration specified.\");\r\n }\r\n }\r\n\r\n /**\r\n * Log RequestTelemetry from HTTP request and response. This method will `follow` the request to completion.\r\n * Use trackNodeHttpRequestSync function to log telemetry immediately without waiting for request completion\r\n * @param telemetry Object encapsulating incoming request and response information\r\n */\r\n public trackNodeHttpRequest(telemetry: Contracts.NodeHttpRequestTelemetry) {\r\n if (telemetry.duration || telemetry.error) {\r\n Logging.warn(\"trackNodeHttpRequest will ignore supplied duration and error parameters. These values are collected from the request and response objects.\");\r\n }\r\n if (telemetry && telemetry.request && telemetry.response) {\r\n ServerRequestTracking.trackRequest(this, telemetry);\r\n } else {\r\n Logging.warn(\"trackNodeHttpRequest requires NodeHttpRequestTelemetry object with request and response specified.\");\r\n }\r\n }\r\n\r\n /**\r\n * Log DependencyTelemetry from outgoing HTTP request. This method will instrument the outgoing request and append\r\n * the specified headers and will log the telemetry when outgoing request is complete\r\n * @param telemetry Object encapsulating outgoing request information\r\n */\r\n public trackNodeHttpDependency(telemetry: Contracts.NodeHttpDependencyTelemetry) {\r\n if (telemetry && telemetry.request) {\r\n ClientRequestTracking.trackRequest(this, telemetry);\r\n }\r\n else {\r\n Logging.warn(\"trackNodeHttpDependency requires NodeHttpDependencyTelemetry object with request specified.\");\r\n }\r\n }\r\n}\r\n\r\nexport = NodeClient"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/PrefixHelper.d.ts b/node_modules/applicationinsights/out/Library/PrefixHelper.d.ts new file mode 100644 index 0000000..f566ec3 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/PrefixHelper.d.ts @@ -0,0 +1,19 @@ +export declare const isWindows: () => boolean; +export declare const isLinux: () => boolean; +export declare const isWebApp: () => boolean; +export declare const isFunctionApp: () => boolean; +/** + * Get prefix for OS + * Windows system: "w" + * Linux system: "l" + * non-Windows and non-Linux system: "u" (unknown) + */ +export declare const getOsPrefix: () => string; +/** + * TODO: add vm resource provider + * Get prefix resource provider, vm will considered as "unknown RP" + * Web App: "a" + * Function App: "f" + * non-Web and non-Function APP: "u" (unknown) + */ +export declare const getResourceProvider: () => string; diff --git a/node_modules/applicationinsights/out/Library/PrefixHelper.js b/node_modules/applicationinsights/out/Library/PrefixHelper.js new file mode 100644 index 0000000..85bbd0c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/PrefixHelper.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getResourceProvider = exports.getOsPrefix = exports.isFunctionApp = exports.isWebApp = exports.isLinux = exports.isWindows = void 0; +var isWindows = function () { + return process.platform === "win32"; +}; +exports.isWindows = isWindows; +var isLinux = function () { + return process.platform === "linux"; +}; +exports.isLinux = isLinux; +var isWebApp = function () { + return process.env.WEBSITE_SITE_NAME ? true : false; +}; +exports.isWebApp = isWebApp; +var isFunctionApp = function () { + return process.env.FUNCTIONS_WORKER_RUNTIME ? true : false; +}; +exports.isFunctionApp = isFunctionApp; +/** + * Get prefix for OS + * Windows system: "w" + * Linux system: "l" + * non-Windows and non-Linux system: "u" (unknown) + */ +var getOsPrefix = function () { + return exports.isWindows() ? "w" : exports.isLinux() ? "l" : "u"; +}; +exports.getOsPrefix = getOsPrefix; +/** + * TODO: add vm resource provider + * Get prefix resource provider, vm will considered as "unknown RP" + * Web App: "a" + * Function App: "f" + * non-Web and non-Function APP: "u" (unknown) + */ +var getResourceProvider = function () { + return exports.isWebApp() ? "a" : exports.isFunctionApp() ? "f" : "u"; +}; +exports.getResourceProvider = getResourceProvider; +//# sourceMappingURL=PrefixHelper.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/PrefixHelper.js.map b/node_modules/applicationinsights/out/Library/PrefixHelper.js.map new file mode 100644 index 0000000..62f6bd4 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/PrefixHelper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PrefixHelper.js","sourceRoot":"","sources":["../../Library/PrefixHelper.ts"],"names":[],"mappings":";;;AAAO,IAAM,SAAS,GAAG;IACrB,OAAQ,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AACzC,CAAC,CAAA;AAFY,QAAA,SAAS,aAErB;AAEM,IAAM,OAAO,GAAG;IACnB,OAAQ,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC;AACzC,CAAC,CAAA;AAFY,QAAA,OAAO,WAEnB;AAEM,IAAM,QAAQ,GAAG;IACpB,OAAO,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAA,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;AACvD,CAAC,CAAA;AAFY,QAAA,QAAQ,YAEpB;AAEM,IAAM,aAAa,GAAG;IACzB,OAAO,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAA,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;AAC9D,CAAC,CAAA;AAFY,QAAA,aAAa,iBAEzB;AAED;;;;;GAKG;AACI,IAAM,WAAW,GAAG;IACvB,OAAO,iBAAS,EAAE,CAAA,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,eAAO,EAAE,CAAA,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;AACnD,CAAC,CAAA;AAFY,QAAA,WAAW,eAEvB;AAED;;;;;;GAMG;AACI,IAAM,mBAAmB,GAAG;IAC/B,OAAO,gBAAQ,EAAE,CAAA,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,qBAAa,EAAE,CAAA,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;AACxD,CAAC,CAAA;AAFY,QAAA,mBAAmB,uBAE/B","sourcesContent":["export const isWindows = (): boolean => {\r\n return process.platform === \"win32\";\r\n}\r\n\r\nexport const isLinux = (): boolean => {\r\n return process.platform === \"linux\";\r\n}\r\n\r\nexport const isWebApp = (): boolean => {\r\n return process.env.WEBSITE_SITE_NAME? true : false;\r\n}\r\n\r\nexport const isFunctionApp = (): boolean => {\r\n return process.env.FUNCTIONS_WORKER_RUNTIME? true : false;\r\n}\r\n\r\n/**\r\n * Get prefix for OS\r\n * Windows system: \"w\"\r\n * Linux system: \"l\"\r\n * non-Windows and non-Linux system: \"u\" (unknown)\r\n */\r\nexport const getOsPrefix = (): string => {\r\n return isWindows()? \"w\" : isLinux()? \"l\" : \"u\";\r\n}\r\n\r\n/**\r\n * TODO: add vm resource provider\r\n * Get prefix resource provider, vm will considered as \"unknown RP\"\r\n * Web App: \"a\"\r\n * Function App: \"f\"\r\n * non-Web and non-Function APP: \"u\" (unknown)\r\n */\r\nexport const getResourceProvider = (): string => {\r\n return isWebApp()? \"a\" : isFunctionApp()? \"f\" : \"u\";\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.d.ts b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.d.ts new file mode 100644 index 0000000..c9d173e --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.d.ts @@ -0,0 +1,17 @@ +import Contracts = require("../Declarations/Contracts"); +import Config = require("./Config"); +import Context = require("./Context"); +declare class QuickPulseEnvelopeFactory { + private static keys; + static createQuickPulseEnvelope(metrics: Contracts.MetricQuickPulse[], documents: Contracts.DocumentQuickPulse[], config: Config, context: Context): Contracts.EnvelopeQuickPulse; + static createQuickPulseMetric(telemetry: Contracts.MetricTelemetry): Contracts.MetricQuickPulse; + static telemetryEnvelopeToQuickPulseDocument(envelope: Contracts.Envelope): Contracts.DocumentQuickPulse; + private static createQuickPulseEventDocument; + private static createQuickPulseTraceDocument; + private static createQuickPulseExceptionDocument; + private static createQuickPulseRequestDocument; + private static createQuickPulseDependencyDocument; + private static createQuickPulseDocument; + private static aggregateProperties; +} +export = QuickPulseEnvelopeFactory; diff --git a/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js new file mode 100644 index 0000000..bbc2348 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js @@ -0,0 +1,169 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var os = require("os"); +var Contracts = require("../Declarations/Contracts"); +var Constants = require("../Declarations/Constants"); +var Util = require("./Util"); +var Logging = require("./Logging"); +var StreamId = Util.w3cTraceId(); // Create a guid +var QuickPulseEnvelopeFactory = /** @class */ (function () { + function QuickPulseEnvelopeFactory() { + } + QuickPulseEnvelopeFactory.createQuickPulseEnvelope = function (metrics, documents, config, context) { + var machineName = (os && typeof os.hostname === "function" + && os.hostname()) || "Unknown"; // Note: os.hostname() was added in node v0.3.3 + var instance = (context.tags + && context.keys + && context.keys.cloudRoleInstance + && context.tags[context.keys.cloudRoleInstance]) || machineName; + var roleName = (context.tags + && context.keys + && context.keys.cloudRole + && context.tags[context.keys.cloudRole]) || null; + var envelope = { + Documents: documents.length > 0 ? documents : null, + InstrumentationKey: config.instrumentationKey || "", + Metrics: metrics.length > 0 ? metrics : null, + InvariantVersion: 1, + Timestamp: "/Date(" + Date.now() + ")/", + Version: context.tags[context.keys.internalSdkVersion], + StreamId: StreamId, + MachineName: machineName, + Instance: instance, + RoleName: roleName + }; + return envelope; + }; + QuickPulseEnvelopeFactory.createQuickPulseMetric = function (telemetry) { + var data; + data = { + Name: telemetry.name, + Value: telemetry.value, + Weight: telemetry.count || 1 + }; + return data; + }; + QuickPulseEnvelopeFactory.telemetryEnvelopeToQuickPulseDocument = function (envelope) { + switch (envelope.data.baseType) { + case Contracts.TelemetryTypeString.Event: + return QuickPulseEnvelopeFactory.createQuickPulseEventDocument(envelope); + case Contracts.TelemetryTypeString.Exception: + return QuickPulseEnvelopeFactory.createQuickPulseExceptionDocument(envelope); + case Contracts.TelemetryTypeString.Trace: + return QuickPulseEnvelopeFactory.createQuickPulseTraceDocument(envelope); + case Contracts.TelemetryTypeString.Dependency: + return QuickPulseEnvelopeFactory.createQuickPulseDependencyDocument(envelope); + case Contracts.TelemetryTypeString.Request: + return QuickPulseEnvelopeFactory.createQuickPulseRequestDocument(envelope); + } + return null; + }; + QuickPulseEnvelopeFactory.createQuickPulseEventDocument = function (envelope) { + var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); + var name = envelope.data.baseData.name; + var eventDocument = __assign(__assign({}, document), { Name: name }); + return eventDocument; + }; + QuickPulseEnvelopeFactory.createQuickPulseTraceDocument = function (envelope) { + var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); + var severityLevel = envelope.data.baseData.severityLevel || 0; + var traceDocument = __assign(__assign({}, document), { Message: envelope.data.baseData.message, SeverityLevel: Contracts.SeverityLevel[severityLevel] }); + return traceDocument; + }; + QuickPulseEnvelopeFactory.createQuickPulseExceptionDocument = function (envelope) { + var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); + var exceptionDetails = envelope.data.baseData.exceptions; + var exception = ""; + var exceptionMessage = ""; + var exceptionType = ""; + // Try to fill exception information from first error only + if (exceptionDetails && exceptionDetails.length > 0) { + // Try to grab the stack from parsedStack or stack + if (exceptionDetails[0].parsedStack && exceptionDetails[0].parsedStack.length > 0) { + exceptionDetails[0].parsedStack.forEach(function (err) { + exception += err.assembly + "\n"; + }); + } + else if (exceptionDetails[0].stack && exceptionDetails[0].stack.length > 0) { + exception = exceptionDetails[0].stack; + } + exceptionMessage = exceptionDetails[0].message; + exceptionType = exceptionDetails[0].typeName; + } + var exceptionDocument = __assign(__assign({}, document), { Exception: exception, ExceptionMessage: exceptionMessage, ExceptionType: exceptionType }); + return exceptionDocument; + }; + QuickPulseEnvelopeFactory.createQuickPulseRequestDocument = function (envelope) { + var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); + var baseData = envelope.data.baseData; + var requestDocument = __assign(__assign({}, document), { Name: baseData.name, Success: baseData.success, Duration: baseData.duration, ResponseCode: baseData.responseCode, OperationName: baseData.name // TODO: is this correct? + }); + return requestDocument; + }; + QuickPulseEnvelopeFactory.createQuickPulseDependencyDocument = function (envelope) { + var document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope); + var baseData = envelope.data.baseData; + var dependencyDocument = __assign(__assign({}, document), { Name: baseData.name, Target: baseData.target, Success: baseData.success, Duration: baseData.duration, ResultCode: baseData.resultCode, CommandName: baseData.data, OperationName: document.OperationId, DependencyTypeName: baseData.type }); + return dependencyDocument; + }; + QuickPulseEnvelopeFactory.createQuickPulseDocument = function (envelope) { + var documentType; + var __type; + var operationId, properties; + if (envelope.data.baseType) { + __type = Constants.TelemetryTypeStringToQuickPulseType[envelope.data.baseType]; + documentType = Constants.TelemetryTypeStringToQuickPulseDocumentType[envelope.data.baseType]; + } + else { + // Remark: This should never be hit because createQuickPulseDocument is only called within + // valid baseType values + Logging.warn("Document type invalid; not sending live metric document", envelope.data.baseType); + } + operationId = envelope.tags[QuickPulseEnvelopeFactory.keys.operationId]; + properties = QuickPulseEnvelopeFactory.aggregateProperties(envelope); + var document = { + DocumentType: documentType, + __type: __type, + OperationId: operationId, + Version: "1.0", + Properties: properties + }; + return document; + }; + QuickPulseEnvelopeFactory.aggregateProperties = function (envelope) { + var properties = []; + // Collect measurements + var meas = (envelope.data.baseData).measurements || {}; + for (var key in meas) { + if (meas.hasOwnProperty(key)) { + var value = meas[key]; + var property = { key: key, value: value }; + properties.push(property); + } + } + // Collect properties + var props = (envelope.data.baseData).properties || {}; + for (var key in props) { + if (props.hasOwnProperty(key)) { + var value = props[key]; + var property = { key: key, value: value }; + properties.push(property); + } + } + return properties; + }; + QuickPulseEnvelopeFactory.keys = new Contracts.ContextTagKeys(); + return QuickPulseEnvelopeFactory; +}()); +module.exports = QuickPulseEnvelopeFactory; +//# sourceMappingURL=QuickPulseEnvelopeFactory.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js.map b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js.map new file mode 100644 index 0000000..70716b0 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseEnvelopeFactory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"QuickPulseEnvelopeFactory.js","sourceRoot":"","sources":["../../Library/QuickPulseEnvelopeFactory.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uBAA0B;AAC1B,qDAAuD;AACvD,qDAAwD;AACxD,6BAA+B;AAG/B,mCAAsC;AAEtC,IAAI,QAAQ,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,gBAAgB;AAElD;IAAA;IA0MA,CAAC;IAvMiB,kDAAwB,GAAtC,UAAuC,OAAqC,EAAE,SAAyC,EAAE,MAAc,EAAE,OAAgB;QACrJ,IAAM,WAAW,GAAG,CAAC,EAAE,IAAI,OAAO,EAAE,CAAC,QAAQ,KAAK,UAAU;eACrD,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,SAAS,CAAC,CAAC,+CAA+C;QACnF,IAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,IAAI;eACvB,OAAO,CAAC,IAAI;eACZ,OAAO,CAAC,IAAI,CAAC,iBAAiB;eAC9B,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,IAAI,WAAW,CAAC;QAEpE,IAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,IAAI;eACvB,OAAO,CAAC,IAAI;eACZ,OAAO,CAAC,IAAI,CAAC,SAAS;eACtB,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,IAAI,CAAC;QAErD,IAAI,QAAQ,GAAiC;YACzC,SAAS,EAAE,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI;YAClD,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,IAAI,EAAE;YACnD,OAAO,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AAW;YACxB,OAAO,EAAE,KAAK;YACd,UAAU,EAAE,UAAU;SACzB,CAAC;QAEF,OAAO,QAAQ,CAAC;IACpB,CAAC;IAEc,6CAAmB,GAAlC,UAAmC,QAA4B;QAC3D,IAAM,UAAU,GAAkC,EAAE,CAAC;QAErD,uBAAuB;QACvB,IAAM,IAAI,GAAG,CAAE,QAAQ,CAAC,IAAY,CAAC,QAAQ,CAAC,CAAC,YAAY,IAAI,EAAE,CAAC;QAClE,KAAK,IAAI,GAAG,IAAI,IAAI,EAAE;YAClB,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;gBAC1B,IAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;gBACxB,IAAM,QAAQ,GAAgC,EAAC,GAAG,KAAA,EAAE,KAAK,OAAA,EAAC,CAAC;gBAC3D,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;aAC7B;SACJ;QAED,qBAAqB;QACrB,IAAM,KAAK,GAAG,CAAE,QAAQ,CAAC,IAAY,CAAC,QAAQ,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC;QACjE,KAAK,IAAI,GAAG,IAAI,KAAK,EAAE;YACnB,IAAI,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;gBAC3B,IAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;gBACzB,IAAM,QAAQ,GAAgC,EAAC,GAAG,KAAA,EAAE,KAAK,OAAA,EAAC,CAAC;gBAC3D,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;aAC7B;SACJ;QAED,OAAO,UAAU,CAAC;IACtB,CAAC;IAxMc,8BAAI,GAAG,IAAI,SAAS,CAAC,cAAc,EAAE,CAAC;IAyMzD,gCAAC;CAAA,AA1MD,IA0MC;AAED,iBAAS,yBAAyB,CAAC","sourcesContent":["import os = require(\"os\");\r\nimport Contracts = require(\"../Declarations/Contracts\")\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport Util = require(\"./Util\")\r\nimport Config = require(\"./Config\");\r\nimport Context = require(\"./Context\");\r\nimport Logging = require(\"./Logging\");\r\n\r\nvar StreamId = Util.w3cTraceId(); // Create a guid\r\n\r\nclass QuickPulseEnvelopeFactory {\r\n private static keys = new Contracts.ContextTagKeys();\r\n\r\n public static createQuickPulseEnvelope(metrics: Contracts.MetricQuickPulse[], documents: Contracts.DocumentQuickPulse[], config: Config, context: Context): Contracts.EnvelopeQuickPulse {\r\n const machineName = (os && typeof os.hostname === \"function\"\r\n && os.hostname()) || \"Unknown\"; // Note: os.hostname() was added in node v0.3.3\r\n const instance = (context.tags\r\n && context.keys\r\n && context.keys.cloudRoleInstance\r\n && context.tags[context.keys.cloudRoleInstance]) || machineName;\r\n\r\n const roleName = (context.tags\r\n && context.keys\r\n && context.keys.cloudRole\r\n && context.tags[context.keys.cloudRole]) || null;\r\n\r\n var envelope: Contracts.EnvelopeQuickPulse = {\r\n Documents: documents.length > 0 ? documents : null,\r\n InstrumentationKey: config.instrumentationKey || \"\",\r\n Metrics: metrics.length > 0 ? metrics : null,\r\n InvariantVersion: 1, // 1 -> v1 QPS protocol\r\n Timestamp: `\\/Date(${Date.now()})\\/`,\r\n Version: context.tags[context.keys.internalSdkVersion],\r\n StreamId: StreamId,\r\n MachineName: machineName,\r\n Instance: instance,\r\n RoleName: roleName\r\n }\r\n\r\n return envelope;\r\n }\r\n\r\n public static createQuickPulseMetric(\r\n telemetry: Contracts.MetricTelemetry\r\n ): Contracts.MetricQuickPulse {\r\n var data: Contracts.MetricQuickPulse;\r\n data = {\r\n Name: telemetry.name, // TODO: map from MetricTelemetry name to QuickPulse name\r\n Value: telemetry.value,\r\n Weight: telemetry.count || 1\r\n };\r\n return data;\r\n }\r\n\r\n public static telemetryEnvelopeToQuickPulseDocument(envelope: Contracts.Envelope): Contracts.DocumentQuickPulse {\r\n switch (envelope.data.baseType) {\r\n case Contracts.TelemetryTypeString.Event:\r\n return QuickPulseEnvelopeFactory.createQuickPulseEventDocument(envelope);\r\n case Contracts.TelemetryTypeString.Exception:\r\n return QuickPulseEnvelopeFactory.createQuickPulseExceptionDocument(envelope);\r\n case Contracts.TelemetryTypeString.Trace:\r\n return QuickPulseEnvelopeFactory.createQuickPulseTraceDocument(envelope);\r\n case Contracts.TelemetryTypeString.Dependency:\r\n return QuickPulseEnvelopeFactory.createQuickPulseDependencyDocument(envelope);\r\n case Contracts.TelemetryTypeString.Request:\r\n return QuickPulseEnvelopeFactory.createQuickPulseRequestDocument(envelope);\r\n }\r\n return null;\r\n }\r\n\r\n private static createQuickPulseEventDocument(envelope: Contracts.Envelope): Contracts.EventDocumentQuickPulse {\r\n const document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope);\r\n const name = ((envelope.data as any).baseData as Contracts.EventData).name;\r\n const eventDocument: Contracts.EventDocumentQuickPulse = {\r\n ...document,\r\n Name: name\r\n };\r\n\r\n return eventDocument;\r\n }\r\n\r\n private static createQuickPulseTraceDocument(envelope: Contracts.Envelope): Contracts.MessageDocumentQuickPulse {\r\n const document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope);\r\n const severityLevel = ((envelope.data as any).baseData as Contracts.MessageData).severityLevel || 0;\r\n var traceDocument: Contracts.MessageDocumentQuickPulse = {\r\n ...document,\r\n Message: ((envelope.data as any).baseData as Contracts.MessageData).message,\r\n SeverityLevel: Contracts.SeverityLevel[severityLevel]\r\n }\r\n\r\n return traceDocument;\r\n }\r\n\r\n private static createQuickPulseExceptionDocument(envelope: Contracts.Envelope): Contracts.ExceptionDocumentQuickPulse {\r\n const document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope);\r\n const exceptionDetails = ((envelope.data as any).baseData as Contracts.ExceptionData).exceptions;\r\n\r\n let exception = \"\";\r\n let exceptionMessage = \"\";\r\n let exceptionType = \"\";\r\n\r\n // Try to fill exception information from first error only\r\n if (exceptionDetails && exceptionDetails.length > 0) {\r\n // Try to grab the stack from parsedStack or stack\r\n if (exceptionDetails[0].parsedStack && exceptionDetails[0].parsedStack.length > 0) {\r\n exceptionDetails[0].parsedStack.forEach(err => {\r\n exception += err.assembly + \"\\n\";\r\n });\r\n } else if (exceptionDetails[0].stack && exceptionDetails[0].stack.length > 0) {\r\n exception = exceptionDetails[0].stack;\r\n }\r\n\r\n exceptionMessage = exceptionDetails[0].message;\r\n exceptionType = exceptionDetails[0].typeName;\r\n }\r\n\r\n var exceptionDocument = {\r\n ...document,\r\n Exception: exception,\r\n ExceptionMessage: exceptionMessage,\r\n ExceptionType: exceptionType\r\n };\r\n return exceptionDocument;\r\n }\r\n\r\n private static createQuickPulseRequestDocument(envelope: Contracts.Envelope): Contracts.RequestDocumentQuickPulse {\r\n const document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope);\r\n const baseData = (envelope.data as Contracts.Data).baseData;\r\n const requestDocument: Contracts.RequestDocumentQuickPulse = {\r\n ...document,\r\n Name: baseData.name,\r\n Success: baseData.success,\r\n Duration: baseData.duration,\r\n ResponseCode: baseData.responseCode,\r\n OperationName: baseData.name // TODO: is this correct?\r\n };\r\n\r\n return requestDocument;\r\n }\r\n\r\n private static createQuickPulseDependencyDocument(envelope: Contracts.Envelope): Contracts.DependencyDocumentQuickPulse {\r\n const document = QuickPulseEnvelopeFactory.createQuickPulseDocument(envelope);\r\n const baseData = (envelope.data as Contracts.Data).baseData;\r\n\r\n const dependencyDocument: Contracts.DependencyDocumentQuickPulse = {\r\n ...document,\r\n Name: baseData.name,\r\n Target: baseData.target,\r\n Success: baseData.success,\r\n Duration: baseData.duration,\r\n ResultCode: baseData.resultCode,\r\n CommandName: baseData.data,\r\n OperationName: document.OperationId,\r\n DependencyTypeName: baseData.type\r\n }\r\n return dependencyDocument;\r\n }\r\n\r\n private static createQuickPulseDocument(envelope: Contracts.Envelope): Contracts.DocumentQuickPulse {\r\n let documentType: Constants.QuickPulseDocumentType;\r\n let __type: Constants.QuickPulseType;\r\n let operationId, properties;\r\n\r\n\r\n if (envelope.data.baseType) {\r\n __type = Constants.TelemetryTypeStringToQuickPulseType[envelope.data.baseType as Contracts.TelemetryTypeValues];\r\n documentType = Constants.TelemetryTypeStringToQuickPulseDocumentType[envelope.data.baseType as Contracts.TelemetryTypeValues];\r\n } else {\r\n // Remark: This should never be hit because createQuickPulseDocument is only called within\r\n // valid baseType values\r\n Logging.warn(\"Document type invalid; not sending live metric document\", envelope.data.baseType);\r\n }\r\n\r\n operationId = envelope.tags[QuickPulseEnvelopeFactory.keys.operationId];\r\n properties = QuickPulseEnvelopeFactory.aggregateProperties(envelope);\r\n\r\n var document: Contracts.DocumentQuickPulse = {\r\n DocumentType: documentType,\r\n __type: __type,\r\n OperationId: operationId,\r\n Version: \"1.0\",\r\n Properties: properties\r\n };\r\n\r\n return document;\r\n }\r\n\r\n private static aggregateProperties(envelope: Contracts.Envelope): Contracts.IDocumentProperty[] {\r\n const properties: Contracts.IDocumentProperty[] = [];\r\n\r\n // Collect measurements\r\n const meas = ((envelope.data as any).baseData).measurements || {};\r\n for (let key in meas) {\r\n if (meas.hasOwnProperty(key)) {\r\n const value = meas[key];\r\n const property: Contracts.IDocumentProperty = {key, value};\r\n properties.push(property);\r\n }\r\n }\r\n\r\n // Collect properties\r\n const props = ((envelope.data as any).baseData).properties || {};\r\n for (let key in props) {\r\n if (props.hasOwnProperty(key)) {\r\n const value = props[key];\r\n const property: Contracts.IDocumentProperty = {key, value};\r\n properties.push(property);\r\n }\r\n }\r\n\r\n return properties;\r\n }\r\n}\r\n\r\nexport = QuickPulseEnvelopeFactory;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseSender.d.ts b/node_modules/applicationinsights/out/Library/QuickPulseSender.d.ts new file mode 100644 index 0000000..bca477b --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseSender.d.ts @@ -0,0 +1,18 @@ +/// +import AuthorizationHandler = require("./AuthorizationHandler"); +import Config = require("./Config"); +import * as http from "http"; +import * as Contracts from "../Declarations/Contracts"; +declare class QuickPulseSender { + private static TAG; + private static MAX_QPS_FAILURES_BEFORE_WARN; + private _config; + private _consecutiveErrors; + private _getAuthorizationHandler; + constructor(config: Config, getAuthorizationHandler?: (config: Config) => AuthorizationHandler); + ping(envelope: Contracts.EnvelopeQuickPulse, redirectedHostEndpoint: string, done: (shouldPOST?: boolean, res?: http.IncomingMessage, redirectedHost?: string, pollingIntervalHint?: number) => void): void; + post(envelope: Contracts.EnvelopeQuickPulse, redirectedHostEndpoint: string, done: (shouldPOST?: boolean, res?: http.IncomingMessage, redirectedHost?: string, pollingIntervalHint?: number) => void): Promise; + private _submitData; + private _onError; +} +export = QuickPulseSender; diff --git a/node_modules/applicationinsights/out/Library/QuickPulseSender.js b/node_modules/applicationinsights/out/Library/QuickPulseSender.js new file mode 100644 index 0000000..920c68c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseSender.js @@ -0,0 +1,189 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var https = require("https"); +var AutoCollectHttpDependencies = require("../AutoCollection/HttpDependencies"); +var Logging = require("./Logging"); +var QuickPulseUtil = require("./QuickPulseUtil"); +var Util = require("./Util"); +var url = require("url"); +var QuickPulseConfig = { + method: "POST", + time: "x-ms-qps-transmission-time", + pollingIntervalHint: "x-ms-qps-service-polling-interval-hint", + endpointRedirect: "x-ms-qps-service-endpoint-redirect-v2", + instanceName: "x-ms-qps-instance-name", + streamId: "x-ms-qps-stream-id", + machineName: "x-ms-qps-machine-name", + roleName: "x-ms-qps-role-name", + streamid: "x-ms-qps-stream-id", + invariantVersion: "x-ms-qps-invariant-version", + subscribed: "x-ms-qps-subscribed" +}; +var QuickPulseSender = /** @class */ (function () { + function QuickPulseSender(config, getAuthorizationHandler) { + this._config = config; + this._consecutiveErrors = 0; + this._getAuthorizationHandler = getAuthorizationHandler; + } + QuickPulseSender.prototype.ping = function (envelope, redirectedHostEndpoint, done) { + var pingHeaders = [ + { name: QuickPulseConfig.streamId, value: envelope.StreamId }, + { name: QuickPulseConfig.machineName, value: envelope.MachineName }, + { name: QuickPulseConfig.roleName, value: envelope.RoleName }, + { name: QuickPulseConfig.instanceName, value: envelope.Instance }, + { name: QuickPulseConfig.invariantVersion, value: envelope.InvariantVersion.toString() } + ]; + this._submitData(envelope, redirectedHostEndpoint, done, "ping", pingHeaders); + }; + QuickPulseSender.prototype.post = function (envelope, redirectedHostEndpoint, done) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // Important: When POSTing data, envelope must be an array + return [4 /*yield*/, this._submitData([envelope], redirectedHostEndpoint, done, "post")]; + case 1: + // Important: When POSTing data, envelope must be an array + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + QuickPulseSender.prototype._submitData = function (envelope, redirectedHostEndpoint, done, postOrPing, additionalHeaders) { + return __awaiter(this, void 0, void 0, function () { + var payload, options, authHandler, authError_1, notice, req; + var _a, _b; + var _this = this; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + payload = Util.stringify(envelope); + options = (_a = {}, + _a[AutoCollectHttpDependencies.disableCollectionRequestOption] = true, + _a.host = (redirectedHostEndpoint && redirectedHostEndpoint.length > 0) ? redirectedHostEndpoint : this._config.quickPulseHost, + _a.method = QuickPulseConfig.method, + _a.path = "/QuickPulseService.svc/" + postOrPing + "?ikey=" + this._config.instrumentationKey, + _a.headers = (_b = { + "Expect": "100-continue" + }, + _b[QuickPulseConfig.time] = QuickPulseUtil.getTransmissionTime(), + _b["Content-Type"] = "application\/json", + _b["Content-Length"] = Buffer.byteLength(payload), + _b), + _a); + if (additionalHeaders && additionalHeaders.length > 0) { + additionalHeaders.forEach(function (header) { return options.headers[header.name] = header.value; }); + } + if (!(postOrPing === "post")) return [3 /*break*/, 4]; + authHandler = this._getAuthorizationHandler ? this._getAuthorizationHandler(this._config) : null; + if (!authHandler) return [3 /*break*/, 4]; + _c.label = 1; + case 1: + _c.trys.push([1, 3, , 4]); + // Add bearer token + return [4 /*yield*/, authHandler.addAuthorizationHeader(options)]; + case 2: + // Add bearer token + _c.sent(); + return [3 /*break*/, 4]; + case 3: + authError_1 = _c.sent(); + notice = "Failed to get AAD bearer token for the Application. Error:"; + Logging.info(QuickPulseSender.TAG, notice, authError_1); + // Do not send request to Quickpulse if auth fails, data will be dropped + return [2 /*return*/]; + case 4: + // HTTPS only + if (this._config.httpsAgent) { + options.agent = this._config.httpsAgent; + } + else { + options.agent = Util.tlsRestrictedAgent; + } + req = https.request(options, function (res) { + if (res.statusCode == 200) { + var shouldPOSTData = res.headers[QuickPulseConfig.subscribed] === "true"; + var redirectHeader = null; + try { + redirectHeader = res.headers[QuickPulseConfig.endpointRedirect] ? new url.URL(res.headers[QuickPulseConfig.endpointRedirect].toString()).host : null; + } + catch (error) { + _this._onError("Failed to parse redirect header from QuickPulse: " + Util.dumpObj(error)); + } + var pollingIntervalHint = res.headers[QuickPulseConfig.pollingIntervalHint] ? parseInt(res.headers[QuickPulseConfig.pollingIntervalHint].toString()) : null; + _this._consecutiveErrors = 0; + done(shouldPOSTData, res, redirectHeader, pollingIntervalHint); + } + else { + _this._onError("StatusCode:" + res.statusCode + " StatusMessage:" + res.statusMessage); + done(); + } + }); + req.on("error", function (error) { + _this._onError(error); + done(); + }); + req.write(payload); + req.end(); + return [2 /*return*/]; + } + }); + }); + }; + QuickPulseSender.prototype._onError = function (error) { + // Unable to contact qps endpoint. + // Do nothing for now. + this._consecutiveErrors++; + // LOG every error, but WARN instead when X number of consecutive errors occur + var notice = "Transient error connecting to the Live Metrics endpoint. This packet will not appear in your Live Metrics Stream. Error:"; + if (this._consecutiveErrors % QuickPulseSender.MAX_QPS_FAILURES_BEFORE_WARN === 0) { + notice = "Live Metrics endpoint could not be reached " + this._consecutiveErrors + " consecutive times. Most recent error:"; + Logging.warn(QuickPulseSender.TAG, notice, error); + } + else { + // Potentially transient error, do not change the ping/post state yet. + Logging.info(QuickPulseSender.TAG, notice, error); + } + }; + QuickPulseSender.TAG = "QuickPulseSender"; + QuickPulseSender.MAX_QPS_FAILURES_BEFORE_WARN = 25; + return QuickPulseSender; +}()); +module.exports = QuickPulseSender; +//# sourceMappingURL=QuickPulseSender.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseSender.js.map b/node_modules/applicationinsights/out/Library/QuickPulseSender.js.map new file mode 100644 index 0000000..0461d64 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseSender.js.map @@ -0,0 +1 @@ +{"version":3,"file":"QuickPulseSender.js","sourceRoot":"","sources":["../../Library/QuickPulseSender.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6BAAgC;AAIhC,gFAAmF;AACnF,mCAAsC;AACtC,iDAAoD;AACpD,6BAAgC;AAChC,yBAA4B;AAM5B,IAAM,gBAAgB,GAAG;IACrB,MAAM,EAAE,MAAM;IACd,IAAI,EAAE,4BAA4B;IAClC,mBAAmB,EAAE,wCAAwC;IAC7D,gBAAgB,EAAE,uCAAuC;IACzD,YAAY,EAAE,wBAAwB;IACtC,QAAQ,EAAE,oBAAoB;IAC9B,WAAW,EAAE,uBAAuB;IACpC,QAAQ,EAAE,oBAAoB;IAC9B,QAAQ,EAAE,oBAAoB;IAC9B,gBAAgB,EAAE,4BAA4B;IAC9C,UAAU,EAAE,qBAAqB;CACpC,CAAC;AAEF;IAQI,0BAAY,MAAc,EAAE,uBAAkE;QAC1F,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,kBAAkB,GAAG,CAAC,CAAC;QAC5B,IAAI,CAAC,wBAAwB,GAAG,uBAAuB,CAAC;IAC5D,CAAC;IAEM,+BAAI,GAAX,UAAY,QAAsC,EAC9C,sBAA8B,EAC9B,IAAuH;QAGvH,IAAI,WAAW,GAAsC;YACjD,EAAE,IAAI,EAAE,gBAAgB,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,QAAQ,EAAE;YAC7D,EAAE,IAAI,EAAE,gBAAgB,CAAC,WAAW,EAAE,KAAK,EAAE,QAAQ,CAAC,WAAW,EAAE;YACnE,EA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AC;;;;;KACb;IAEO,mCAAQ,GAAhB,UAAiB,KAAqB;QAClC,kCAAkC;QAClC,sBAAsB;QACtB,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAC1B,8EAA8E;QAC9E,IAAI,MAAM,GAAG,0HAA0H,CAAC;QACxI,IAAI,IAAI,CAAC,kBAAkB,GAAG,gBAAgB,CAAC,4BAA4B,KAAK,CAAC,EAAE;YAC/E,MAAM,GAAG,gDAA8C,IAAI,CAAC,kBAAkB,2CAAwC,CAAC;YACvH,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;SACrD;aAAM;YACH,sEAAsE;YACtE,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;SACrD;IACL,CAAC;IA/Hc,oBAAG,GAAG,kBAAkB,CAAC;IACzB,6CAA4B,GAAG,EAAE,CAAC;IA+HrD,uBAAC;CAAA,AAjID,IAiIC;AAED,iBAAS,gBAAgB,CAAC","sourcesContent":["import https = require(\"https\");\r\n\r\nimport AuthorizationHandler = require(\"./AuthorizationHandler\");\r\nimport Config = require(\"./Config\");\r\nimport AutoCollectHttpDependencies = require(\"../AutoCollection/HttpDependencies\");\r\nimport Logging = require(\"./Logging\");\r\nimport QuickPulseUtil = require(\"./QuickPulseUtil\");\r\nimport Util = require(\"./Util\");\r\nimport url = require(\"url\");\r\n\r\n// Types\r\nimport * as http from \"http\";\r\nimport * as Contracts from \"../Declarations/Contracts\";\r\n\r\nconst QuickPulseConfig = {\r\n method: \"POST\",\r\n time: \"x-ms-qps-transmission-time\",\r\n pollingIntervalHint: \"x-ms-qps-service-polling-interval-hint\",\r\n endpointRedirect: \"x-ms-qps-service-endpoint-redirect-v2\",\r\n instanceName: \"x-ms-qps-instance-name\",\r\n streamId: \"x-ms-qps-stream-id\",\r\n machineName: \"x-ms-qps-machine-name\",\r\n roleName: \"x-ms-qps-role-name\",\r\n streamid: \"x-ms-qps-stream-id\",\r\n invariantVersion: \"x-ms-qps-invariant-version\",\r\n subscribed: \"x-ms-qps-subscribed\"\r\n};\r\n\r\nclass QuickPulseSender {\r\n private static TAG = \"QuickPulseSender\";\r\n private static MAX_QPS_FAILURES_BEFORE_WARN = 25;\r\n\r\n private _config: Config;\r\n private _consecutiveErrors: number;\r\n private _getAuthorizationHandler: (config: Config) => AuthorizationHandler;\r\n\r\n constructor(config: Config, getAuthorizationHandler?: (config: Config) => AuthorizationHandler) {\r\n this._config = config;\r\n this._consecutiveErrors = 0;\r\n this._getAuthorizationHandler = getAuthorizationHandler;\r\n }\r\n\r\n public ping(envelope: Contracts.EnvelopeQuickPulse,\r\n redirectedHostEndpoint: string,\r\n done: (shouldPOST?: boolean, res?: http.IncomingMessage, redirectedHost?: string, pollingIntervalHint?: number) => void\r\n ): void {\r\n\r\n let pingHeaders: { name: string, value: string }[] = [\r\n { name: QuickPulseConfig.streamId, value: envelope.StreamId },\r\n { name: QuickPulseConfig.machineName, value: envelope.MachineName },\r\n { name: QuickPulseConfig.roleName, value: envelope.RoleName },\r\n { name: QuickPulseConfig.instanceName, value: envelope.Instance },\r\n { name: QuickPulseConfig.invariantVersion, value: envelope.InvariantVersion.toString() }\r\n ];\r\n this._submitData(envelope, redirectedHostEndpoint, done, \"ping\", pingHeaders);\r\n }\r\n\r\n public async post(envelope: Contracts.EnvelopeQuickPulse,\r\n redirectedHostEndpoint: string,\r\n done: (shouldPOST?: boolean, res?: http.IncomingMessage, redirectedHost?: string, pollingIntervalHint?: number) => void\r\n ): Promise {\r\n\r\n // Important: When POSTing data, envelope must be an array\r\n await this._submitData([envelope], redirectedHostEndpoint, done, \"post\");\r\n }\r\n\r\n private async _submitData(envelope: Contracts.EnvelopeQuickPulse | Contracts.EnvelopeQuickPulse[],\r\n redirectedHostEndpoint: string,\r\n done: (shouldPOST?: boolean, res?: http.IncomingMessage, redirectedHost?: string, pollingIntervalHint?: number) => void,\r\n postOrPing: \"post\" | \"ping\",\r\n additionalHeaders?: { name: string, value: string }[]\r\n ): Promise {\r\n\r\n const payload = Util.stringify(envelope);\r\n var options = {\r\n [AutoCollectHttpDependencies.disableCollectionRequestOption]: true,\r\n host: (redirectedHostEndpoint && redirectedHostEndpoint.length > 0) ? redirectedHostEndpoint : this._config.quickPulseHost,\r\n method: QuickPulseConfig.method,\r\n path: `/QuickPulseService.svc/${postOrPing}?ikey=${this._config.instrumentationKey}`,\r\n headers: {\r\n \"Expect\": \"100-continue\",\r\n [QuickPulseConfig.time]: QuickPulseUtil.getTransmissionTime(), // unit = 100s of nanoseconds\r\n \"Content-Type\": \"application\\/json\",\r\n \"Content-Length\": Buffer.byteLength(payload)\r\n }\r\n };\r\n\r\n if (additionalHeaders && additionalHeaders.length > 0) {\r\n additionalHeaders.forEach(header => options.headers[header.name] = header.value);\r\n }\r\n\r\n if (postOrPing === \"post\") {\r\n let authHandler = this._getAuthorizationHandler ? this._getAuthorizationHandler(this._config) : null;\r\n if (authHandler) {\r\n try {\r\n // Add bearer token\r\n await authHandler.addAuthorizationHeader(options);\r\n }\r\n catch (authError) {\r\n let notice = \"Failed to get AAD bearer token for the Application. Error:\";\r\n Logging.info(QuickPulseSender.TAG, notice, authError);\r\n // Do not send request to Quickpulse if auth fails, data will be dropped\r\n return;\r\n }\r\n }\r\n }\r\n\r\n // HTTPS only\r\n if (this._config.httpsAgent) {\r\n (options).agent = this._config.httpsAgent;\r\n } else {\r\n (options).agent = Util.tlsRestrictedAgent;\r\n }\r\n\r\n const req = https.request(options, (res: http.IncomingMessage) => {\r\n if (res.statusCode == 200) {\r\n const shouldPOSTData = res.headers[QuickPulseConfig.subscribed] === \"true\";\r\n let redirectHeader = null;\r\n try {\r\n redirectHeader = res.headers[QuickPulseConfig.endpointRedirect] ? new url.URL(res.headers[QuickPulseConfig.endpointRedirect].toString()).host : null;\r\n } catch (error) {\r\n this._onError(\"Failed to parse redirect header from QuickPulse: \" + Util.dumpObj(error));\r\n }\r\n \r\n const pollingIntervalHint = res.headers[QuickPulseConfig.pollingIntervalHint] ? parseInt(res.headers[QuickPulseConfig.pollingIntervalHint].toString()) : null;\r\n this._consecutiveErrors = 0;\r\n done(shouldPOSTData, res, redirectHeader, pollingIntervalHint);\r\n }\r\n else {\r\n this._onError(\"StatusCode:\" + res.statusCode + \" StatusMessage:\" + res.statusMessage);\r\n done();\r\n }\r\n });\r\n\r\n req.on(\"error\", (error: Error) => {\r\n this._onError(error);\r\n done();\r\n });\r\n\r\n req.write(payload);\r\n req.end();\r\n }\r\n\r\n private _onError(error: Error | string) {\r\n // Unable to contact qps endpoint.\r\n // Do nothing for now.\r\n this._consecutiveErrors++;\r\n // LOG every error, but WARN instead when X number of consecutive errors occur\r\n let notice = \"Transient error connecting to the Live Metrics endpoint. This packet will not appear in your Live Metrics Stream. Error:\";\r\n if (this._consecutiveErrors % QuickPulseSender.MAX_QPS_FAILURES_BEFORE_WARN === 0) {\r\n notice = `Live Metrics endpoint could not be reached ${this._consecutiveErrors} consecutive times. Most recent error:`;\r\n Logging.warn(QuickPulseSender.TAG, notice, error);\r\n } else {\r\n // Potentially transient error, do not change the ping/post state yet.\r\n Logging.info(QuickPulseSender.TAG, notice, error);\r\n }\r\n }\r\n}\r\n\r\nexport = QuickPulseSender;"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseStateManager.d.ts b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.d.ts new file mode 100644 index 0000000..bfdfd16 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.d.ts @@ -0,0 +1,65 @@ +import AuthorizationHandler = require("./AuthorizationHandler"); +import Config = require("./Config"); +import Context = require("./Context"); +import * as Contracts from "../Declarations/Contracts"; +/** State Container for sending to the QuickPulse Service */ +declare class QuickPulseStateManager { + config: Config; + context: Context; + authorizationHandler: AuthorizationHandler; + private static MAX_POST_WAIT_TIME; + private static MAX_PING_WAIT_TIME; + private static FALLBACK_INTERVAL; + private static PING_INTERVAL; + private static POST_INTERVAL; + private _isCollectingData; + private _sender; + private _isEnabled; + private _lastSuccessTime; + private _lastSendSucceeded; + private _handle; + private _metrics; + private _documents; + private _collectors; + private _redirectedHost; + private _pollingIntervalHint; + constructor(config: Config, context?: Context, getAuthorizationHandler?: (config: Config) => AuthorizationHandler); + /** + * + * @param collector + */ + addCollector(collector: any): void; + /** + * Override of TelemetryClient.trackMetric + */ + trackMetric(telemetry: Contracts.MetricTelemetry): void; + /** + * Add a document to the current buffer + * @param envelope + */ + addDocument(envelope: Contracts.Envelope): void; + /** + * Enable or disable communication with QuickPulseService + * @param isEnabled + */ + enable(isEnabled: boolean): void; + /** + * Enable or disable all collectors in this instance + * @param enable + */ + private enableCollectors; + /** + * Add the metric to this buffer. If same metric already exists in this buffer, add weight to it + * @param telemetry + */ + private _addMetric; + private _resetQuickPulseBuffer; + private _goQuickPulse; + private _ping; + private _post; + /** + * Change the current QPS send state. (shouldPOST == undefined) --> error, but do not change the state yet. + */ + private _quickPulseDone; +} +export = QuickPulseStateManager; diff --git a/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js new file mode 100644 index 0000000..3b4cec4 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js @@ -0,0 +1,226 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var Logging = require("./Logging"); +var QuickPulseEnvelopeFactory = require("./QuickPulseEnvelopeFactory"); +var QuickPulseSender = require("./QuickPulseSender"); +var Constants = require("../Declarations/Constants"); +var Context = require("./Context"); +/** State Container for sending to the QuickPulse Service */ +var QuickPulseStateManager = /** @class */ (function () { + function QuickPulseStateManager(config, context, getAuthorizationHandler) { + this._isCollectingData = false; + this._lastSuccessTime = Date.now(); + this._lastSendSucceeded = true; + this._metrics = {}; + this._documents = []; + this._collectors = []; + this._redirectedHost = null; + this._pollingIntervalHint = -1; + this.config = config; + this.context = context || new Context(); + this._sender = new QuickPulseSender(this.config, getAuthorizationHandler); + this._isEnabled = false; + } + /** + * + * @param collector + */ + QuickPulseStateManager.prototype.addCollector = function (collector) { + this._collectors.push(collector); + }; + /** + * Override of TelemetryClient.trackMetric + */ + QuickPulseStateManager.prototype.trackMetric = function (telemetry) { + this._addMetric(telemetry); + }; + /** + * Add a document to the current buffer + * @param envelope + */ + QuickPulseStateManager.prototype.addDocument = function (envelope) { + // Only add documents in buffer when Live Metrics is collecting data + if (this._isCollectingData) { + var document_1 = QuickPulseEnvelopeFactory.telemetryEnvelopeToQuickPulseDocument(envelope); + if (document_1) { + this._documents.push(document_1); + } + } + }; + /** + * Enable or disable communication with QuickPulseService + * @param isEnabled + */ + QuickPulseStateManager.prototype.enable = function (isEnabled) { + if (isEnabled && !this._isEnabled) { + this._isEnabled = true; + this._goQuickPulse(); + } + else if (!isEnabled && this._isEnabled) { + this._isEnabled = false; + clearTimeout(this._handle); + this._handle = undefined; + } + }; + /** + * Enable or disable all collectors in this instance + * @param enable + */ + QuickPulseStateManager.prototype.enableCollectors = function (enable) { + this._collectors.forEach(function (collector) { + collector.enable(enable); + }); + }; + /** + * Add the metric to this buffer. If same metric already exists in this buffer, add weight to it + * @param telemetry + */ + QuickPulseStateManager.prototype._addMetric = function (telemetry) { + var value = telemetry.value; + var count = telemetry.count || 1; + var name = Constants.PerformanceToQuickPulseCounter[telemetry.name]; + if (name) { + if (this._metrics[name]) { + this._metrics[name].Value = (this._metrics[name].Value * this._metrics[name].Weight + value * count) / (this._metrics[name].Weight + count); + this._metrics[name].Weight += count; + } + else { + this._metrics[name] = QuickPulseEnvelopeFactory.createQuickPulseMetric(telemetry); + this._metrics[name].Name = name; + this._metrics[name].Weight = 1; + } + } + }; + QuickPulseStateManager.prototype._resetQuickPulseBuffer = function () { + delete this._metrics; + this._metrics = {}; + this._documents.length = 0; + }; + QuickPulseStateManager.prototype._goQuickPulse = function () { + return __awaiter(this, void 0, void 0, function () { + var metrics, envelope, pingInterval, currentTimeout; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + metrics = Object.keys(this._metrics).map(function (k) { return _this._metrics[k]; }); + envelope = QuickPulseEnvelopeFactory.createQuickPulseEnvelope(metrics, this._documents.slice(), this.config, this.context); + // Clear this document, metric buffer + this._resetQuickPulseBuffer(); + if (!this._isCollectingData) return [3 /*break*/, 2]; + return [4 /*yield*/, this._post(envelope)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + this._ping(envelope); + _a.label = 3; + case 3: + pingInterval = this._pollingIntervalHint > 0 ? this._pollingIntervalHint : QuickPulseStateManager.PING_INTERVAL; + currentTimeout = this._isCollectingData ? QuickPulseStateManager.POST_INTERVAL : pingInterval; + if (this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_POST_WAIT_TIME && !this._lastSendSucceeded) { + // Haven't posted successfully in 20 seconds, so wait 60 seconds and ping + this._isCollectingData = false; + currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL; + } + else if (!this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_PING_WAIT_TIME && !this._lastSendSucceeded) { + // Haven't pinged successfully in 60 seconds, so wait another 60 seconds + currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL; + } + this._lastSendSucceeded = null; + this._handle = setTimeout(this._goQuickPulse.bind(this), currentTimeout); + this._handle.unref(); // Don't block apps from terminating + return [2 /*return*/]; + } + }); + }); + }; + QuickPulseStateManager.prototype._ping = function (envelope) { + this._sender.ping(envelope, this._redirectedHost, this._quickPulseDone.bind(this)); + }; + QuickPulseStateManager.prototype._post = function (envelope) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this._sender.post(envelope, this._redirectedHost, this._quickPulseDone.bind(this))]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + /** + * Change the current QPS send state. (shouldPOST == undefined) --> error, but do not change the state yet. + */ + QuickPulseStateManager.prototype._quickPulseDone = function (shouldPOST, res, redirectedHost, pollingIntervalHint) { + if (shouldPOST != undefined) { + if (this._isCollectingData !== shouldPOST) { + Logging.info("Live Metrics sending data", shouldPOST); + this.enableCollectors(shouldPOST); + } + this._isCollectingData = shouldPOST; + if (redirectedHost && redirectedHost.length > 0) { + this._redirectedHost = redirectedHost; + Logging.info("Redirecting endpoint to: ", redirectedHost); + } + if (pollingIntervalHint && pollingIntervalHint > 0) { + this._pollingIntervalHint = pollingIntervalHint; + } + if (res && res.statusCode < 300 && res.statusCode >= 200) { + this._lastSuccessTime = Date.now(); + this._lastSendSucceeded = true; + } + else { + this._lastSendSucceeded = false; + } + } + else { + // Received an error, keep the state as is + this._lastSendSucceeded = false; + } + }; + QuickPulseStateManager.MAX_POST_WAIT_TIME = 20000; + QuickPulseStateManager.MAX_PING_WAIT_TIME = 60000; + QuickPulseStateManager.FALLBACK_INTERVAL = 60000; + QuickPulseStateManager.PING_INTERVAL = 5000; + QuickPulseStateManager.POST_INTERVAL = 1000; + return QuickPulseStateManager; +}()); +module.exports = QuickPulseStateManager; +//# sourceMappingURL=QuickPulseStateManager.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js.map b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js.map new file mode 100644 index 0000000..92b39c1 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseStateManager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"QuickPulseStateManager.js","sourceRoot":"","sources":["../../Library/QuickPulseStateManager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,mCAAsC;AAEtC,uEAA0E;AAC1E,qDAAwD;AACxD,qDAAwD;AACxD,mCAAsC;AAMtC,4DAA4D;AAC5D;IAuBI,gCAAY,MAAc,EAAE,OAAiB,EAAE,uBAAkE;QAZzG,sBAAiB,GAAY,KAAK,CAAC;QAGnC,qBAAgB,GAAW,IAAI,CAAC,GAAG,EAAE,CAAC;QACtC,uBAAkB,GAAY,IAAI,CAAC;QAEnC,aAAQ,GAA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,IAAI,CAAC,iBAAiB,GAAG,UAAU,CAAC;YAEpC,IAAI,cAAc,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;gBAC7C,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;gBACtC,OAAO,CAAC,IAAI,CAAC,2BAA2B,EAAE,cAAc,CAAC,CAAC;aAC7D;YAED,IAAI,mBAAmB,IAAI,mBAAmB,GAAG,CAAC,EAAE;gBAChD,IAAI,CAAC,oBAAoB,GAAG,mBAAmB,CAAC;aACnD;YAED,IAAI,GAAG,IAAI,GAAG,CAAC,UAAU,GAAG,GAAG,IAAI,GAAG,CAAC,UAAU,IAAI,GAAG,EAAE;gBACtD,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;gBACnC,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC;aAClC;iBAAM;gBACH,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC;aACnC;SACJ;aAAM;YACH,0CAA0C;YAC1C,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC;SACnC;IACL,CAAC;IA/Kc,yCAAkB,GAAG,KAAK,CAAC;IAC3B,yCAAkB,GAAG,KAAK,CAAC;IAC3B,wCAAiB,GAAG,KAAK,CAAC;IAC1B,oCAAa,GAAG,IAAI,CAAC;IACrB,oCAAa,GAAG,IAAI,CAAC;IA4KxC,6BAAC;CAAA,AArLD,IAqLC;AAED,iBAAS,sBAAsB,CAAC","sourcesContent":["import AuthorizationHandler = require(\"./AuthorizationHandler\");\r\nimport Logging = require(\"./Logging\");\r\nimport Config = require(\"./Config\");\r\nimport QuickPulseEnvelopeFactory = require(\"./QuickPulseEnvelopeFactory\");\r\nimport QuickPulseSender = require(\"./QuickPulseSender\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport Context = require(\"./Context\");\r\n\r\nimport * as http from \"http\";\r\nimport * as Contracts from \"../Declarations/Contracts\";\r\n\r\n\r\n/** State Container for sending to the QuickPulse Service */\r\nclass QuickPulseStateManager {\r\n public config: Config;\r\n public context: Context;\r\n public authorizationHandler: AuthorizationHandler;\r\n\r\n private static MAX_POST_WAIT_TIME = 20000;\r\n private static MAX_PING_WAIT_TIME = 60000;\r\n private static FALLBACK_INTERVAL = 60000;\r\n private static PING_INTERVAL = 5000;\r\n private static POST_INTERVAL = 1000;\r\n\r\n private _isCollectingData: boolean = false;\r\n private _sender: QuickPulseSender;\r\n private _isEnabled: boolean;\r\n private _lastSuccessTime: number = Date.now();\r\n private _lastSendSucceeded: boolean = true;\r\n private _handle: NodeJS.Timer;\r\n private _metrics: { [name: string]: Contracts.MetricQuickPulse } = {};\r\n private _documents: Contracts.DocumentQuickPulse[] = [];\r\n private _collectors: { enable: (enable: boolean) => void }[] = [];\r\n private _redirectedHost: string = null;\r\n private _pollingIntervalHint: number = -1;\r\n\r\n constructor(config: Config, context?: Context, getAuthorizationHandler?: (config: Config) => AuthorizationHandler) {\r\n this.config = config;\r\n this.context = context || new Context();\r\n this._sender = new QuickPulseSender(this.config, getAuthorizationHandler);\r\n this._isEnabled = false;\r\n }\r\n\r\n /**\r\n *\r\n * @param collector\r\n */\r\n public addCollector(collector: any): void {\r\n this._collectors.push(collector);\r\n }\r\n\r\n /**\r\n * Override of TelemetryClient.trackMetric\r\n */\r\n public trackMetric(telemetry: Contracts.MetricTelemetry): void {\r\n this._addMetric(telemetry);\r\n }\r\n\r\n /**\r\n * Add a document to the current buffer\r\n * @param envelope\r\n */\r\n public addDocument(envelope: Contracts.Envelope): void {\r\n // Only add documents in buffer when Live Metrics is collecting data\r\n if (this._isCollectingData) {\r\n const document = QuickPulseEnvelopeFactory.telemetryEnvelopeToQuickPulseDocument(envelope);\r\n if (document) {\r\n this._documents.push(document);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Enable or disable communication with QuickPulseService\r\n * @param isEnabled\r\n */\r\n public enable(isEnabled: boolean): void {\r\n if (isEnabled && !this._isEnabled) {\r\n this._isEnabled = true;\r\n this._goQuickPulse();\r\n } else if (!isEnabled && this._isEnabled) {\r\n this._isEnabled = false;\r\n clearTimeout(this._handle);\r\n this._handle = undefined;\r\n }\r\n }\r\n\r\n /**\r\n * Enable or disable all collectors in this instance\r\n * @param enable\r\n */\r\n private enableCollectors(enable: boolean): void {\r\n this._collectors.forEach(collector => {\r\n collector.enable(enable)\r\n });\r\n }\r\n\r\n /**\r\n * Add the metric to this buffer. If same metric already exists in this buffer, add weight to it\r\n * @param telemetry\r\n */\r\n private _addMetric(telemetry: Contracts.MetricTelemetry) {\r\n const { value } = telemetry;\r\n const count = telemetry.count || 1;\r\n\r\n let name = Constants.PerformanceToQuickPulseCounter[telemetry.name];\r\n if (name) {\r\n if (this._metrics[name]) {\r\n this._metrics[name].Value = (this._metrics[name].Value * this._metrics[name].Weight + value * count) / (this._metrics[name].Weight + count);\r\n this._metrics[name].Weight += count;\r\n } else {\r\n this._metrics[name] = QuickPulseEnvelopeFactory.createQuickPulseMetric(telemetry);\r\n this._metrics[name].Name = name;\r\n this._metrics[name].Weight = 1;\r\n }\r\n }\r\n }\r\n\r\n private _resetQuickPulseBuffer(): void {\r\n delete this._metrics;\r\n this._metrics = {};\r\n this._documents.length = 0;\r\n }\r\n\r\n private async _goQuickPulse(): Promise {\r\n // Create envelope from Documents and Metrics\r\n const metrics = Object.keys(this._metrics).map(k => this._metrics[k]);\r\n const envelope = QuickPulseEnvelopeFactory.createQuickPulseEnvelope(metrics, this._documents.slice(), this.config, this.context);\r\n\r\n // Clear this document, metric buffer\r\n this._resetQuickPulseBuffer();\r\n\r\n // Send it to QuickPulseService, if collecting\r\n if (this._isCollectingData) {\r\n await this._post(envelope);\r\n } else {\r\n this._ping(envelope);\r\n }\r\n\r\n let pingInterval = this._pollingIntervalHint > 0 ? this._pollingIntervalHint : QuickPulseStateManager.PING_INTERVAL;\r\n let currentTimeout = this._isCollectingData ? QuickPulseStateManager.POST_INTERVAL : pingInterval;\r\n if (this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_POST_WAIT_TIME && !this._lastSendSucceeded) {\r\n // Haven't posted successfully in 20 seconds, so wait 60 seconds and ping\r\n this._isCollectingData = false;\r\n currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL;\r\n } else if (!this._isCollectingData && Date.now() - this._lastSuccessTime >= QuickPulseStateManager.MAX_PING_WAIT_TIME && !this._lastSendSucceeded) {\r\n // Haven't pinged successfully in 60 seconds, so wait another 60 seconds\r\n currentTimeout = QuickPulseStateManager.FALLBACK_INTERVAL;\r\n }\r\n this._lastSendSucceeded = null;\r\n this._handle = setTimeout(this._goQuickPulse.bind(this), currentTimeout);\r\n this._handle.unref(); // Don't block apps from terminating\r\n }\r\n\r\n private _ping(envelope: Contracts.EnvelopeQuickPulse): void {\r\n this._sender.ping(envelope, this._redirectedHost, this._quickPulseDone.bind(this));\r\n }\r\n\r\n private async _post(envelope: Contracts.EnvelopeQuickPulse): Promise {\r\n await this._sender.post(envelope, this._redirectedHost, this._quickPulseDone.bind(this));\r\n }\r\n\r\n /**\r\n * Change the current QPS send state. (shouldPOST == undefined) --> error, but do not change the state yet.\r\n */\r\n private _quickPulseDone(shouldPOST?: boolean, res?: http.IncomingMessage,\r\n redirectedHost?: string, pollingIntervalHint?: number): void {\r\n if (shouldPOST != undefined) {\r\n if (this._isCollectingData !== shouldPOST) {\r\n Logging.info(\"Live Metrics sending data\", shouldPOST);\r\n this.enableCollectors(shouldPOST);\r\n }\r\n this._isCollectingData = shouldPOST;\r\n\r\n if (redirectedHost && redirectedHost.length > 0) {\r\n this._redirectedHost = redirectedHost;\r\n Logging.info(\"Redirecting endpoint to: \", redirectedHost);\r\n }\r\n\r\n if (pollingIntervalHint && pollingIntervalHint > 0) {\r\n this._pollingIntervalHint = pollingIntervalHint;\r\n }\r\n\r\n if (res && res.statusCode < 300 && res.statusCode >= 200) {\r\n this._lastSuccessTime = Date.now();\r\n this._lastSendSucceeded = true;\r\n } else {\r\n this._lastSendSucceeded = false;\r\n }\r\n } else {\r\n // Received an error, keep the state as is\r\n this._lastSendSucceeded = false;\r\n }\r\n }\r\n}\r\n\r\nexport = QuickPulseStateManager;"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseUtil.d.ts b/node_modules/applicationinsights/out/Library/QuickPulseUtil.d.ts new file mode 100644 index 0000000..3b65d12 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseUtil.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + getTransmissionTime: () => number; +}; +export = _default; diff --git a/node_modules/applicationinsights/out/Library/QuickPulseUtil.js b/node_modules/applicationinsights/out/Library/QuickPulseUtil.js new file mode 100644 index 0000000..c63e9cd --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseUtil.js @@ -0,0 +1,15 @@ +"use strict"; +/** + * @description UTC time the request was made. Expressed as the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight on January 1, 0001. This is used for clock skew calculations, so the value can never be stale (cached). + * + * @example + * 8/5/2020 10:15:00 PM UTC => 637322625000000000 + * 8/5/2020 10:15:01 PM UTC => 637322625010000000 + * + * @returns {number} + */ +var getTransmissionTime = function () { + return (Date.now() + 62135596800000) * 10000; +}; +module.exports = { getTransmissionTime: getTransmissionTime }; +//# sourceMappingURL=QuickPulseUtil.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/QuickPulseUtil.js.map b/node_modules/applicationinsights/out/Library/QuickPulseUtil.js.map new file mode 100644 index 0000000..ab39a7a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/QuickPulseUtil.js.map @@ -0,0 +1 @@ +{"version":3,"file":"QuickPulseUtil.js","sourceRoot":"","sources":["../../Library/QuickPulseUtil.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;AACH,IAAM,mBAAmB,GAAG;IACxB,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,cAAc,CAAC,GAAG,KAAK,CAAC;AACjD,CAAC,CAAA;AAED,iBAAS,EAAC,mBAAmB,qBAAA,EAAC,CAAC","sourcesContent":["/**\r\n * @description UTC time the request was made. Expressed as the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight on January 1, 0001. This is used for clock skew calculations, so the value can never be stale (cached).\r\n *\r\n * @example\r\n * 8/5/2020 10:15:00 PM UTC => 637322625000000000\r\n * 8/5/2020 10:15:01 PM UTC => 637322625010000000\r\n *\r\n * @returns {number}\r\n */\r\nconst getTransmissionTime = (): number => {\r\n return (Date.now() + 62135596800000) * 10000;\r\n}\r\n\r\nexport = {getTransmissionTime};\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/RequestResponseHeaders.d.ts b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.d.ts new file mode 100644 index 0000000..1b5623e --- /dev/null +++ b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.d.ts @@ -0,0 +1,44 @@ +declare const _default: { + /** + * Request-Context header + */ + requestContextHeader: string; + /** + * Source instrumentation header that is added by an application while making http + * requests and retrieved by the other application when processing incoming requests. + */ + requestContextSourceKey: string; + /** + * Target instrumentation header that is added to the response and retrieved by the + * calling application when processing incoming responses. + */ + requestContextTargetKey: string; + /** + * Request-Id header + */ + requestIdHeader: string; + /** + * Legacy Header containing the id of the immediate caller + */ + parentIdHeader: string; + /** + * Legacy Header containing the correlation id that kept the same for every telemetry item + * across transactions + */ + rootIdHeader: string; + /** + * Correlation-Context header + * + * Not currently actively used, but the contents should be passed from incoming to outgoing requests + */ + correlationContextHeader: string; + /** + * W3C distributed tracing protocol header + */ + traceparentHeader: string; + /** + * W3C distributed tracing protocol state header + */ + traceStateHeader: string; +}; +export = _default; diff --git a/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js new file mode 100644 index 0000000..80766fe --- /dev/null +++ b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js @@ -0,0 +1,45 @@ +"use strict"; +module.exports = { + /** + * Request-Context header + */ + requestContextHeader: "request-context", + /** + * Source instrumentation header that is added by an application while making http + * requests and retrieved by the other application when processing incoming requests. + */ + requestContextSourceKey: "appId", + /** + * Target instrumentation header that is added to the response and retrieved by the + * calling application when processing incoming responses. + */ + requestContextTargetKey: "appId", + /** + * Request-Id header + */ + requestIdHeader: "request-id", + /** + * Legacy Header containing the id of the immediate caller + */ + parentIdHeader: "x-ms-request-id", + /** + * Legacy Header containing the correlation id that kept the same for every telemetry item + * across transactions + */ + rootIdHeader: "x-ms-request-root-id", + /** + * Correlation-Context header + * + * Not currently actively used, but the contents should be passed from incoming to outgoing requests + */ + correlationContextHeader: "correlation-context", + /** + * W3C distributed tracing protocol header + */ + traceparentHeader: "traceparent", + /** + * W3C distributed tracing protocol state header + */ + traceStateHeader: "tracestate" +}; +//# sourceMappingURL=RequestResponseHeaders.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js.map b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js.map new file mode 100644 index 0000000..558efec --- /dev/null +++ b/node_modules/applicationinsights/out/Library/RequestResponseHeaders.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RequestResponseHeaders.js","sourceRoot":"","sources":["../../Library/RequestResponseHeaders.ts"],"names":[],"mappings":";AAAA,iBAAS;IAEL;;OAEG;IACH,oBAAoB,EAAE,iBAAiB;IAEvC;;;OAGG;IACH,uBAAuB,EAAE,OAAO;IAEhC;;;OAGG;IACH,uBAAuB,EAAE,OAAO;IAEhC;;OAEG;IACH,eAAe,EAAE,YAAY;IAE7B;;OAEG;IACH,cAAc,EAAE,iBAAiB;IAEjC;;;OAGG;IACH,YAAY,EAAE,sBAAsB;IAEpC;;;;OAIG;IACH,wBAAwB,EAAE,qBAAqB;IAE/C;;OAEG;IACH,iBAAiB,EAAE,aAAa;IAEhC;;OAEG;IACH,gBAAgB,EAAE,YAAY;CACjC,CAAA","sourcesContent":["export = {\r\n\r\n /**\r\n * Request-Context header\r\n */\r\n requestContextHeader: \"request-context\",\r\n\r\n /**\r\n * Source instrumentation header that is added by an application while making http\r\n * requests and retrieved by the other application when processing incoming requests.\r\n */\r\n requestContextSourceKey: \"appId\",\r\n\r\n /**\r\n * Target instrumentation header that is added to the response and retrieved by the\r\n * calling application when processing incoming responses.\r\n */\r\n requestContextTargetKey: \"appId\",\r\n\r\n /**\r\n * Request-Id header\r\n */\r\n requestIdHeader: \"request-id\",\r\n\r\n /**\r\n * Legacy Header containing the id of the immediate caller\r\n */\r\n parentIdHeader: \"x-ms-request-id\",\r\n\r\n /**\r\n * Legacy Header containing the correlation id that kept the same for every telemetry item\r\n * across transactions\r\n */\r\n rootIdHeader: \"x-ms-request-root-id\",\r\n\r\n /**\r\n * Correlation-Context header\r\n *\r\n * Not currently actively used, but the contents should be passed from incoming to outgoing requests\r\n */\r\n correlationContextHeader: \"correlation-context\",\r\n\r\n /**\r\n * W3C distributed tracing protocol header\r\n */\r\n traceparentHeader: \"traceparent\",\r\n\r\n /**\r\n * W3C distributed tracing protocol state header\r\n */\r\n traceStateHeader: \"tracestate\"\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Sender.d.ts b/node_modules/applicationinsights/out/Library/Sender.d.ts new file mode 100644 index 0000000..d83c0f7 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Sender.d.ts @@ -0,0 +1,61 @@ +import AuthorizationHandler = require("./AuthorizationHandler"); +import Config = require("./Config"); +import Contracts = require("../Declarations/Contracts"); +import Statsbeat = require("../AutoCollection/Statsbeat"); +declare class Sender { + private static TAG; + static WAIT_BETWEEN_RESEND: number; + static MAX_BYTES_ON_DISK: number; + static MAX_CONNECTION_FAILURES_BEFORE_WARN: number; + static CLEANUP_TIMEOUT: number; + static FILE_RETEMPTION_PERIOD: number; + static TEMPDIR_PREFIX: string; + static HTTP_TIMEOUT: number; + private _config; + private _isStatsbeatSender; + private _shutdownStatsbeat; + private _failedToIngestCounter; + private _statsbeatHasReachedIngestionAtLeastOnce; + private _statsbeat; + private _onSuccess; + private _onError; + private _getAuthorizationHandler; + private _enableDiskRetryMode; + private _numConsecutiveFailures; + private _numConsecutiveRedirects; + private _resendTimer; + private _fileCleanupTimer; + private _redirectedHost; + private _tempDir; + private _requestTimedOut; + protected _resendInterval: number; + protected _maxBytesOnDisk: number; + constructor(config: Config, getAuthorizationHandler?: (config: Config) => AuthorizationHandler, onSuccess?: (response: string) => void, onError?: (error: Error) => void, statsbeat?: Statsbeat, isStatsbeatSender?: boolean, shutdownStatsbeat?: () => void); + /** + * Enable or disable offline mode + */ + setDiskRetryMode(value: boolean, resendInterval?: number, maxBytesOnDisk?: number): void; + send(envelopes: Contracts.EnvelopeTelemetry[], callback?: (v: string) => void): Promise; + saveOnCrash(envelopes: Contracts.EnvelopeTelemetry[]): void; + private _isRetriable; + private _logInfo; + private _logWarn; + private _statsbeatFailedToIngest; + /** + * Stores the payload as a json file on disk in the temp directory + */ + private _storeToDisk; + /** + * Stores the payload as a json file on disk using sync file operations + * this is used when storing data before crashes + */ + private _storeToDiskSync; + /** + * Check for temp telemetry files + * reads the first file if exist, deletes it and tries to send its load + */ + private _sendFirstFileOnDisk; + private _onErrorHelper; + private _fileCleanupTask; +} +export = Sender; diff --git a/node_modules/applicationinsights/out/Library/Sender.js b/node_modules/applicationinsights/out/Library/Sender.js new file mode 100644 index 0000000..3ec9153 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Sender.js @@ -0,0 +1,581 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (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 }; + } +}; +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var zlib = require("zlib"); +var Constants = require("../Declarations/Constants"); +var AutoCollectHttpDependencies = require("../AutoCollection/HttpDependencies"); +var FileSystemHelper = require("./FileSystemHelper"); +var Util = require("./Util"); +var url_1 = require("url"); +var Logging = require("./Logging"); +var FileAccessControl_1 = require("./FileAccessControl"); +var legacyThrottleStatusCode = 439; // - Too many requests and refresh cache +var throttleStatusCode = 402; // Monthly Quota Exceeded (new SDK) +var RESPONSE_CODES_INDICATING_REACHED_BREEZE = [200, 206, 402, 408, 429, 439, 500]; +var Sender = /** @class */ (function () { + function Sender(config, getAuthorizationHandler, onSuccess, onError, statsbeat, isStatsbeatSender, shutdownStatsbeat) { + this._redirectedHost = null; + this._config = config; + this._onSuccess = onSuccess; + this._onError = onError; + this._statsbeat = statsbeat; + this._enableDiskRetryMode = false; + this._resendInterval = Sender.WAIT_BETWEEN_RESEND; + this._maxBytesOnDisk = Sender.MAX_BYTES_ON_DISK; + this._numConsecutiveFailures = 0; + this._numConsecutiveRedirects = 0; + this._resendTimer = null; + this._getAuthorizationHandler = getAuthorizationHandler; + this._fileCleanupTimer = null; + // tmpdir is /tmp for *nix and USERDIR/AppData/Local/Temp for Windows + this._tempDir = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey); + this._isStatsbeatSender = isStatsbeatSender || false; + this._shutdownStatsbeat = shutdownStatsbeat; + this._failedToIngestCounter = 0; + this._statsbeatHasReachedIngestionAtLeastOnce = false; + } + /** + * Enable or disable offline mode + */ + Sender.prototype.setDiskRetryMode = function (value, resendInterval, maxBytesOnDisk) { + var _this = this; + if (value) { + FileAccessControl_1.FileAccessControl.checkFileProtection(); // Only check file protection when disk retry is enabled + } + this._enableDiskRetryMode = FileAccessControl_1.FileAccessControl.OS_PROVIDES_FILE_PROTECTION && value; + if (typeof resendInterval === "number" && resendInterval >= 0) { + this._resendInterval = Math.floor(resendInterval); + } + if (typeof maxBytesOnDisk === "number" && maxBytesOnDisk >= 0) { + this._maxBytesOnDisk = Math.floor(maxBytesOnDisk); + } + if (value && !FileAccessControl_1.FileAccessControl.OS_PROVIDES_FILE_PROTECTION) { + this._enableDiskRetryMode = false; + this._logWarn("Ignoring request to enable disk retry mode. Sufficient file protection capabilities were not detected."); + } + if (this._enableDiskRetryMode) { + if (this._statsbeat) { + this._statsbeat.addFeature(Constants.StatsbeatFeature.DISK_RETRY); + } + // Starts file cleanup task + if (!this._fileCleanupTimer) { + this._fileCleanupTimer = setTimeout(function () { _this._fileCleanupTask(); }, Sender.CLEANUP_TIMEOUT); + this._fileCleanupTimer.unref(); + } + } + else { + if (this._statsbeat) { + this._statsbeat.removeFeature(Constants.StatsbeatFeature.DISK_RETRY); + } + if (this._fileCleanupTimer) { + clearTimeout(this._fileCleanupTimer); + } + } + }; + Sender.prototype.send = function (envelopes, callback) { + return __awaiter(this, void 0, void 0, function () { + var endpointUrl, endpointHost, options, authHandler, authError_1, errorMsg, batch_1, payload_1; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!envelopes) return [3 /*break*/, 5]; + endpointUrl = this._redirectedHost || this._config.endpointUrl; + endpointHost = new url_1.URL(endpointUrl).hostname; + options = { + method: "POST", + withCredentials: false, + headers: { + "Content-Type": "application/x-json-stream" + } + }; + authHandler = this._getAuthorizationHandler ? this._getAuthorizationHandler(this._config) : null; + if (!authHandler) return [3 /*break*/, 4]; + if (this._statsbeat) { + this._statsbeat.addFeature(Constants.StatsbeatFeature.AAD_HANDLING); + } + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + // Add bearer token + return [4 /*yield*/, authHandler.addAuthorizationHeader(options)]; + case 2: + // Add bearer token + _a.sent(); + return [3 /*break*/, 4]; + case 3: + authError_1 = _a.sent(); + errorMsg = "Failed to get AAD bearer token for the Application."; + if (this._enableDiskRetryMode) { + errorMsg += "This batch of telemetry items will be retried. "; + this._storeToDisk(envelopes); + } + errorMsg += "Error:" + authError_1.toString(); + this._logWarn(errorMsg); + if (typeof callback === "function") { + callback(errorMsg); + } + return [2 /*return*/]; // If AAD auth fails do not send to Breeze + case 4: + batch_1 = ""; + envelopes.forEach(function (envelope) { + var payload = Util.stringify(envelope); + if (typeof payload !== "string") { + return; + } + batch_1 += payload + "\n"; + }); + // Remove last \n + if (batch_1.length > 0) { + batch_1 = batch_1.substring(0, batch_1.length - 1); + } + payload_1 = Buffer.from ? Buffer.from(batch_1) : new Buffer(batch_1); + zlib.gzip(payload_1, function (err, buffer) { + var dataToSend = buffer; + if (err) { + _this._logWarn(Util.dumpObj(err)); + dataToSend = payload_1; // something went wrong so send without gzip + options.headers["Content-Length"] = payload_1.length.toString(); + } + else { + options.headers["Content-Encoding"] = "gzip"; + options.headers["Content-Length"] = buffer.length.toString(); + } + _this._logInfo(Util.dumpObj(options)); + // Ensure this request is not captured by auto-collection. + options[AutoCollectHttpDependencies.disableCollectionRequestOption] = true; + var startTime = +new Date(); + var requestCallback = function (res) { + res.setEncoding("utf-8"); + //returns empty if the data is accepted + var responseString = ""; + res.on("data", function (data) { + responseString += data; + }); + res.on("end", function () { + var endTime = +new Date(); + var duration = endTime - startTime; + _this._numConsecutiveFailures = 0; + // Handling of Statsbeat instance sending data, should turn it off if is not able to reach ingestion endpoint + if (_this._isStatsbeatSender && !_this._statsbeatHasReachedIngestionAtLeastOnce) { + if (RESPONSE_CODES_INDICATING_REACHED_BREEZE.includes(res.statusCode)) { + _this._statsbeatHasReachedIngestionAtLeastOnce = true; + } + else { + _this._statsbeatFailedToIngest(); + } + } + if (_this._statsbeat) { + if (res.statusCode == throttleStatusCode || res.statusCode == legacyThrottleStatusCode) { // Throttle + _this._statsbeat.countThrottle(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, res.statusCode); + } + else { + _this._statsbeat.countRequest(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, duration, res.statusCode === 200, res.statusCode); + } + } + if (_this._enableDiskRetryMode) { + // try to send any cached events if the user is back online + if (res.statusCode === 200) { + if (!_this._resendTimer) { + _this._resendTimer = setTimeout(function () { + _this._resendTimer = null; + _this._sendFirstFileOnDisk(); + }, _this._resendInterval); + _this._resendTimer.unref(); + } + } + else if (_this._isRetriable(res.statusCode)) { + try { + if (_this._statsbeat) { + _this._statsbeat.countRetry(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, res.statusCode); + } + var breezeResponse = JSON.parse(responseString); + var filteredEnvelopes_1 = []; + if (breezeResponse.errors) { + breezeResponse.errors.forEach(function (error) { + // Only retry errors if 429, 500 or 503 response codes + if (error.statusCode == 429 || error.statusCode == 500 || error.statusCode == 503) { + filteredEnvelopes_1.push(envelopes[error.index]); + } + }); + if (filteredEnvelopes_1.length > 0) { + _this._storeToDisk(filteredEnvelopes_1); + } + } + } + catch (ex) { + _this._storeToDisk(envelopes); // Retriable status code with not valid Breeze response + } + } + } + // Redirect handling + if (res.statusCode === 307 || // Temporary Redirect + res.statusCode === 308) { // Permanent Redirect + _this._numConsecutiveRedirects++; + // To prevent circular redirects + if (_this._numConsecutiveRedirects < 10) { + // Try to get redirect header + var locationHeader = res.headers["location"] ? res.headers["location"].toString() : null; + if (locationHeader) { + _this._redirectedHost = locationHeader; + // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically + _this.send(envelopes, callback); + } + } + else { + var circularRedirectError = { name: "Circular Redirect", message: "Error sending telemetry because of circular redirects." }; + if (_this._statsbeat) { + _this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, circularRedirectError); + } + if (typeof callback === "function") { + callback("Error sending telemetry because of circular redirects."); + } + } + } + else { + _this._numConsecutiveRedirects = 0; + if (typeof callback === "function") { + callback(responseString); + } + _this._logInfo(responseString); + if (typeof _this._onSuccess === "function") { + _this._onSuccess(responseString); + } + } + }); + }; + var req = Util.makeRequest(_this._config, endpointUrl, options, requestCallback); + // Needed as of Node.js v13 default timeouts on HTTP requests are no longer default + // Timeout should trigger the request on error function to run + req.setTimeout(Sender.HTTP_TIMEOUT, function () { + _this._requestTimedOut = true; + req.abort(); + }); + req.on("error", function (error) { + if (_this._isStatsbeatSender && !_this._statsbeatHasReachedIngestionAtLeastOnce) { + _this._statsbeatFailedToIngest(); + } + // todo: handle error codes better (group to recoverable/non-recoverable and persist) + _this._numConsecutiveFailures++; + if (_this._statsbeat) { + _this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, error); + } + // Only use warn level if retries are disabled or we've had some number of consecutive failures sending data + // This is because warn level is printed in the console by default, and we don't want to be noisy for transient and self-recovering errors + // Continue informing on each failure if verbose logging is being used + if (!_this._enableDiskRetryMode || _this._numConsecutiveFailures > 0 && _this._numConsecutiveFailures % Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN === 0) { + var notice = "Ingestion endpoint could not be reached. This batch of telemetry items has been lost. Use Disk Retry Caching to enable resending of failed telemetry. Error:"; + if (_this._enableDiskRetryMode) { + notice = "Ingestion endpoint could not be reached " + _this._numConsecutiveFailures + " consecutive times. There may be resulting telemetry loss. Most recent error:"; + } + _this._logWarn(notice, Util.dumpObj(error)); + } + else { + var notice = "Transient failure to reach ingestion endpoint. This batch of telemetry items will be retried. Error:"; + _this._logInfo(notice, Util.dumpObj(error)); + } + _this._onErrorHelper(error); + if (typeof callback === "function") { + if (error) { + // If the error type is a timeout we want to provide more meaningful output + if (_this._requestTimedOut) { + error.name = "telemetry timeout"; + error.message = "telemetry request timed out"; + } + callback(Util.dumpObj(error)); + } + else { + callback("Error sending telemetry"); + } + } + if (_this._enableDiskRetryMode) { + _this._storeToDisk(envelopes); + } + }); + req.write(dataToSend); + req.end(); + }); + _a.label = 5; + case 5: return [2 /*return*/]; + } + }); + }); + }; + Sender.prototype.saveOnCrash = function (envelopes) { + if (this._enableDiskRetryMode) { + this._storeToDiskSync(Util.stringify(envelopes)); + } + }; + Sender.prototype._isRetriable = function (statusCode) { + return (statusCode === 206 || // Partial Accept + statusCode === 401 || // Unauthorized + statusCode === 403 || // Forbidden + statusCode === 408 || // Timeout + statusCode === 429 || // Too many requests + statusCode === 500 || // Server Error + statusCode === 502 || // Bad Gateway + statusCode === 503 || // Server Unavailable + statusCode === 504 // Gateway Timeout + ); + }; + Sender.prototype._logInfo = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + if (!this._isStatsbeatSender) { + Logging.info(Sender.TAG, message, optionalParams); + } + }; + Sender.prototype._logWarn = function (message) { + var optionalParams = []; + for (var _i = 1; _i < arguments.length; _i++) { + optionalParams[_i - 1] = arguments[_i]; + } + if (!this._isStatsbeatSender) { + Logging.warn(Sender.TAG, message, optionalParams); + } + }; + Sender.prototype._statsbeatFailedToIngest = function () { + if (this._shutdownStatsbeat) { // Check if callback is available + this._failedToIngestCounter++; + if (this._failedToIngestCounter >= 3) { + this._shutdownStatsbeat(); + } + } + }; + /** + * Stores the payload as a json file on disk in the temp directory + */ + Sender.prototype._storeToDisk = function (envelopes) { + return __awaiter(this, void 0, void 0, function () { + var ex_1, ex_2, size, ex_3, fileName, fileFullPath, ex_4; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + this._logInfo("Checking existence of data storage directory: " + this._tempDir); + return [4 /*yield*/, FileSystemHelper.confirmDirExists(this._tempDir)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + ex_1 = _a.sent(); + this._logWarn("Failed to create folder to put telemetry: " + Util.dumpObj(ex_1)); + this._onErrorHelper(ex_1); + return [2 /*return*/]; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, FileAccessControl_1.FileAccessControl.applyACLRules(this._tempDir)]; + case 4: + _a.sent(); + return [3 /*break*/, 6]; + case 5: + ex_2 = _a.sent(); + this._logWarn("Failed to apply file access control to folder: " + Util.dumpObj(ex_2)); + this._onErrorHelper(ex_2); + return [2 /*return*/]; + case 6: + _a.trys.push([6, 8, , 9]); + return [4 /*yield*/, FileSystemHelper.getShallowDirectorySize(this._tempDir)]; + case 7: + size = _a.sent(); + if (size > this._maxBytesOnDisk) { + this._logWarn("Not saving data due to max size limit being met. Directory size in bytes is: " + size); + return [2 /*return*/]; + } + return [3 /*break*/, 9]; + case 8: + ex_3 = _a.sent(); + this._logWarn("Failed to read directory for retriable telemetry: " + Util.dumpObj(ex_3)); + this._onErrorHelper(ex_3); + return [2 /*return*/]; + case 9: + _a.trys.push([9, 11, , 12]); + fileName = new Date().getTime() + ".ai.json"; + fileFullPath = path.join(this._tempDir, fileName); + // Mode 600 is w/r for creator and no read access for others (only applies on *nix) + // For Windows, ACL rules are applied to the entire directory (see logic in _confirmDirExists and _applyACLRules) + this._logInfo("saving data to disk at: " + fileFullPath); + return [4 /*yield*/, FileSystemHelper.writeFileAsync(fileFullPath, Util.stringify(envelopes), { mode: 384 })]; + case 10: + _a.sent(); + return [3 /*break*/, 12]; + case 11: + ex_4 = _a.sent(); + this._logWarn("Failed to persist telemetry to disk: " + Util.dumpObj(ex_4)); + this._onErrorHelper(ex_4); + return [2 /*return*/]; + case 12: return [2 /*return*/]; + } + }); + }); + }; + /** + * Stores the payload as a json file on disk using sync file operations + * this is used when storing data before crashes + */ + Sender.prototype._storeToDiskSync = function (payload) { + try { + this._logInfo("Checking existence of data storage directory: " + this._tempDir); + if (!fs.existsSync(this._tempDir)) { + fs.mkdirSync(this._tempDir); + } + // Make sure permissions are valid + FileAccessControl_1.FileAccessControl.applyACLRulesSync(this._tempDir); + var dirSize = FileSystemHelper.getShallowDirectorySizeSync(this._tempDir); + if (dirSize > this._maxBytesOnDisk) { + this._logInfo("Not saving data due to max size limit being met. Directory size in bytes is: " + dirSize); + return; + } + //create file - file name for now is the timestamp, a better approach would be a UUID but that + //would require an external dependency + var fileName = new Date().getTime() + ".ai.json"; + var fileFullPath = path.join(this._tempDir, fileName); + // Mode 600 is w/r for creator and no access for anyone else (only applies on *nix) + this._logInfo("saving data before crash to disk at: " + fileFullPath); + fs.writeFileSync(fileFullPath, payload, { mode: 384 }); + } + catch (error) { + this._logWarn("Error while saving data to disk: " + Util.dumpObj(error)); + this._onErrorHelper(error); + } + }; + /** + * Check for temp telemetry files + * reads the first file if exist, deletes it and tries to send its load + */ + Sender.prototype._sendFirstFileOnDisk = function () { + return __awaiter(this, void 0, void 0, function () { + var files, firstFile, filePath, buffer, envelopes, err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 6, , 7]); + return [4 /*yield*/, FileSystemHelper.readdirAsync(this._tempDir)]; + case 1: + files = _a.sent(); + files = files.filter(function (f) { return path.basename(f).indexOf(".ai.json") > -1; }); + if (!(files.length > 0)) return [3 /*break*/, 5]; + firstFile = files[0]; + filePath = path.join(this._tempDir, firstFile); + return [4 /*yield*/, FileSystemHelper.readFileAsync(filePath)]; + case 2: + buffer = _a.sent(); + // delete the file first to prevent double sending + return [4 /*yield*/, FileSystemHelper.unlinkAsync(filePath)]; + case 3: + // delete the file first to prevent double sending + _a.sent(); + envelopes = JSON.parse(buffer.toString()); + return [4 /*yield*/, this.send(envelopes)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: return [3 /*break*/, 7]; + case 6: + err_1 = _a.sent(); + this._onErrorHelper(err_1); + return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + Sender.prototype._onErrorHelper = function (error) { + if (typeof this._onError === "function") { + this._onError(error); + } + }; + Sender.prototype._fileCleanupTask = function () { + return __awaiter(this, void 0, void 0, function () { + var files, i, fileCreationDate, expired, filePath, err_2; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 6, , 7]); + return [4 /*yield*/, FileSystemHelper.readdirAsync(this._tempDir)]; + case 1: + files = _a.sent(); + files = files.filter(function (f) { return path.basename(f).indexOf(".ai.json") > -1; }); + if (!(files.length > 0)) return [3 /*break*/, 5]; + i = 0; + _a.label = 2; + case 2: + if (!(i < files.length)) return [3 /*break*/, 5]; + fileCreationDate = new Date(parseInt(files[i].split(".ai.json")[0])); + expired = new Date(+(new Date()) - Sender.FILE_RETEMPTION_PERIOD) > fileCreationDate; + if (!expired) return [3 /*break*/, 4]; + filePath = path.join(this._tempDir, files[i]); + return [4 /*yield*/, FileSystemHelper.unlinkAsync(filePath).catch(function (err) { + _this._onErrorHelper(err); + })]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 7]; + case 6: + err_2 = _a.sent(); + if (err_2.code != "ENOENT") { + this._onErrorHelper(err_2); + } + return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); + }); + }; + Sender.TAG = "Sender"; + // the amount of time the SDK will wait between resending cached data, this buffer is to avoid any throttling from the service side + Sender.WAIT_BETWEEN_RESEND = 60 * 1000; // 1 minute + Sender.MAX_BYTES_ON_DISK = 50 * 1024 * 1024; // 50 mb + Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN = 5; + Sender.CLEANUP_TIMEOUT = 60 * 60 * 1000; // 1 hour + Sender.FILE_RETEMPTION_PERIOD = 7 * 24 * 60 * 60 * 1000; // 7 days + Sender.TEMPDIR_PREFIX = "appInsights-node"; + Sender.HTTP_TIMEOUT = 20000; // 20 seconds + return Sender; +}()); +module.exports = Sender; +//# sourceMappingURL=Sender.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Sender.js.map b/node_modules/applicationinsights/out/Library/Sender.js.map new file mode 100644 index 0000000..4952782 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Sender.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Sender.js","sourceRoot":"","sources":["../../Library/Sender.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uBAA0B;AAE1B,uBAA0B;AAC1B,2BAA8B;AAC9B,2BAA8B;AAK9B,qDAAwD;AACxD,gFAAmF;AAEnF,qDAAwD;AACxD,6BAAgC;AAChC,2BAA0B;AAC1B,mCAAsC;AACtC,yDAAwD;AAExD,IAAM,wBAAwB,GAAG,GAAG,CAAC,CAAC,yCAAyC;AAC/E,IAAM,kBAAkB,GAAG,GAAG,CAAC,CAAC,mCAAmC;AACnE,IAAM,wCAAwC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAErF;IA+BI,gBAAY,MAAc,EAAE,uBAAkE,EAAE,SAAsC,EAAE,OAAgC,EAAE,SAAqB,EAAE,iBAA2B,EAAE,iBAA8B;QANpP,oBAAe,GAAW,IAAI,CAAC;QAOnC,IAAI,CAAC,OAAO,GAAG,MAAM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AC,CAAC,SAAS;IAC3C,6BAAsB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;IAC3D,qBAAc,GAAW,kBAAkB,CAAC;IAC5C,mBAAY,GAAW,KAAK,CAAC,CAAC,aAAa;IAif7D,aAAC;CAAA,AA1fD,IA0fC;AAED,iBAAS,MAAM,CAAC","sourcesContent":["import fs = require(\"fs\");\r\nimport http = require(\"http\");\r\nimport os = require(\"os\");\r\nimport path = require(\"path\");\r\nimport zlib = require(\"zlib\");\r\n\r\nimport AuthorizationHandler = require(\"./AuthorizationHandler\");\r\nimport Config = require(\"./Config\")\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport Constants = require(\"../Declarations/Constants\");\r\nimport AutoCollectHttpDependencies = require(\"../AutoCollection/HttpDependencies\");\r\nimport Statsbeat = require(\"../AutoCollection/Statsbeat\");\r\nimport FileSystemHelper = require(\"./FileSystemHelper\");\r\nimport Util = require(\"./Util\");\r\nimport { URL } from \"url\";\r\nimport Logging = require(\"./Logging\");\r\nimport { FileAccessControl } from \"./FileAccessControl\";\r\n\r\nconst legacyThrottleStatusCode = 439; // - Too many requests and refresh cache\r\nconst throttleStatusCode = 402; // Monthly Quota Exceeded (new SDK)\r\nconst RESPONSE_CODES_INDICATING_REACHED_BREEZE = [200, 206, 402, 408, 429, 439, 500];\r\n\r\nclass Sender {\r\n private static TAG = \"Sender\";\r\n // the amount of time the SDK will wait between resending cached data, this buffer is to avoid any throttling from the service side\r\n public static WAIT_BETWEEN_RESEND = 60 * 1000; // 1 minute\r\n public static MAX_BYTES_ON_DISK = 50 * 1024 * 1024; // 50 mb\r\n public static MAX_CONNECTION_FAILURES_BEFORE_WARN = 5;\r\n public static CLEANUP_TIMEOUT = 60 * 60 * 1000; // 1 hour\r\n public static FILE_RETEMPTION_PERIOD = 7 * 24 * 60 * 60 * 1000; // 7 days\r\n public static TEMPDIR_PREFIX: string = \"appInsights-node\";\r\n public static HTTP_TIMEOUT: number = 20000; // 20 seconds\r\n\r\n private _config: Config;\r\n private _isStatsbeatSender: boolean;\r\n private _shutdownStatsbeat: () => void;\r\n private _failedToIngestCounter: number;\r\n private _statsbeatHasReachedIngestionAtLeastOnce: boolean;\r\n private _statsbeat: Statsbeat;\r\n private _onSuccess: (response: string) => void;\r\n private _onError: (error: Error) => void;\r\n private _getAuthorizationHandler: (config: Config) => AuthorizationHandler;\r\n private _enableDiskRetryMode: boolean;\r\n private _numConsecutiveFailures: number;\r\n private _numConsecutiveRedirects: number;\r\n private _resendTimer: NodeJS.Timer | null;\r\n private _fileCleanupTimer: NodeJS.Timer;\r\n private _redirectedHost: string = null;\r\n private _tempDir: string;\r\n private _requestTimedOut: boolean;\r\n protected _resendInterval: number;\r\n protected _maxBytesOnDisk: number;\r\n\r\n constructor(config: Config, getAuthorizationHandler?: (config: Config) => AuthorizationHandler, onSuccess?: (response: string) => void, onError?: (error: Error) => void, statsbeat?: Statsbeat, isStatsbeatSender?: boolean, shutdownStatsbeat?: () => void) {\r\n this._config = config;\r\n this._onSuccess = onSuccess;\r\n this._onError = onError;\r\n this._statsbeat = statsbeat;\r\n this._enableDiskRetryMode = false;\r\n this._resendInterval = Sender.WAIT_BETWEEN_RESEND;\r\n this._maxBytesOnDisk = Sender.MAX_BYTES_ON_DISK;\r\n this._numConsecutiveFailures = 0;\r\n this._numConsecutiveRedirects = 0;\r\n this._resendTimer = null;\r\n this._getAuthorizationHandler = getAuthorizationHandler;\r\n this._fileCleanupTimer = null;\r\n // tmpdir is /tmp for *nix and USERDIR/AppData/Local/Temp for Windows\r\n this._tempDir = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey);\r\n this._isStatsbeatSender = isStatsbeatSender || false;\r\n this._shutdownStatsbeat = shutdownStatsbeat;\r\n this._failedToIngestCounter = 0;\r\n this._statsbeatHasReachedIngestionAtLeastOnce = false;\r\n }\r\n\r\n /**\r\n * Enable or disable offline mode\r\n */\r\n public setDiskRetryMode(value: boolean, resendInterval?: number, maxBytesOnDisk?: number) {\r\n if (value) {\r\n FileAccessControl.checkFileProtection(); // Only check file protection when disk retry is enabled\r\n }\r\n this._enableDiskRetryMode = FileAccessControl.OS_PROVIDES_FILE_PROTECTION && value;\r\n if (typeof resendInterval === \"number\" && resendInterval >= 0) {\r\n this._resendInterval = Math.floor(resendInterval);\r\n }\r\n if (typeof maxBytesOnDisk === \"number\" && maxBytesOnDisk >= 0) {\r\n this._maxBytesOnDisk = Math.floor(maxBytesOnDisk);\r\n }\r\n\r\n if (value && !FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\r\n this._enableDiskRetryMode = false;\r\n this._logWarn(\"Ignoring request to enable disk retry mode. Sufficient file protection capabilities were not detected.\")\r\n }\r\n if (this._enableDiskRetryMode) {\r\n if (this._statsbeat) {\r\n this._statsbeat.addFeature(Constants.StatsbeatFeature.DISK_RETRY);\r\n }\r\n // Starts file cleanup task\r\n if (!this._fileCleanupTimer) {\r\n this._fileCleanupTimer = setTimeout(() => { this._fileCleanupTask(); }, Sender.CLEANUP_TIMEOUT);\r\n this._fileCleanupTimer.unref();\r\n }\r\n }\r\n else {\r\n if (this._statsbeat) {\r\n this._statsbeat.removeFeature(Constants.StatsbeatFeature.DISK_RETRY);\r\n }\r\n if (this._fileCleanupTimer) {\r\n clearTimeout(this._fileCleanupTimer);\r\n }\r\n }\r\n }\r\n\r\n public async send(envelopes: Contracts.EnvelopeTelemetry[], callback?: (v: string) => void) {\r\n if (envelopes) {\r\n var endpointUrl = this._redirectedHost || this._config.endpointUrl;\r\n\r\n var endpointHost = new URL(endpointUrl).hostname;\r\n\r\n // todo: investigate specifying an agent here: https://nodejs.org/api/http.html#http_class_http_agent\r\n var options = {\r\n method: \"POST\",\r\n withCredentials: false,\r\n headers: <{ [key: string]: string }>{\r\n \"Content-Type\": \"application/x-json-stream\"\r\n }\r\n };\r\n\r\n let authHandler = this._getAuthorizationHandler ? this._getAuthorizationHandler(this._config) : null;\r\n if (authHandler) {\r\n if (this._statsbeat) {\r\n this._statsbeat.addFeature(Constants.StatsbeatFeature.AAD_HANDLING);\r\n }\r\n try {\r\n // Add bearer token\r\n await authHandler.addAuthorizationHeader(options);\r\n }\r\n catch (authError) {\r\n let errorMsg = \"Failed to get AAD bearer token for the Application.\";\r\n if (this._enableDiskRetryMode) {\r\n errorMsg += \"This batch of telemetry items will be retried. \";\r\n this._storeToDisk(envelopes);\r\n }\r\n errorMsg += \"Error:\" + authError.toString();\r\n this._logWarn(errorMsg);\r\n\r\n if (typeof callback === \"function\") {\r\n callback(errorMsg);\r\n }\r\n return; // If AAD auth fails do not send to Breeze\r\n }\r\n }\r\n\r\n let batch: string = \"\";\r\n envelopes.forEach(envelope => {\r\n var payload: string = Util.stringify(envelope);\r\n if (typeof payload !== \"string\") {\r\n return;\r\n }\r\n batch += payload + \"\\n\";\r\n });\r\n // Remove last \\n\r\n if (batch.length > 0) {\r\n batch = batch.substring(0, batch.length - 1);\r\n }\r\n\r\n let payload: Buffer = Buffer.from ? Buffer.from(batch) : new Buffer(batch);\r\n\r\n zlib.gzip(payload, (err, buffer) => {\r\n var dataToSend = buffer;\r\n if (err) {\r\n this._logWarn(Util.dumpObj(err));\r\n dataToSend = payload; // something went wrong so send without gzip\r\n options.headers[\"Content-Length\"] = payload.length.toString();\r\n } else {\r\n options.headers[\"Content-Encoding\"] = \"gzip\";\r\n options.headers[\"Content-Length\"] = buffer.length.toString();\r\n }\r\n\r\n this._logInfo(Util.dumpObj(options));\r\n\r\n // Ensure this request is not captured by auto-collection.\r\n (options)[AutoCollectHttpDependencies.disableCollectionRequestOption] = true;\r\n\r\n let startTime = +new Date();\r\n\r\n var requestCallback = (res: http.ClientResponse) => {\r\n res.setEncoding(\"utf-8\");\r\n\r\n //returns empty if the data is accepted\r\n var responseString = \"\";\r\n res.on(\"data\", (data: string) => {\r\n responseString += data;\r\n });\r\n\r\n res.on(\"end\", () => {\r\n let endTime = +new Date();\r\n let duration = endTime - startTime;\r\n this._numConsecutiveFailures = 0;\r\n // Handling of Statsbeat instance sending data, should turn it off if is not able to reach ingestion endpoint\r\n if (this._isStatsbeatSender && !this._statsbeatHasReachedIngestionAtLeastOnce) {\r\n if (RESPONSE_CODES_INDICATING_REACHED_BREEZE.includes(res.statusCode)) {\r\n this._statsbeatHasReachedIngestionAtLeastOnce = true;\r\n }\r\n else {\r\n this._statsbeatFailedToIngest();\r\n }\r\n }\r\n if (this._statsbeat) {\r\n if (res.statusCode == throttleStatusCode || res.statusCode == legacyThrottleStatusCode) { // Throttle\r\n this._statsbeat.countThrottle(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, res.statusCode);\r\n }\r\n else {\r\n this._statsbeat.countRequest(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, duration, res.statusCode === 200, res.statusCode);\r\n }\r\n }\r\n if (this._enableDiskRetryMode) {\r\n // try to send any cached events if the user is back online\r\n if (res.statusCode === 200) {\r\n if (!this._resendTimer) {\r\n this._resendTimer = setTimeout(() => {\r\n this._resendTimer = null;\r\n this._sendFirstFileOnDisk()\r\n }, this._resendInterval);\r\n this._resendTimer.unref();\r\n }\r\n } else if (this._isRetriable(res.statusCode)) {\r\n try {\r\n if (this._statsbeat) {\r\n this._statsbeat.countRetry(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, res.statusCode);\r\n }\r\n const breezeResponse = JSON.parse(responseString) as Contracts.BreezeResponse;\r\n let filteredEnvelopes: Contracts.EnvelopeTelemetry[] = [];\r\n if (breezeResponse.errors) {\r\n breezeResponse.errors.forEach(error => {\r\n // Only retry errors if 429, 500 or 503 response codes\r\n if (error.statusCode == 429 || error.statusCode == 500 || error.statusCode == 503) {\r\n filteredEnvelopes.push(envelopes[error.index]);\r\n }\r\n });\r\n if (filteredEnvelopes.length > 0) {\r\n this._storeToDisk(filteredEnvelopes);\r\n }\r\n }\r\n\r\n }\r\n catch (ex) {\r\n this._storeToDisk(envelopes); // Retriable status code with not valid Breeze response\r\n }\r\n }\r\n }\r\n // Redirect handling\r\n if (res.statusCode === 307 || // Temporary Redirect\r\n res.statusCode === 308) { // Permanent Redirect\r\n this._numConsecutiveRedirects++;\r\n // To prevent circular redirects\r\n if (this._numConsecutiveRedirects < 10) {\r\n // Try to get redirect header\r\n const locationHeader = res.headers[\"location\"] ? res.headers[\"location\"].toString() : null;\r\n if (locationHeader) {\r\n this._redirectedHost = locationHeader;\r\n // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically\r\n this.send(envelopes, callback);\r\n }\r\n }\r\n else {\r\n const circularRedirectError: Error = { name: \"Circular Redirect\", message: \"Error sending telemetry because of circular redirects.\" }\r\n if (this._statsbeat) {\r\n this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, circularRedirectError);\r\n }\r\n if (typeof callback === \"function\") {\r\n callback(\"Error sending telemetry because of circular redirects.\");\r\n }\r\n }\r\n\r\n }\r\n else {\r\n this._numConsecutiveRedirects = 0;\r\n if (typeof callback === \"function\") {\r\n callback(responseString);\r\n }\r\n this._logInfo(responseString);\r\n if (typeof this._onSuccess === \"function\") {\r\n this._onSuccess(responseString);\r\n }\r\n }\r\n });\r\n };\r\n\r\n var req = Util.makeRequest(this._config, endpointUrl, options, requestCallback);\r\n\r\n // Needed as of Node.js v13 default timeouts on HTTP requests are no longer default\r\n // Timeout should trigger the request on error function to run\r\n req.setTimeout(Sender.HTTP_TIMEOUT, () => {\r\n this._requestTimedOut = true;\r\n req.abort();\r\n });\r\n\r\n req.on(\"error\", (error: Error) => {\r\n if (this._isStatsbeatSender && !this._statsbeatHasReachedIngestionAtLeastOnce) {\r\n this._statsbeatFailedToIngest();\r\n }\r\n // todo: handle error codes better (group to recoverable/non-recoverable and persist)\r\n this._numConsecutiveFailures++;\r\n if (this._statsbeat) {\r\n this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, error);\r\n }\r\n\r\n // Only use warn level if retries are disabled or we've had some number of consecutive failures sending data\r\n // This is because warn level is printed in the console by default, and we don't want to be noisy for transient and self-recovering errors\r\n // Continue informing on each failure if verbose logging is being used\r\n if (!this._enableDiskRetryMode || this._numConsecutiveFailures > 0 && this._numConsecutiveFailures % Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN === 0) {\r\n let notice = \"Ingestion endpoint could not be reached. This batch of telemetry items has been lost. Use Disk Retry Caching to enable resending of failed telemetry. Error:\";\r\n if (this._enableDiskRetryMode) {\r\n notice = `Ingestion endpoint could not be reached ${this._numConsecutiveFailures} consecutive times. There may be resulting telemetry loss. Most recent error:`;\r\n }\r\n this._logWarn(notice, Util.dumpObj(error));\r\n } else {\r\n let notice = \"Transient failure to reach ingestion endpoint. This batch of telemetry items will be retried. Error:\";\r\n this._logInfo(notice, Util.dumpObj(error));\r\n }\r\n this._onErrorHelper(error);\r\n\r\n if (typeof callback === \"function\") {\r\n if (error) {\r\n // If the error type is a timeout we want to provide more meaningful output\r\n if (this._requestTimedOut) {\r\n error.name = \"telemetry timeout\";\r\n error.message = \"telemetry request timed out\";\r\n }\r\n callback(Util.dumpObj(error));\r\n }\r\n else {\r\n callback(\"Error sending telemetry\");\r\n }\r\n }\r\n\r\n if (this._enableDiskRetryMode) {\r\n this._storeToDisk(envelopes);\r\n }\r\n });\r\n\r\n req.write(dataToSend);\r\n req.end();\r\n });\r\n }\r\n }\r\n\r\n public saveOnCrash(envelopes: Contracts.EnvelopeTelemetry[]) {\r\n if (this._enableDiskRetryMode) {\r\n this._storeToDiskSync(Util.stringify(envelopes));\r\n }\r\n }\r\n\r\n private _isRetriable(statusCode: number) {\r\n return (\r\n statusCode === 206 || // Partial Accept\r\n statusCode === 401 || // Unauthorized\r\n statusCode === 403 || // Forbidden\r\n statusCode === 408 || // Timeout\r\n statusCode === 429 || // Too many requests\r\n statusCode === 500 || // Server Error\r\n statusCode === 502 || // Bad Gateway\r\n statusCode === 503 || // Server Unavailable\r\n statusCode === 504 // Gateway Timeout\r\n );\r\n }\r\n\r\n private _logInfo(message?: any, ...optionalParams: any[]) {\r\n if (!this._isStatsbeatSender) {\r\n Logging.info(Sender.TAG, message, optionalParams);\r\n }\r\n }\r\n\r\n private _logWarn(message?: any, ...optionalParams: any[]) {\r\n if (!this._isStatsbeatSender) {\r\n Logging.warn(Sender.TAG, message, optionalParams);\r\n }\r\n }\r\n\r\n private _statsbeatFailedToIngest() {\r\n if (this._shutdownStatsbeat) { // Check if callback is available\r\n this._failedToIngestCounter++;\r\n if (this._failedToIngestCounter >= 3) {\r\n this._shutdownStatsbeat();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Stores the payload as a json file on disk in the temp directory\r\n */\r\n private async _storeToDisk(envelopes: Contracts.EnvelopeTelemetry[]): Promise {\r\n try {\r\n this._logInfo(\"Checking existence of data storage directory: \" + this._tempDir);\r\n await FileSystemHelper.confirmDirExists(this._tempDir);\r\n }\r\n catch (ex) {\r\n this._logWarn(\"Failed to create folder to put telemetry: \" + Util.dumpObj(ex));\r\n this._onErrorHelper(ex);\r\n return;\r\n }\r\n try {\r\n await FileAccessControl.applyACLRules(this._tempDir);\r\n }\r\n catch (ex) {\r\n this._logWarn(\"Failed to apply file access control to folder: \" + Util.dumpObj(ex));\r\n this._onErrorHelper(ex);\r\n return;\r\n }\r\n try {\r\n let size = await FileSystemHelper.getShallowDirectorySize(this._tempDir);\r\n if (size > this._maxBytesOnDisk) {\r\n this._logWarn(\"Not saving data due to max size limit being met. Directory size in bytes is: \" + size);\r\n return;\r\n }\r\n }\r\n catch (ex) {\r\n this._logWarn(\"Failed to read directory for retriable telemetry: \" + Util.dumpObj(ex));\r\n this._onErrorHelper(ex);\r\n return;\r\n }\r\n try {\r\n //create file - file name for now is the timestamp, a better approach would be a UUID but that\r\n //would require an external dependency\r\n var fileName = new Date().getTime() + \".ai.json\";\r\n var fileFullPath = path.join(this._tempDir, fileName);\r\n\r\n // Mode 600 is w/r for creator and no read access for others (only applies on *nix)\r\n // For Windows, ACL rules are applied to the entire directory (see logic in _confirmDirExists and _applyACLRules)\r\n this._logInfo(\"saving data to disk at: \" + fileFullPath);\r\n await FileSystemHelper.writeFileAsync(fileFullPath, Util.stringify(envelopes), { mode: 0o600 });\r\n }\r\n catch (ex) {\r\n this._logWarn(\"Failed to persist telemetry to disk: \" + Util.dumpObj(ex));\r\n this._onErrorHelper(ex);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Stores the payload as a json file on disk using sync file operations\r\n * this is used when storing data before crashes\r\n */\r\n private _storeToDiskSync(payload: any) {\r\n try {\r\n this._logInfo(\"Checking existence of data storage directory: \" + this._tempDir);\r\n if (!fs.existsSync(this._tempDir)) {\r\n fs.mkdirSync(this._tempDir);\r\n }\r\n\r\n // Make sure permissions are valid\r\n FileAccessControl.applyACLRulesSync(this._tempDir);\r\n\r\n let dirSize = FileSystemHelper.getShallowDirectorySizeSync(this._tempDir);\r\n if (dirSize > this._maxBytesOnDisk) {\r\n this._logInfo(\"Not saving data due to max size limit being met. Directory size in bytes is: \" + dirSize);\r\n return;\r\n }\r\n\r\n //create file - file name for now is the timestamp, a better approach would be a UUID but that\r\n //would require an external dependency\r\n var fileName = new Date().getTime() + \".ai.json\";\r\n var fileFullPath = path.join(this._tempDir, fileName);\r\n\r\n // Mode 600 is w/r for creator and no access for anyone else (only applies on *nix)\r\n this._logInfo(\"saving data before crash to disk at: \" + fileFullPath);\r\n fs.writeFileSync(fileFullPath, payload, { mode: 0o600 });\r\n\r\n } catch (error) {\r\n this._logWarn(\"Error while saving data to disk: \" + Util.dumpObj(error));\r\n this._onErrorHelper(error);\r\n }\r\n }\r\n\r\n /**\r\n * Check for temp telemetry files\r\n * reads the first file if exist, deletes it and tries to send its load\r\n */\r\n private async _sendFirstFileOnDisk(): Promise {\r\n try {\r\n let files = await FileSystemHelper.readdirAsync(this._tempDir);\r\n files = files.filter(f => path.basename(f).indexOf(\".ai.json\") > -1);\r\n if (files.length > 0) {\r\n var firstFile = files[0];\r\n var filePath = path.join(this._tempDir, firstFile);\r\n let buffer = await FileSystemHelper.readFileAsync(filePath);\r\n // delete the file first to prevent double sending\r\n await FileSystemHelper.unlinkAsync(filePath);\r\n let envelopes: Contracts.EnvelopeTelemetry[] = JSON.parse(buffer.toString());\r\n await this.send(envelopes);\r\n }\r\n }\r\n catch (err) {\r\n this._onErrorHelper(err);\r\n }\r\n }\r\n\r\n private _onErrorHelper(error: Error): void {\r\n if (typeof this._onError === \"function\") {\r\n this._onError(error);\r\n }\r\n }\r\n\r\n private async _fileCleanupTask(): Promise {\r\n try {\r\n let files = await FileSystemHelper.readdirAsync(this._tempDir);\r\n files = files.filter(f => path.basename(f).indexOf(\".ai.json\") > -1);\r\n if (files.length > 0) {\r\n for (let i = 0; i < files.length; i++) {\r\n // Check expiration\r\n let fileCreationDate: Date = new Date(parseInt(files[i].split(\".ai.json\")[0]));\r\n let expired = new Date(+(new Date()) - Sender.FILE_RETEMPTION_PERIOD) > fileCreationDate;\r\n if (expired) {\r\n var filePath = path.join(this._tempDir, files[i]);\r\n await FileSystemHelper.unlinkAsync(filePath).catch((err) => {\r\n this._onErrorHelper(err);\r\n });\r\n }\r\n }\r\n }\r\n }\r\n catch (err) {\r\n if (err.code != \"ENOENT\") {\r\n this._onErrorHelper(err);\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport = Sender;"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.d.ts b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.d.ts new file mode 100644 index 0000000..c923f3c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.d.ts @@ -0,0 +1,24 @@ +/// +import zlib = require("zlib"); +import http = require("http"); +export declare enum contentEncodingMethod { + GZIP = "gzip", + DEFLATE = "deflate", + BR = "br" +} +export declare const bufferEncodingTypes: string[]; +export declare const isBrotliSupperted: () => boolean; +export declare const gzipAsync: (arg1: zlib.InputType) => Promise; +export declare const gunzipAsync: (arg1: zlib.InputType) => Promise; +export declare const deflateAsync: (arg1: zlib.InputType) => Promise; +export declare const inflateAsync: (arg1: zlib.InputType) => Promise; +export declare const getBrotliCompressAsync: (zlibObject: any) => Function; +export declare const getBrotliCompressSync: (zlibObject: any) => Function; +export declare const getBrotliDecompressAsync: (zlibObject: any) => Function; +export declare const getBrotliDecompressSync: (zlibObject: any) => Function; +export declare const isBufferType: (buffer: Buffer, type?: string) => boolean; +export declare const findBufferEncodingType: (buffer: Buffer) => string; +export declare const isSupportedContentEncoding: (encodingMethod: string) => contentEncodingMethod; +export declare const getContentEncodingFromHeaders: (response: http.ServerResponse) => contentEncodingMethod[]; +export declare const insertSnippetByIndex: (index: number, html: string, snippet: string) => string; +export declare const isContentTypeHeaderHtml: (response: http.ServerResponse) => boolean; diff --git a/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js new file mode 100644 index 0000000..a3bb65a --- /dev/null +++ b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js @@ -0,0 +1,136 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isContentTypeHeaderHtml = exports.insertSnippetByIndex = exports.getContentEncodingFromHeaders = exports.isSupportedContentEncoding = exports.findBufferEncodingType = exports.isBufferType = exports.getBrotliDecompressSync = exports.getBrotliDecompressAsync = exports.getBrotliCompressSync = exports.getBrotliCompressAsync = exports.inflateAsync = exports.deflateAsync = exports.gunzipAsync = exports.gzipAsync = exports.isBrotliSupperted = exports.bufferEncodingTypes = exports.contentEncodingMethod = void 0; +var zlib = require("zlib"); +var util_1 = require("util"); +// currently support the following encoding types +var contentEncodingMethod; +(function (contentEncodingMethod) { + contentEncodingMethod["GZIP"] = "gzip"; + contentEncodingMethod["DEFLATE"] = "deflate"; + contentEncodingMethod["BR"] = "br"; +})(contentEncodingMethod = exports.contentEncodingMethod || (exports.contentEncodingMethod = {})); +//current supported encoding types +exports.bufferEncodingTypes = ["utf8", "utf16le", "latin1", "base64", "hex", "ascii", "binary", "ucs2"]; +//for node version under 10, Brotli compression is not supported. +var isBrotliSupperted = function () { + var majVer = process.versions.node.split(".")[0]; + return parseInt(majVer) >= 10; +}; +exports.isBrotliSupperted = isBrotliSupperted; +exports.gzipAsync = util_1.promisify(zlib.gzip); +exports.gunzipAsync = util_1.promisify(zlib.gunzip); +exports.deflateAsync = util_1.promisify(zlib.deflate); +exports.inflateAsync = util_1.promisify(zlib.inflate); +var getBrotliCompressAsync = function (zlibObject) { + var isMajorVer = exports.isBrotliSupperted(); + if (isMajorVer && typeof zlibObject.brotliCompress === "function") { + return util_1.promisify(zlibObject.brotliCompress); + } + return null; +}; +exports.getBrotliCompressAsync = getBrotliCompressAsync; +var getBrotliCompressSync = function (zlibObject) { + var isMajorVer = exports.isBrotliSupperted(); + if (isMajorVer && typeof zlibObject.brotliCompressSync === "function") { + return zlibObject.brotliCompressSync; + } + return null; +}; +exports.getBrotliCompressSync = getBrotliCompressSync; +var getBrotliDecompressAsync = function (zlibObject) { + var isMajorVer = exports.isBrotliSupperted(); + if (isMajorVer && typeof zlibObject.brotliDecompress === "function") { + return util_1.promisify(zlibObject.brotliDecompress); + } + return null; +}; +exports.getBrotliDecompressAsync = getBrotliDecompressAsync; +var getBrotliDecompressSync = function (zlibObject) { + var isMajorVer = exports.isBrotliSupperted(); + if (isMajorVer && typeof zlibObject.brotliDecompressSync === "function") { + return zlibObject.brotliDecompressSync; + } + return null; +}; +exports.getBrotliDecompressSync = getBrotliDecompressSync; +var isBufferType = function (buffer, type) { + var encodingType = type ? type : "utf8"; + var result = false; + if (Buffer.isEncoding(encodingType)) { + var newBuffer = Buffer.from(buffer.toString(encodingType), encodingType); + result = newBuffer.toJSON().data.toString() === buffer.toJSON().data.toString(); + } + return result; +}; +exports.isBufferType = isBufferType; +var findBufferEncodingType = function (buffer) { + var bufferType = null; + for (var key in exports.bufferEncodingTypes) { + var type = exports.bufferEncodingTypes[key]; + if (Buffer.isEncoding(type) && exports.isBufferType(buffer, type)) { + bufferType = type; + break; + } + } + return bufferType; +}; +exports.findBufferEncodingType = findBufferEncodingType; +var isSupportedContentEncoding = function (encodingMethod) { + var encodingType = null; + switch (encodingMethod) { + case "gzip": + encodingType = contentEncodingMethod.GZIP; + break; + case "br": + encodingType = contentEncodingMethod.BR; + break; + case "deflate": + encodingType = contentEncodingMethod.DEFLATE; + break; + default: + } + return encodingType; +}; +exports.isSupportedContentEncoding = isSupportedContentEncoding; +// mutiple content-encoding is not supported +// for mutiple content-encoding, this method will return any empty array +var getContentEncodingFromHeaders = function (response) { + var headers = []; + var contentEncodingHeaders = response.getHeader("Content-Encoding"); + if (!contentEncodingHeaders) + return null; + if (typeof contentEncodingHeaders === "string") { + var supportedContentEncoding = exports.isSupportedContentEncoding(contentEncodingHeaders); + if (supportedContentEncoding) { + headers.push(supportedContentEncoding); + } + } + return headers; +}; +exports.getContentEncodingFromHeaders = getContentEncodingFromHeaders; +var insertSnippetByIndex = function (index, html, snippet) { + if (index < 0) + return null; + var newHtml = null; + var subStart = html.substring(0, index); + var subEnd = html.substring(index); + newHtml = subStart + "" + subEnd; + return newHtml; +}; +exports.insertSnippetByIndex = insertSnippetByIndex; +var isContentTypeHeaderHtml = function (response) { + var isHtml = false; + var contentType = response.getHeader("Content-Type"); + if (contentType) { + if (typeof contentType === "string") { + isHtml = contentType.indexOf("html") >= 0; + } + else { + isHtml = contentType.toString().indexOf("html") >= 0; + } + } + return isHtml; +}; +exports.isContentTypeHeaderHtml = isContentTypeHeaderHtml; +//# sourceMappingURL=SnippetInjectionHelper.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js.map b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js.map new file mode 100644 index 0000000..db66782 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/SnippetInjectionHelper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SnippetInjectionHelper.js","sourceRoot":"","sources":["../../Library/SnippetInjectionHelper.ts"],"names":[],"mappings":";;;AAAA,2BAA8B;AAC9B,6BAAiC;AAGjC,i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C,CAAC;SAAE;KAC5E;IACD,OAAO,OAAO,CAAC;AACnB,CAAC,CAAA;AATY,QAAA,6BAA6B,iCASzC;AAEM,IAAM,oBAAoB,GAAG,UAAC,KAAa,EAAE,IAAY,EAAE,OAAe;IAC7E,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAC3B,IAAI,OAAO,GAAG,IAAI,CAAC;IACnB,IAAI,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IACxC,IAAI,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,GAAG,QAAQ,GAAG,mCAAmC,GAAG,OAAO,GAAG,WAAW,GAAG,MAAM,CAAC;IAC1F,OAAO,OAAO,CAAC;AACnB,CAAC,CAAA;AAPY,QAAA,oBAAoB,wBAOhC;AAEM,IAAM,uBAAuB,GAAG,UAAC,QAA6B;IACjE,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,WAAW,GAAG,QAAQ,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;IACrD,IAAI,WAAW,EAAE;QACb,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;YACjC,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SAC7C;aAAM;YACH,MAAM,GAAG,WAAW,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;SACxD;KACJ;IACD,OAAO,MAAM,CAAC;AAClB,CAAC,CAAA;AAXY,QAAA,uBAAuB,2BAWnC","sourcesContent":["import zlib = require(\"zlib\");\r\nimport { promisify } from \"util\";\r\nimport http = require(\"http\");\r\n\r\n// currently support the following encoding types\r\nexport enum contentEncodingMethod {\r\n GZIP = \"gzip\",\r\n DEFLATE = \"deflate\",\r\n BR = \"br\"\r\n}\r\n\r\n//current supported encoding types\r\nexport const bufferEncodingTypes = [\"utf8\",\"utf16le\",\"latin1\",\"base64\",\"hex\",\"ascii\",\"binary\",\"ucs2\"];\r\n\r\n//for node version under 10, Brotli compression is not supported.\r\nexport const isBrotliSupperted = (): boolean => {\r\n const majVer = process.versions.node.split(\".\")[0];\r\n return parseInt(majVer) >= 10;\r\n}\r\n\r\nexport const gzipAsync = promisify(zlib.gzip);\r\nexport const gunzipAsync = promisify(zlib.gunzip);\r\nexport const deflateAsync = promisify(zlib.deflate);\r\nexport const inflateAsync = promisify(zlib.inflate);\r\n\r\nexport const getBrotliCompressAsync = (zlibObject: any): Function => {\r\n let isMajorVer = isBrotliSupperted();\r\n if (isMajorVer && typeof zlibObject.brotliCompress === \"function\") {\r\n return promisify(zlibObject.brotliCompress);\r\n }\r\n return null;\r\n}\r\n\r\nexport const getBrotliCompressSync = (zlibObject: any): Function => {\r\n let isMajorVer = isBrotliSupperted();\r\n if (isMajorVer && typeof zlibObject.brotliCompressSync === \"function\") {\r\n return zlibObject.brotliCompressSync;\r\n }\r\n return null;\r\n}\r\n\r\nexport const getBrotliDecompressAsync = (zlibObject: any): Function => {\r\n let isMajorVer = isBrotliSupperted();\r\n if (isMajorVer && typeof zlibObject.brotliDecompress === \"function\") {\r\n return promisify(zlibObject.brotliDecompress);\r\n }\r\n return null;\r\n}\r\n\r\nexport const getBrotliDecompressSync = (zlibObject: any): Function => {\r\n let isMajorVer = isBrotliSupperted();\r\n if (isMajorVer && typeof zlibObject.brotliDecompressSync === \"function\") {\r\n return zlibObject.brotliDecompressSync;\r\n }\r\n return null;\r\n}\r\n\r\nexport const isBufferType = (buffer: Buffer, type?:string): boolean => {\r\n let encodingType = type? type:\"utf8\";\r\n let result = false;\r\n if (Buffer.isEncoding(encodingType)) {\r\n let newBuffer = Buffer.from(buffer.toString(encodingType),encodingType);\r\n result = newBuffer.toJSON().data.toString() === buffer.toJSON().data.toString();\r\n }\r\n \r\n return result;\r\n}\r\n\r\nexport const findBufferEncodingType = (buffer: Buffer): string => {\r\n let bufferType = null;\r\n for (let key in bufferEncodingTypes) {\r\n let type = bufferEncodingTypes[key]\r\n if (Buffer.isEncoding(type) && isBufferType(buffer, type) ) {\r\n bufferType = type;\r\n break;\r\n }\r\n }\r\n return bufferType;\r\n}\r\n\r\nexport const isSupportedContentEncoding = (encodingMethod: string): contentEncodingMethod => {\r\n let encodingType = null;\r\n switch (encodingMethod) {\r\n case \"gzip\":\r\n encodingType = contentEncodingMethod.GZIP;\r\n break;\r\n case \"br\":\r\n encodingType = contentEncodingMethod.BR;\r\n break;\r\n case \"deflate\":\r\n encodingType = contentEncodingMethod.DEFLATE;\r\n break;\r\n default:\r\n }\r\n return encodingType;\r\n}\r\n\r\n// mutiple content-encoding is not supported\r\n// for mutiple content-encoding, this method will return any empty array\r\nexport const getContentEncodingFromHeaders = (response: http.ServerResponse): contentEncodingMethod[] => {\r\n let headers: contentEncodingMethod[] = [];\r\n let contentEncodingHeaders = response.getHeader(\"Content-Encoding\");\r\n if (!contentEncodingHeaders) return null;\r\n if (typeof contentEncodingHeaders === \"string\") {\r\n let supportedContentEncoding = isSupportedContentEncoding(contentEncodingHeaders);\r\n if (supportedContentEncoding) { headers.push(supportedContentEncoding); }\r\n }\r\n return headers;\r\n}\r\n\r\nexport const insertSnippetByIndex = (index: number, html: string, snippet: string): string => {\r\n if (index < 0) return null;\r\n let newHtml = null;\r\n let subStart = html.substring(0, index);\r\n let subEnd = html.substring(index);\r\n newHtml = subStart + \"\" + subEnd;\r\n return newHtml;\r\n}\r\n\r\nexport const isContentTypeHeaderHtml = (response: http.ServerResponse): boolean => {\r\n let isHtml = false;\r\n let contentType = response.getHeader(\"Content-Type\");\r\n if (contentType) {\r\n if (typeof contentType === \"string\") {\r\n isHtml = contentType.indexOf(\"html\") >= 0;\r\n } else {\r\n isHtml = contentType.toString().indexOf(\"html\") >= 0;\r\n }\r\n }\r\n return isHtml;\r\n}\r\n\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/TelemetryClient.d.ts b/node_modules/applicationinsights/out/Library/TelemetryClient.d.ts new file mode 100644 index 0000000..85bebe3 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/TelemetryClient.d.ts @@ -0,0 +1,111 @@ +import Config = require("./Config"); +import AuthorizationHandler = require("./AuthorizationHandler"); +import Context = require("./Context"); +import Contracts = require("../Declarations/Contracts"); +import Channel = require("./Channel"); +import Statsbeat = require("../AutoCollection/Statsbeat"); +import FlushOptions = require("./FlushOptions"); +import QuickPulseStateManager = require("./QuickPulseStateManager"); +/** + * Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and + * and manually trigger immediate sending (flushing) + */ +declare class TelemetryClient { + private static TAG; + private _telemetryProcessors; + private _enableAzureProperties; + private _statsbeat; + config: Config; + context: Context; + commonProperties: { + [key: string]: string; + }; + channel: Channel; + quickPulseClient: QuickPulseStateManager; + authorizationHandler: AuthorizationHandler; + /** + * Constructs a new client of the client + * @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified) + */ + constructor(setupString?: string); + /** + * Log information about availability of an application + * @param telemetry Object encapsulating tracking options + */ + trackAvailability(telemetry: Contracts.AvailabilityTelemetry): void; + /** + * Log a page view + * @param telemetry Object encapsulating tracking options + */ + trackPageView(telemetry: Contracts.PageViewTelemetry): void; + /** + * Log a trace message + * @param telemetry Object encapsulating tracking options + */ + trackTrace(telemetry: Contracts.TraceTelemetry): void; + /** + * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. + * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the + * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. + * @param telemetry Object encapsulating tracking options + */ + trackMetric(telemetry: Contracts.MetricTelemetry): void; + /** + * Log an exception + * @param telemetry Object encapsulating tracking options + */ + trackException(telemetry: Contracts.ExceptionTelemetry): void; + /** + * Log a user action or other occurrence. + * @param telemetry Object encapsulating tracking options + */ + trackEvent(telemetry: Contracts.EventTelemetry): void; + /** + * Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests + * that aren't automatically captured or if you've disabled automatic request collection. + * + * @param telemetry Object encapsulating tracking options + */ + trackRequest(telemetry: Contracts.RequestTelemetry & Contracts.Identified): void; + /** + * Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies + * that aren't automatically captured or if you've disabled automatic dependency collection. + * + * @param telemetry Object encapsulating tracking option + * */ + trackDependency(telemetry: Contracts.DependencyTelemetry & Contracts.Identified): void; + /** + * Immediately send all queued telemetry. + * @param options Flush options, including indicator whether app is crashing and callback + */ + flush(options?: FlushOptions): void; + /** + * Generic track method for all telemetry types + * @param data the telemetry to send + * @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes + */ + track(telemetry: Contracts.Telemetry, telemetryType: Contracts.TelemetryType): void; + /** + * Automatically populate telemetry properties like RoleName when running in Azure + * + * @param value if true properties will be populated + */ + setAutoPopulateAzureProperties(value: boolean): void; + /** + * Get Authorization handler + */ + getAuthorizationHandler(config: Config): AuthorizationHandler; + /** + * Adds telemetry processor to the collection. Telemetry processors will be called one by one + * before telemetry item is pushed for sending and in the order they were added. + * + * @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean + */ + addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.EnvelopeTelemetry, contextObjects?: { + [name: string]: any; + }) => boolean): void; + clearTelemetryProcessors(): void; + private runTelemetryProcessors; + getStatsbeat(): Statsbeat; +} +export = TelemetryClient; diff --git a/node_modules/applicationinsights/out/Library/TelemetryClient.js b/node_modules/applicationinsights/out/Library/TelemetryClient.js new file mode 100644 index 0000000..923bef1 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/TelemetryClient.js @@ -0,0 +1,237 @@ +"use strict"; +var url = require("url"); +var Config = require("./Config"); +var AuthorizationHandler = require("./AuthorizationHandler"); +var Context = require("./Context"); +var Contracts = require("../Declarations/Contracts"); +var Channel = require("./Channel"); +var TelemetryProcessors = require("../TelemetryProcessors"); +var CorrelationContextManager_1 = require("../AutoCollection/CorrelationContextManager"); +var Statsbeat = require("../AutoCollection/Statsbeat"); +var Sender = require("./Sender"); +var Util = require("./Util"); +var Logging = require("./Logging"); +var EnvelopeFactory = require("./EnvelopeFactory"); +/** + * Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and + * and manually trigger immediate sending (flushing) + */ +var TelemetryClient = /** @class */ (function () { + /** + * Constructs a new client of the client + * @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified) + */ + function TelemetryClient(setupString) { + this._telemetryProcessors = []; + this._enableAzureProperties = false; + var config = new Config(setupString); + this.config = config; + if (!this.config.instrumentationKey || this.config.instrumentationKey == "") { + throw new Error("Instrumentation key not found, please provide a connection string before starting Application Insights SDK."); + } + this.context = new Context(); + this.commonProperties = {}; + this.authorizationHandler = null; + if (!this.config.disableStatsbeat) { + this._statsbeat = new Statsbeat(this.config, this.context); + this._statsbeat.enable(true); + } + var sender = new Sender(this.config, this.getAuthorizationHandler, null, null, this._statsbeat); + this.channel = new Channel(function () { return config.disableAppInsights; }, function () { return config.maxBatchSize; }, function () { return config.maxBatchIntervalMs; }, sender); + } + /** + * Log information about availability of an application + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackAvailability = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.Availability); + }; + /** + * Log a page view + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackPageView = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.PageView); + }; + /** + * Log a trace message + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackTrace = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.Trace); + }; + /** + * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. + * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the + * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackMetric = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.Metric); + }; + /** + * Log an exception + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackException = function (telemetry) { + if (telemetry && telemetry.exception && !Util.isError(telemetry.exception)) { + telemetry.exception = new Error(telemetry.exception.toString()); + } + this.track(telemetry, Contracts.TelemetryType.Exception); + }; + /** + * Log a user action or other occurrence. + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackEvent = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.Event); + }; + /** + * Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests + * that aren't automatically captured or if you've disabled automatic request collection. + * + * @param telemetry Object encapsulating tracking options + */ + TelemetryClient.prototype.trackRequest = function (telemetry) { + this.track(telemetry, Contracts.TelemetryType.Request); + }; + /** + * Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies + * that aren't automatically captured or if you've disabled automatic dependency collection. + * + * @param telemetry Object encapsulating tracking option + * */ + TelemetryClient.prototype.trackDependency = function (telemetry) { + if (telemetry && !telemetry.target && telemetry.data) { + // url.parse().host returns null for non-urls, + // making this essentially a no-op in those cases + // If this logic is moved, update jsdoc in DependencyTelemetry.target + // url.parse() is deprecated, update to use WHATWG URL API instead + try { + telemetry.target = new url.URL(telemetry.data).host; + } + catch (error) { + // set target as null to be compliant with previous behavior + telemetry.target = null; + Logging.warn(TelemetryClient.TAG, "The URL object is failed to create.", error); + } + } + this.track(telemetry, Contracts.TelemetryType.Dependency); + }; + /** + * Immediately send all queued telemetry. + * @param options Flush options, including indicator whether app is crashing and callback + */ + TelemetryClient.prototype.flush = function (options) { + this.channel.triggerSend(options ? !!options.isAppCrashing : false, options ? options.callback : undefined); + }; + /** + * Generic track method for all telemetry types + * @param data the telemetry to send + * @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes + */ + TelemetryClient.prototype.track = function (telemetry, telemetryType) { + if (telemetry && Contracts.telemetryTypeToBaseType(telemetryType)) { + var envelope = EnvelopeFactory.createEnvelope(telemetry, telemetryType, this.commonProperties, this.context, this.config); + // Set time on the envelope if it was set on the telemetry item + if (telemetry.time) { + envelope.time = telemetry.time.toISOString(); + } + if (this._enableAzureProperties) { + TelemetryProcessors.azureRoleEnvironmentTelemetryProcessor(envelope, this.context); + } + var accepted = this.runTelemetryProcessors(envelope, telemetry.contextObjects); + // Ideally we would have a central place for "internal" telemetry processors and users can configure which ones are in use. + // This will do for now. Otherwise clearTelemetryProcessors() would be problematic. + accepted = accepted && TelemetryProcessors.samplingTelemetryProcessor(envelope, { correlationContext: CorrelationContextManager_1.CorrelationContextManager.getCurrentContext() }); + TelemetryProcessors.preAggregatedMetricsTelemetryProcessor(envelope, this.context); + if (accepted) { + TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient); + this.channel.send(envelope); + } + } + else { + Logging.warn(TelemetryClient.TAG, "track() requires telemetry object and telemetryType to be specified."); + } + }; + /** + * Automatically populate telemetry properties like RoleName when running in Azure + * + * @param value if true properties will be populated + */ + TelemetryClient.prototype.setAutoPopulateAzureProperties = function (value) { + this._enableAzureProperties = value; + }; + /** + * Get Authorization handler + */ + TelemetryClient.prototype.getAuthorizationHandler = function (config) { + if (config && config.aadTokenCredential) { + if (!this.authorizationHandler) { + Logging.info(TelemetryClient.TAG, "Adding authorization handler"); + this.authorizationHandler = new AuthorizationHandler(config.aadTokenCredential); + } + return this.authorizationHandler; + } + return null; + }; + /** + * Adds telemetry processor to the collection. Telemetry processors will be called one by one + * before telemetry item is pushed for sending and in the order they were added. + * + * @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean + */ + TelemetryClient.prototype.addTelemetryProcessor = function (telemetryProcessor) { + this._telemetryProcessors.push(telemetryProcessor); + }; + /* + * Removes all telemetry processors + */ + TelemetryClient.prototype.clearTelemetryProcessors = function () { + this._telemetryProcessors = []; + }; + TelemetryClient.prototype.runTelemetryProcessors = function (envelope, contextObjects) { + var accepted = true; + var telemetryProcessorsCount = this._telemetryProcessors.length; + if (telemetryProcessorsCount === 0) { + return accepted; + } + contextObjects = contextObjects || {}; + contextObjects["correlationContext"] = CorrelationContextManager_1.CorrelationContextManager.getCurrentContext(); + for (var i = 0; i < telemetryProcessorsCount; ++i) { + try { + var processor = this._telemetryProcessors[i]; + if (processor) { + if (processor.apply(null, [envelope, contextObjects]) === false) { + accepted = false; + break; + } + } + } + catch (error) { + accepted = true; + Logging.warn(TelemetryClient.TAG, "One of telemetry processors failed, telemetry item will be sent.", error, envelope); + } + } + // Sanitize tags and properties after running telemetry processors + if (accepted) { + if (envelope && envelope.tags) { + envelope.tags = Util.validateStringMap(envelope.tags); + } + if (envelope && envelope.data && envelope.data.baseData && envelope.data.baseData.properties) { + envelope.data.baseData.properties = Util.validateStringMap(envelope.data.baseData.properties); + } + } + return accepted; + }; + /* + * Get Statsbeat instance + */ + TelemetryClient.prototype.getStatsbeat = function () { + return this._statsbeat; + }; + TelemetryClient.TAG = "TelemetryClient"; + return TelemetryClient; +}()); +module.exports = TelemetryClient; +//# sourceMappingURL=TelemetryClient.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/TelemetryClient.js.map b/node_modules/applicationinsights/out/Library/TelemetryClient.js.map new file mode 100644 index 0000000..66281f1 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/TelemetryClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"TelemetryClient.js","sourceRoot":"","sources":["../../Library/TelemetryClient.ts"],"names":[],"mappings":";AAAA,yBAA4B;AAG5B,iCAAoC;AACpC,6DAAgE;AAChE,mCAAsC;AACtC,qDAAwD;AACxD,mCAAsC;AACtC,4DAA+D;AAC/D,yFAAwF;AACxF,uDAA0D;AAC1D,iCAAoC;AACpC,6BAAgC;AAChC,mCAAsC;AAEtC,mDAAsD;AAItD;;;GAGG;AACH;IAaI;;;OAGG;IACH,yBAAY,WAAoB;QAfxB,yBAAoB,GAAsG,EAAE,CAAC;QAC7H,2BAAsB,GAAY,KAAK,CAAC;QAe5C,IAAI,MAAM,GAAG,IAAI,MAAM,CAAC,WAAW,CAAC,CAAC;Q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AAU,GAAG,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;aACjG;SACJ;QAED,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,sCAAY,GAAnB;QACI,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;IAvPc,mBAAG,GAAG,iBAAiB,CAAC;IAwP3C,sBAAC;CAAA,AAzPD,IAyPC;AAED,iBAAS,eAAe,CAAC","sourcesContent":["import url = require(\"url\");\r\nimport os = require(\"os\");\r\n\r\nimport Config = require(\"./Config\");\r\nimport AuthorizationHandler = require(\"./AuthorizationHandler\");\r\nimport Context = require(\"./Context\");\r\nimport Contracts = require(\"../Declarations/Contracts\");\r\nimport Channel = require(\"./Channel\");\r\nimport TelemetryProcessors = require(\"../TelemetryProcessors\");\r\nimport { CorrelationContextManager } from \"../AutoCollection/CorrelationContextManager\";\r\nimport Statsbeat = require(\"../AutoCollection/Statsbeat\");\r\nimport Sender = require(\"./Sender\");\r\nimport Util = require(\"./Util\");\r\nimport Logging = require(\"./Logging\");\r\nimport FlushOptions = require(\"./FlushOptions\");\r\nimport EnvelopeFactory = require(\"./EnvelopeFactory\");\r\nimport QuickPulseStateManager = require(\"./QuickPulseStateManager\");\r\nimport { Tags } from \"../Declarations/Contracts\";\r\n\r\n/**\r\n * Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and\r\n * and manually trigger immediate sending (flushing)\r\n */\r\nclass TelemetryClient {\r\n private static TAG = \"TelemetryClient\";\r\n private _telemetryProcessors: { (envelope: Contracts.EnvelopeTelemetry, contextObjects: { [name: string]: any; }): boolean; }[] = [];\r\n private _enableAzureProperties: boolean = false;\r\n private _statsbeat: Statsbeat;\r\n\r\n public config: Config;\r\n public context: Context;\r\n public commonProperties: { [key: string]: string; };\r\n public channel: Channel;\r\n public quickPulseClient: QuickPulseStateManager;\r\n public authorizationHandler: AuthorizationHandler;\r\n\r\n /**\r\n * Constructs a new client of the client\r\n * @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified)\r\n */\r\n constructor(setupString?: string) {\r\n var config = new Config(setupString);\r\n this.config = config;\r\n if (!this.config.instrumentationKey || this.config.instrumentationKey == \"\") {\r\n throw new Error(\"Instrumentation key not found, please provide a connection string before starting Application Insights SDK.\");\r\n }\r\n this.context = new Context();\r\n this.commonProperties = {};\r\n this.authorizationHandler = null;\r\n if (!this.config.disableStatsbeat) {\r\n this._statsbeat = new Statsbeat(this.config, this.context);\r\n this._statsbeat.enable(true);\r\n }\r\n var sender = new Sender(this.config, this.getAuthorizationHandler, null, null, this._statsbeat);\r\n this.channel = new Channel(() => config.disableAppInsights, () => config.maxBatchSize, () => config.maxBatchIntervalMs, sender);\r\n }\r\n\r\n /**\r\n * Log information about availability of an application\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackAvailability(telemetry: Contracts.AvailabilityTelemetry): void {\r\n this.track(telemetry, Contracts.TelemetryType.Availability);\r\n }\r\n\r\n /**\r\n * Log a page view\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackPageView(telemetry: Contracts.PageViewTelemetry): void {\r\n this.track(telemetry, Contracts.TelemetryType.PageView);\r\n }\r\n\r\n /**\r\n * Log a trace message\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackTrace(telemetry: Contracts.TraceTelemetry): void {\r\n this.track(telemetry, Contracts.TelemetryType.Trace);\r\n }\r\n\r\n /**\r\n * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.\r\n * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the\r\n * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackMetric(telemetry: Contracts.MetricTelemetry): void {\r\n this.track(telemetry, Contracts.TelemetryType.Metric);\r\n }\r\n\r\n /**\r\n * Log an exception\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackException(telemetry: Contracts.ExceptionTelemetry): void {\r\n if (telemetry && telemetry.exception && !Util.isError(telemetry.exception)) {\r\n telemetry.exception = new Error(telemetry.exception.toString());\r\n }\r\n this.track(telemetry, Contracts.TelemetryType.Exception);\r\n }\r\n\r\n /**\r\n * Log a user action or other occurrence.\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackEvent(telemetry: Contracts.EventTelemetry): void {\r\n this.track(telemetry, Contracts.TelemetryType.Event);\r\n }\r\n\r\n /**\r\n * Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests\r\n * that aren't automatically captured or if you've disabled automatic request collection.\r\n *\r\n * @param telemetry Object encapsulating tracking options\r\n */\r\n public trackRequest(telemetry: Contracts.RequestTelemetry & Contracts.Identified): void {\r\n this.track(telemetry, Contracts.TelemetryType.Request);\r\n }\r\n\r\n /**\r\n * Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies\r\n * that aren't automatically captured or if you've disabled automatic dependency collection.\r\n *\r\n * @param telemetry Object encapsulating tracking option\r\n * */\r\n public trackDependency(telemetry: Contracts.DependencyTelemetry & Contracts.Identified) {\r\n\r\n if (telemetry && !telemetry.target && telemetry.data) {\r\n // url.parse().host returns null for non-urls,\r\n // making this essentially a no-op in those cases\r\n // If this logic is moved, update jsdoc in DependencyTelemetry.target\r\n // url.parse() is deprecated, update to use WHATWG URL API instead\r\n try {\r\n telemetry.target = new url.URL(telemetry.data).host;\r\n } catch (error) {\r\n // set target as null to be compliant with previous behavior\r\n telemetry.target = null;\r\n Logging.warn(TelemetryClient.TAG, \"The URL object is failed to create.\", error);\r\n }\r\n }\r\n this.track(telemetry, Contracts.TelemetryType.Dependency);\r\n }\r\n\r\n /**\r\n * Immediately send all queued telemetry.\r\n * @param options Flush options, including indicator whether app is crashing and callback\r\n */\r\n public flush(options?: FlushOptions) {\r\n this.channel.triggerSend(\r\n options ? !!options.isAppCrashing : false,\r\n options ? options.callback : undefined);\r\n }\r\n\r\n /**\r\n * Generic track method for all telemetry types\r\n * @param data the telemetry to send\r\n * @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes\r\n */\r\n public track(telemetry: Contracts.Telemetry, telemetryType: Contracts.TelemetryType) {\r\n if (telemetry && Contracts.telemetryTypeToBaseType(telemetryType)) {\r\n var envelope = EnvelopeFactory.createEnvelope(telemetry, telemetryType, this.commonProperties, this.context, this.config);\r\n\r\n // Set time on the envelope if it was set on the telemetry item\r\n if (telemetry.time) {\r\n envelope.time = telemetry.time.toISOString();\r\n }\r\n if (this._enableAzureProperties) {\r\n TelemetryProcessors.azureRoleEnvironmentTelemetryProcessor(envelope, this.context);\r\n }\r\n var accepted = this.runTelemetryProcessors(envelope, telemetry.contextObjects);\r\n\r\n // Ideally we would have a central place for \"internal\" telemetry processors and users can configure which ones are in use.\r\n // This will do for now. Otherwise clearTelemetryProcessors() would be problematic.\r\n accepted = accepted && TelemetryProcessors.samplingTelemetryProcessor(envelope, { correlationContext: CorrelationContextManager.getCurrentContext() });\r\n TelemetryProcessors.preAggregatedMetricsTelemetryProcessor(envelope, this.context);\r\n if (accepted) {\r\n TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient);\r\n this.channel.send(envelope);\r\n }\r\n }\r\n else {\r\n Logging.warn(TelemetryClient.TAG, \"track() requires telemetry object and telemetryType to be specified.\")\r\n }\r\n }\r\n\r\n /**\r\n * Automatically populate telemetry properties like RoleName when running in Azure\r\n *\r\n * @param value if true properties will be populated\r\n */\r\n public setAutoPopulateAzureProperties(value: boolean) {\r\n this._enableAzureProperties = value;\r\n }\r\n\r\n /**\r\n * Get Authorization handler\r\n */\r\n public getAuthorizationHandler(config: Config): AuthorizationHandler {\r\n if (config && config.aadTokenCredential) {\r\n if (!this.authorizationHandler) {\r\n Logging.info(TelemetryClient.TAG, \"Adding authorization handler\");\r\n this.authorizationHandler = new AuthorizationHandler(config.aadTokenCredential)\r\n }\r\n return this.authorizationHandler;\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Adds telemetry processor to the collection. Telemetry processors will be called one by one\r\n * before telemetry item is pushed for sending and in the order they were added.\r\n *\r\n * @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean\r\n */\r\n public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.EnvelopeTelemetry, contextObjects?: { [name: string]: any; }) => boolean) {\r\n this._telemetryProcessors.push(telemetryProcessor);\r\n }\r\n\r\n /*\r\n * Removes all telemetry processors\r\n */\r\n public clearTelemetryProcessors() {\r\n this._telemetryProcessors = [];\r\n }\r\n\r\n private runTelemetryProcessors(envelope: Contracts.EnvelopeTelemetry, contextObjects: { [name: string]: any; }): boolean {\r\n var accepted = true;\r\n var telemetryProcessorsCount = this._telemetryProcessors.length;\r\n\r\n if (telemetryProcessorsCount === 0) {\r\n return accepted;\r\n }\r\n\r\n contextObjects = contextObjects || {};\r\n contextObjects[\"correlationContext\"] = CorrelationContextManager.getCurrentContext();\r\n\r\n for (var i = 0; i < telemetryProcessorsCount; ++i) {\r\n try {\r\n var processor = this._telemetryProcessors[i];\r\n if (processor) {\r\n if (processor.apply(null, [envelope, contextObjects]) === false) {\r\n accepted = false;\r\n break;\r\n }\r\n }\r\n\r\n } catch (error) {\r\n accepted = true;\r\n Logging.warn(TelemetryClient.TAG, \"One of telemetry processors failed, telemetry item will be sent.\", error, envelope);\r\n }\r\n }\r\n\r\n // Sanitize tags and properties after running telemetry processors\r\n if (accepted) {\r\n if (envelope && envelope.tags) {\r\n envelope.tags = Util.validateStringMap(envelope.tags) as Tags & Tags[];\r\n }\r\n if (envelope && envelope.data && envelope.data.baseData && envelope.data.baseData.properties) {\r\n envelope.data.baseData.properties = Util.validateStringMap(envelope.data.baseData.properties);\r\n }\r\n }\r\n\r\n return accepted;\r\n }\r\n\r\n /*\r\n * Get Statsbeat instance\r\n */\r\n public getStatsbeat() {\r\n return this._statsbeat;\r\n }\r\n}\r\n\r\nexport = TelemetryClient;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Traceparent.d.ts b/node_modules/applicationinsights/out/Library/Traceparent.d.ts new file mode 100644 index 0000000..b3a9bb8 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Traceparent.d.ts @@ -0,0 +1,23 @@ +/** + * Helper class to manage parsing and validation of traceparent header. Also handles hierarchical + * back-compatibility headers generated from traceparent. W3C traceparent spec is documented at + * https://www.w3.org/TR/trace-context/#traceparent-field + */ +declare class Traceparent { + static DEFAULT_TRACE_FLAG: string; + static DEFAULT_VERSION: string; + legacyRootId: string; + parentId: string; + spanId: string; + traceFlag: string; + traceId: string; + version: string; + constructor(traceparent?: string, parentId?: string); + static isValidTraceId(id: string): boolean; + static isValidSpanId(id: string): boolean; + static formatOpenTelemetryTraceFlags(traceFlags: number): string; + getBackCompatRequestId(): string; + toString(): string; + updateSpanId(): void; +} +export = Traceparent; diff --git a/node_modules/applicationinsights/out/Library/Traceparent.js b/node_modules/applicationinsights/out/Library/Traceparent.js new file mode 100644 index 0000000..b767570 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Traceparent.js @@ -0,0 +1,112 @@ +"use strict"; +var Util = require("./Util"); +var CorrelationIdManager = require("./CorrelationIdManager"); +/** + * Helper class to manage parsing and validation of traceparent header. Also handles hierarchical + * back-compatibility headers generated from traceparent. W3C traceparent spec is documented at + * https://www.w3.org/TR/trace-context/#traceparent-field + */ +var Traceparent = /** @class */ (function () { + function Traceparent(traceparent, parentId) { + this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG; + this.version = Traceparent.DEFAULT_VERSION; + if (traceparent && typeof traceparent === "string") { // traceparent constructor + // If incoming request contains traceparent: parse it, set operation, parent and telemetry id accordingly. traceparent should be injected into outgoing requests. request-id should be injected in back-compat format |traceId.spanId. so that older SDKs could understand it. + if (traceparent.split(",").length > 1) { // If more than 1 traceparent is present, discard both + this.traceId = Util.w3cTraceId(); + this.spanId = Util.w3cTraceId().substr(0, 16); + } + else { + var traceparentArr = traceparent.trim().split("-"); + var len = traceparentArr.length; + if (len >= 4) { // traceparent must contain at least 4 fields + this.version = traceparentArr[0]; + this.traceId = traceparentArr[1]; + this.spanId = traceparentArr[2]; + this.traceFlag = traceparentArr[3]; + } + else { // Discard traceparent if a field is missing + this.traceId = Util.w3cTraceId(); + this.spanId = Util.w3cTraceId().substr(0, 16); + } + // Version validation + if (!this.version.match(/^[0-9a-f]{2}$/g)) { + this.version = Traceparent.DEFAULT_VERSION; + this.traceId = Util.w3cTraceId(); + } + if (this.version === "00" && len !== 4) { // 0x00 (and perhaps future versions) require exactly 4 fields. This strict check will need to be updated on each spec release + this.traceId = Util.w3cTraceId(); + this.spanId = Util.w3cTraceId().substr(0, 16); + } + if (this.version === "ff") { // 0xff is forbidden, generate new traceparent + this.version = Traceparent.DEFAULT_VERSION; + this.traceId = Util.w3cTraceId(); + this.spanId = Util.w3cTraceId().substr(0, 16); + } + if (!this.version.match(/^0[0-9a-f]$/g)) { + this.version = Traceparent.DEFAULT_VERSION; + } + // TraceFlag validation + if (!this.traceFlag.match(/^[0-9a-f]{2}$/g)) { + this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG; + this.traceId = Util.w3cTraceId(); + } + // Validate TraceId, regenerate new traceid if invalid + if (!Traceparent.isValidTraceId(this.traceId)) { + this.traceId = Util.w3cTraceId(); + } + // Validate Span Id, discard entire traceparent if invalid + if (!Traceparent.isValidSpanId(this.spanId)) { + this.spanId = Util.w3cTraceId().substr(0, 16); + this.traceId = Util.w3cTraceId(); + } + // Save backCompat parentId + this.parentId = this.getBackCompatRequestId(); + } + } + else if (parentId) { // backcompat constructor + // If incoming request contains only request-id, new traceid and spanid should be started, request-id value should be used as a parent. Root part of request-id should be stored in custom dimension on the request telemetry if root part is different from traceid. On the outgoing request side, request-id should be emitted in the |traceId.spanId. format. + this.parentId = parentId.slice(); // copy + var operationId = CorrelationIdManager.getRootId(parentId); + if (!Traceparent.isValidTraceId(operationId)) { + this.legacyRootId = operationId; + operationId = Util.w3cTraceId(); + } + if (parentId.indexOf("|") !== -1) { + parentId = parentId.substring(1 + parentId.substring(0, parentId.length - 1).lastIndexOf("."), parentId.length - 1); + } + this.traceId = operationId; + this.spanId = parentId; + } + else { + // Fallback default constructor + // if request does not contain any correlation headers, see case p2 + this.traceId = Util.w3cTraceId(); + this.spanId = Util.w3cTraceId().substr(0, 16); + } + } + Traceparent.isValidTraceId = function (id) { + return id.match(/^[0-9a-f]{32}$/) && id !== "00000000000000000000000000000000"; + }; + Traceparent.isValidSpanId = function (id) { + return id.match(/^[0-9a-f]{16}$/) && id !== "0000000000000000"; + }; + Traceparent.formatOpenTelemetryTraceFlags = function (traceFlags) { + var formattedFlags = ("0" + traceFlags.toString(16)); + return formattedFlags.substring(formattedFlags.length - 2); + }; + Traceparent.prototype.getBackCompatRequestId = function () { + return "|" + this.traceId + "." + this.spanId + "."; + }; + Traceparent.prototype.toString = function () { + return this.version + "-" + this.traceId + "-" + this.spanId + "-" + this.traceFlag; + }; + Traceparent.prototype.updateSpanId = function () { + this.spanId = Util.w3cTraceId().substr(0, 16); + }; + Traceparent.DEFAULT_TRACE_FLAG = "01"; + Traceparent.DEFAULT_VERSION = "00"; + return Traceparent; +}()); +module.exports = Traceparent; +//# sourceMappingURL=Traceparent.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Traceparent.js.map b/node_modules/applicationinsights/out/Library/Traceparent.js.map new file mode 100644 index 0000000..77e2ae0 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Traceparent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Traceparent.js","sourceRoot":"","sources":["../../Library/Traceparent.ts"],"names":[],"mappings":";AACA,6BAAgC;AAChC,6DAAgE;AAEhE;;;;GAIG;AACH;IAWI,qBAAY,WAAoB,EAAE,QAAiB;QAJ5C,cAAS,GAAW,WAAW,CAAC,kBAAkB,CAAC;QAEnD,YAAO,GAAW,WAAW,CAAC,eAAe,CAAC;QAGjD,IAAI,WAAW,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE,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OAAO,EAAE,CAAC,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,KAAK,kBAAkB,CAAC;IACnE,CAAC;IAEa,yCAA6B,GAA3C,UAA4C,UAAmB;QAC3D,IAAI,cAAc,GAAG,CAAC,GAAG,GAAG,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QACrD,OAAO,cAAc,CAAC,SAAS,CAAC,cAAc,CAAC,MAAM,GAAE,CAAC,CAAC,CAAC;IAC9D,CAAC;IAEM,4CAAsB,GAA7B;QACI,OAAO,MAAI,IAAI,CAAC,OAAO,SAAI,IAAI,CAAC,MAAM,MAAG,CAAC;IAC9C,CAAC;IAEM,8BAAQ,GAAf;QACI,OAAU,IAAI,CAAC,OAAO,SAAI,IAAI,CAAC,OAAO,SAAI,IAAI,CAAC,MAAM,SAAI,IAAI,CAAC,SAAW,CAAC;IAC9E,CAAC;IAEM,kCAAY,GAAnB;QACI,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAClD,CAAC;IAhHa,8BAAkB,GAAK,IAAI,CAAC;IAC5B,2BAAe,GAAG,IAAI,CAAC;IAgHzC,kBAAC;CAAA,AAlHD,IAkHC;AAED,iBAAS,WAAW,CAAC","sourcesContent":["import { TraceFlags } from \"@opentelemetry/api\";\r\nimport Util = require(\"./Util\");\r\nimport CorrelationIdManager = require(\"./CorrelationIdManager\");\r\n\r\n/**\r\n * Helper class to manage parsing and validation of traceparent header. Also handles hierarchical\r\n * back-compatibility headers generated from traceparent. W3C traceparent spec is documented at\r\n * https://www.w3.org/TR/trace-context/#traceparent-field\r\n */\r\nclass Traceparent {\r\n public static DEFAULT_TRACE_FLAG = \"01\";\r\n public static DEFAULT_VERSION = \"00\";\r\n\r\n public legacyRootId: string;\r\n public parentId: string;\r\n public spanId: string;\r\n public traceFlag: string = Traceparent.DEFAULT_TRACE_FLAG;\r\n public traceId: string;\r\n public version: string = Traceparent.DEFAULT_VERSION;\r\n\r\n constructor(traceparent?: string, parentId?: string) {\r\n if (traceparent && typeof traceparent === \"string\") { // traceparent constructor\r\n // If incoming request contains traceparent: parse it, set operation, parent and telemetry id accordingly. traceparent should be injected into outgoing requests. request-id should be injected in back-compat format |traceId.spanId. so that older SDKs could understand it.\r\n if (traceparent.split(\",\").length > 1) { // If more than 1 traceparent is present, discard both\r\n this.traceId = Util.w3cTraceId();\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n } else {\r\n const traceparentArr = traceparent.trim().split(\"-\");\r\n const len = traceparentArr.length;\r\n if (len >= 4) { // traceparent must contain at least 4 fields\r\n this.version = traceparentArr[0];\r\n this.traceId = traceparentArr[1];\r\n this.spanId = traceparentArr[2];\r\n this.traceFlag = traceparentArr[3];\r\n } else { // Discard traceparent if a field is missing\r\n this.traceId = Util.w3cTraceId();\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n }\r\n\r\n // Version validation\r\n if (!this.version.match(/^[0-9a-f]{2}$/g)) {\r\n this.version = Traceparent.DEFAULT_VERSION;\r\n this.traceId = Util.w3cTraceId();\r\n }\r\n if (this.version === \"00\" && len !== 4) { // 0x00 (and perhaps future versions) require exactly 4 fields. This strict check will need to be updated on each spec release\r\n this.traceId = Util.w3cTraceId();\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n }\r\n if (this.version === \"ff\") { // 0xff is forbidden, generate new traceparent\r\n this.version = Traceparent.DEFAULT_VERSION;\r\n this.traceId = Util.w3cTraceId();\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n }\r\n if (!this.version.match(/^0[0-9a-f]$/g)) {\r\n this.version = Traceparent.DEFAULT_VERSION;\r\n }\r\n\r\n // TraceFlag validation\r\n if (!this.traceFlag.match(/^[0-9a-f]{2}$/g)) {\r\n this.traceFlag = Traceparent.DEFAULT_TRACE_FLAG;\r\n this.traceId = Util.w3cTraceId();\r\n }\r\n\r\n // Validate TraceId, regenerate new traceid if invalid\r\n if (!Traceparent.isValidTraceId(this.traceId)) {\r\n this.traceId = Util.w3cTraceId();\r\n }\r\n\r\n // Validate Span Id, discard entire traceparent if invalid\r\n if (!Traceparent.isValidSpanId(this.spanId)) {\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n this.traceId = Util.w3cTraceId();\r\n }\r\n\r\n // Save backCompat parentId\r\n this.parentId = this.getBackCompatRequestId();\r\n }\r\n } else if (parentId) { // backcompat constructor\r\n // If incoming request contains only request-id, new traceid and spanid should be started, request-id value should be used as a parent. Root part of request-id should be stored in custom dimension on the request telemetry if root part is different from traceid. On the outgoing request side, request-id should be emitted in the |traceId.spanId. format.\r\n this.parentId = parentId.slice(); // copy\r\n let operationId = CorrelationIdManager.getRootId(parentId);\r\n if (!Traceparent.isValidTraceId(operationId)) {\r\n this.legacyRootId = operationId;\r\n operationId = Util.w3cTraceId();\r\n }\r\n if (parentId.indexOf(\"|\") !== -1) {\r\n parentId = parentId.substring(1 + parentId.substring(0, parentId.length - 1).lastIndexOf(\".\"), parentId.length - 1);\r\n }\r\n this.traceId = operationId;\r\n this.spanId = parentId;\r\n } else {\r\n // Fallback default constructor\r\n // if request does not contain any correlation headers, see case p2\r\n this.traceId = Util.w3cTraceId();\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n }\r\n\r\n }\r\n\r\n public static isValidTraceId(id: string): boolean {\r\n return id.match(/^[0-9a-f]{32}$/) && id !== \"00000000000000000000000000000000\";\r\n }\r\n\r\n public static isValidSpanId(id: string): boolean {\r\n return id.match(/^[0-9a-f]{16}$/) && id !== \"0000000000000000\";\r\n }\r\n\r\n public static formatOpenTelemetryTraceFlags(traceFlags : number){\r\n let formattedFlags = (\"0\" + traceFlags.toString(16));\r\n return formattedFlags.substring(formattedFlags.length -2);\r\n }\r\n\r\n public getBackCompatRequestId(): string {\r\n return `|${this.traceId}.${this.spanId}.`;\r\n }\r\n\r\n public toString(): string {\r\n return `${this.version}-${this.traceId}-${this.spanId}-${this.traceFlag}`;\r\n }\r\n\r\n public updateSpanId(): void {\r\n this.spanId = Util.w3cTraceId().substr(0, 16);\r\n }\r\n}\r\n\r\nexport = Traceparent;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Tracestate.d.ts b/node_modules/applicationinsights/out/Library/Tracestate.d.ts new file mode 100644 index 0000000..38113d5 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Tracestate.d.ts @@ -0,0 +1,14 @@ +/** + * Helper class to manage parsing and strict-validation of tracestate header. W3C tracestate spec + * is documented at https://www.w3.org/TR/trace-context/#header-value + * @class Tracestate + */ +declare class Tracestate { + static strict: boolean; + fieldmap: string[]; + constructor(id?: string); + toString(): string; + private static validateKeyChars; + private parseHeader; +} +export = Tracestate; diff --git a/node_modules/applicationinsights/out/Library/Tracestate.js b/node_modules/applicationinsights/out/Library/Tracestate.js new file mode 100644 index 0000000..2317542 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Tracestate.js @@ -0,0 +1,76 @@ +"use strict"; +/** + * Helper class to manage parsing and strict-validation of tracestate header. W3C tracestate spec + * is documented at https://www.w3.org/TR/trace-context/#header-value + * @class Tracestate + */ +var Tracestate = /** @class */ (function () { + // if true, performs strict tracestate header checking, else just passes it along + function Tracestate(id) { + this.fieldmap = []; + if (!id) { + return; + } + this.fieldmap = this.parseHeader(id); + } + Tracestate.prototype.toString = function () { + var fieldarr = this.fieldmap; + if (!fieldarr || fieldarr.length == 0) { + return null; + } + return fieldarr.join(", "); + }; + Tracestate.validateKeyChars = function (key) { + var keyParts = key.split("@"); + if (keyParts.length == 2) { + // Parse for tenant@vendor format + var tenant = keyParts[0].trim(); + var vendor = keyParts[1].trim(); + var tenantValid = Boolean(tenant.match(/^[\ ]?[a-z0-9\*\-\_/]{1,241}$/)); + var vendorValid = Boolean(vendor.match(/^[\ ]?[a-z0-9\*\-\_/]{1,14}$/)); + return tenantValid && vendorValid; + } + else if (keyParts.length == 1) { + // Parse for standard key format + return Boolean(key.match(/^[\ ]?[a-z0-9\*\-\_/]{1,256}$/)); + } + return false; + }; + Tracestate.prototype.parseHeader = function (id) { + var res = []; + var keydeduper = {}; + var parts = id.split(","); + if (parts.length > 32) + return null; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var rawPart = parts_1[_i]; + var part = rawPart.trim(); // trim out whitespace + if (part.length === 0) { + continue; // Discard empty pairs, but keep the rest of this tracestate + } + var pair = part.split("="); + // pair should contain exactly one "=" + if (pair.length !== 2) { + return null; // invalid pair: discard entire tracestate + } + // Validate length and charset of this key + if (!Tracestate.validateKeyChars(pair[0])) { + return null; + } + // Assert uniqueness of this key + if (keydeduper[pair[0]]) { + return null; // duplicate key: discard entire tracestate + } + else { + keydeduper[pair[0]] = true; + } + // All checks passed -- add this part + res.push(part); + } + return res; + }; + Tracestate.strict = true; + return Tracestate; +}()); +module.exports = Tracestate; +//# sourceMappingURL=Tracestate.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Tracestate.js.map b/node_modules/applicationinsights/out/Library/Tracestate.js.map new file mode 100644 index 0000000..0569b33 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Tracestate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Tracestate.js","sourceRoot":"","sources":["../../Library/Tracestate.ts"],"names":[],"mappings":";AAAA;;;;GAIG;AACH;IAKI,iFAAiF;IACjF,oBAAY,EAAW;QAHhB,aAAQ,GAAa,EAAE,CAAC;QAI3B,IAAI,CAAC,EAAE,EAAE;YACL,OAAO;SACV;QACD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACzC,CAAC;IAEM,6BAAQ,GAAf;QACI,IAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAE/B,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE;YACnC,OAAO,IAAI,CAAC;SACf;QAED,OAAO,QAAQ,CAAC,IAAI,CAA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AAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC7B,sCAAsC;YACtC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;gBACnB,OAAO,IAAI,CAAC,CAAC,0CAA0C;aAC1D;YAED,0CAA0C;YAC1C,IAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE;gBACvC,OAAO,IAAI,CAAC;aACf;YAED,gCAAgC;YAChC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE;gBACrB,OAAO,IAAI,CAAC,CAAC,2CAA2C;aAC3D;iBAAM;gBACH,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;aAC7B;YAED,qCAAqC;YACrC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SAClB;QAED,OAAO,GAAG,CAAC;IACf,CAAC;IAzEa,iBAAM,GAAG,IAAI,CAAC;IA0EhC,iBAAC;CAAA,AA3ED,IA2EC;AAED,iBAAS,UAAU,CAAC","sourcesContent":["/**\r\n * Helper class to manage parsing and strict-validation of tracestate header. W3C tracestate spec\r\n * is documented at https://www.w3.org/TR/trace-context/#header-value\r\n * @class Tracestate\r\n */\r\nclass Tracestate {\r\n public static strict = true;\r\n\r\n public fieldmap: string[] = [];\r\n\r\n // if true, performs strict tracestate header checking, else just passes it along\r\n constructor(id?: string) {\r\n if (!id) {\r\n return;\r\n }\r\n this.fieldmap = this.parseHeader(id);\r\n }\r\n\r\n public toString(): string {\r\n const fieldarr = this.fieldmap;\r\n\r\n if (!fieldarr || fieldarr.length == 0) {\r\n return null;\r\n }\r\n\r\n return fieldarr.join(\", \");\r\n }\r\n\r\n private static validateKeyChars(key: string): boolean {\r\n const keyParts = key.split(\"@\");\r\n if (keyParts.length == 2) {\r\n // Parse for tenant@vendor format\r\n const tenant = keyParts[0].trim();\r\n const vendor = keyParts[1].trim();\r\n const tenantValid = Boolean(tenant.match(/^[\\ ]?[a-z0-9\\*\\-\\_/]{1,241}$/));\r\n const vendorValid = Boolean(vendor.match(/^[\\ ]?[a-z0-9\\*\\-\\_/]{1,14}$/));\r\n return tenantValid && vendorValid;\r\n } else if (keyParts.length == 1) {\r\n // Parse for standard key format\r\n return Boolean(key.match(/^[\\ ]?[a-z0-9\\*\\-\\_/]{1,256}$/));\r\n }\r\n\r\n return false;\r\n }\r\n\r\n private parseHeader(id: string): string[] {\r\n const res: string[] = [];\r\n const keydeduper: {[key: string]: boolean} = {};\r\n const parts = id.split(\",\");\r\n if (parts.length > 32) return null;\r\n for (let rawPart of parts) {\r\n const part = rawPart.trim(); // trim out whitespace\r\n if (part.length === 0) {\r\n continue; // Discard empty pairs, but keep the rest of this tracestate\r\n }\r\n\r\n const pair = part.split(\"=\");\r\n // pair should contain exactly one \"=\"\r\n if (pair.length !== 2) {\r\n return null; // invalid pair: discard entire tracestate\r\n }\r\n\r\n // Validate length and charset of this key\r\n if (!Tracestate.validateKeyChars(pair[0])) {\r\n return null;\r\n }\r\n\r\n // Assert uniqueness of this key\r\n if (keydeduper[pair[0]]) {\r\n return null; // duplicate key: discard entire tracestate\r\n } else {\r\n keydeduper[pair[0]] = true\r\n }\r\n\r\n // All checks passed -- add this part\r\n res.push(part);\r\n }\r\n\r\n return res;\r\n }\r\n}\r\n\r\nexport = Tracestate;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Util.d.ts b/node_modules/applicationinsights/out/Library/Util.d.ts new file mode 100644 index 0000000..bfff922 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Util.d.ts @@ -0,0 +1,112 @@ +/// +import http = require("http"); +import https = require("https"); +import Config = require("./Config"); +import TelemetryClient = require("../Library/TelemetryClient"); +import { HttpRequest } from "../Library/Functions"; +declare class Util { + private static _useKeepAlive; + private static _listenerAttached; + static MAX_PROPERTY_LENGTH: number; + static keepAliveAgent: http.Agent; + static tlsRestrictedAgent: http.Agent; + static isNodeExit: boolean; + constructor(); + /** + * helper method to access userId and sessionId cookie + */ + static getCookie(name: string, cookie: string): string; + /** + * helper method to trim strings (IE8 does not implement String.prototype.trim) + */ + static trim(str: string): string; + /** + * Convert an array of int32 to Base64 (no '==' at the end). + * MSB first. + */ + static int32ArrayToBase64(array: number[]): string; + /** + * generate a random 32bit number (-0x80000000..0x7FFFFFFF). + */ + static random32(): number; + /** + * generate a random 32bit number (0x00000000..0xFFFFFFFF). + */ + static randomu32(): number; + /** + * generate W3C-compatible trace id + * https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md#trace-id + */ + static w3cTraceId(): string; + static w3cSpanId(): string; + static isValidW3CId(id: string): boolean; + /** + * Check if an object is of type Array + */ + static isArray(obj: any): boolean; + /** + * Check if an object is of type Error + */ + static isError(obj: any): boolean; + static isPrimitive(input: any): boolean; + /** + * Check if an object is of type Date + */ + static isDate(obj: any): boolean; + /** + * Convert ms to c# time span format + */ + static msToTimeSpan(totalms: number): string; + /** + * Using JSON.stringify, by default Errors do not serialize to something useful: + * Simplify a generic Node Error into a simpler map for customDimensions + * Custom errors can still implement toJSON to override this functionality + */ + protected static extractError(err: Error): { + message: string; + code: string; + }; + /** + * Manually call toJSON if available to pre-convert the value. + * If a primitive is returned, then the consumer of this function can skip JSON.stringify. + * This avoids double escaping of quotes for Date objects, for example. + */ + protected static extractObject(origProperty: any): any; + /** + * Validate that an object is of type { [key: string]: string } + */ + static validateStringMap(obj: any): { + [key: string]: string; + }; + /** + * Checks if a request url is not on a excluded domain list + * and if it is safe to add correlation headers + */ + static canIncludeCorrelationHeader(client: TelemetryClient, requestUrl: string): boolean; + static getCorrelationContextTarget(response: http.ClientResponse | http.ServerRequest | HttpRequest, key: string): any; + /** + * Generate request + * + * Proxify the request creation to handle proxy http + * + * @param {string} requestUrl url endpoint + * @param {Object} requestOptions Request option + * @param {Function} requestCallback callback on request + * @param {boolean} useProxy Use proxy URL from config + * @param {boolean} useAgent Set Http Agent in request + * @returns {http.ClientRequest} request object + */ + static makeRequest(config: Config, requestUrl: string, requestOptions: http.RequestOptions | https.RequestOptions, requestCallback: (res: http.IncomingMessage) => void, useProxy?: boolean, useAgent?: boolean): http.ClientRequest; + /** + * Parse standard request-context header + */ + static safeIncludeCorrelationHeader(client: TelemetryClient, request: http.ClientRequest | http.ServerResponse, correlationHeader: any): void; + /** + * Returns string representation of an object suitable for diagnostics logging. + */ + static dumpObj(object: any): string; + static stringify(payload: any): string; + private static addCorrelationIdHeaderFromString; + private static _addCloseHandler; +} +export = Util; diff --git a/node_modules/applicationinsights/out/Library/Util.js b/node_modules/applicationinsights/out/Library/Util.js new file mode 100644 index 0000000..70b6d3c --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Util.js @@ -0,0 +1,413 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var http = require("http"); +var https = require("https"); +var url = require("url"); +var constants = require("constants"); +var Logging = require("./Logging"); +var RequestResponseHeaders = require("./RequestResponseHeaders"); +var JsonConfig_1 = require("./JsonConfig"); +var Util = /** @class */ (function () { + function Util() { + Util._addCloseHandler(); + } + /** + * helper method to access userId and sessionId cookie + */ + Util.getCookie = function (name, cookie) { + var value = ""; + if (name && name.length && typeof cookie === "string") { + var cookieName = name + "="; + var cookies = cookie.split(";"); + for (var i = 0; i < cookies.length; i++) { + var cookie = cookies[i]; + cookie = Util.trim(cookie); + if (cookie && cookie.indexOf(cookieName) === 0) { + value = cookie.substring(cookieName.length, cookies[i].length); + break; + } + } + } + return value; + }; + /** + * helper method to trim strings (IE8 does not implement String.prototype.trim) + */ + Util.trim = function (str) { + if (typeof str === "string") { + return str.replace(/^\s+|\s+$/g, ""); + } + else { + return ""; + } + }; + /** + * Convert an array of int32 to Base64 (no '==' at the end). + * MSB first. + */ + Util.int32ArrayToBase64 = function (array) { + var toChar = function (v, i) { + return String.fromCharCode((v >> i) & 0xFF); + }; + var int32AsString = function (v) { + return toChar(v, 24) + toChar(v, 16) + toChar(v, 8) + toChar(v, 0); + }; + var x = array.map(int32AsString).join(""); + var b = Buffer.from ? Buffer.from(x, "binary") : new Buffer(x, "binary"); + var s = b.toString("base64"); + return s.substr(0, s.indexOf("=")); + }; + /** + * generate a random 32bit number (-0x80000000..0x7FFFFFFF). + */ + Util.random32 = function () { + return (0x100000000 * Math.random()) | 0; + }; + /** + * generate a random 32bit number (0x00000000..0xFFFFFFFF). + */ + Util.randomu32 = function () { + return Util.random32() + 0x80000000; + }; + /** + * generate W3C-compatible trace id + * https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md#trace-id + */ + Util.w3cTraceId = function () { + var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + // rfc4122 version 4 UUID without dashes and with lowercase letters + var oct = "", tmp; + for (var a = 0; a < 4; a++) { + tmp = Util.random32(); + oct += + hexValues[tmp & 0xF] + + hexValues[tmp >> 4 & 0xF] + + hexValues[tmp >> 8 & 0xF] + + hexValues[tmp >> 12 & 0xF] + + hexValues[tmp >> 16 & 0xF] + + hexValues[tmp >> 20 & 0xF] + + hexValues[tmp >> 24 & 0xF] + + hexValues[tmp >> 28 & 0xF]; + } + // "Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively" + var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0]; + return oct.substr(0, 8) + oct.substr(9, 4) + "4" + oct.substr(13, 3) + clockSequenceHi + oct.substr(16, 3) + oct.substr(19, 12); + }; + Util.w3cSpanId = function () { + return Util.w3cTraceId().substring(16); + }; + Util.isValidW3CId = function (id) { + return id.length === 32 && id !== "00000000000000000000000000000000"; + }; + /** + * Check if an object is of type Array + */ + Util.isArray = function (obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + /** + * Check if an object is of type Error + */ + Util.isError = function (obj) { + return Object.prototype.toString.call(obj) === "[object Error]"; + }; + Util.isPrimitive = function (input) { + var propType = typeof input; + return propType === "string" || propType === "number" || propType === "boolean"; + }; + /** + * Check if an object is of type Date + */ + Util.isDate = function (obj) { + return Object.prototype.toString.call(obj) === "[object Date]"; + }; + /** + * Convert ms to c# time span format + */ + Util.msToTimeSpan = function (totalms) { + if (isNaN(totalms) || totalms < 0) { + totalms = 0; + } + var sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, ""); + var min = "" + Math.floor(totalms / (1000 * 60)) % 60; + var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24; + var days = Math.floor(totalms / (1000 * 60 * 60 * 24)); + sec = sec.indexOf(".") < 2 ? "0" + sec : sec; + min = min.length < 2 ? "0" + min : min; + hour = hour.length < 2 ? "0" + hour : hour; + var daysText = days > 0 ? days + "." : ""; + return daysText + hour + ":" + min + ":" + sec; + }; + /** + * Using JSON.stringify, by default Errors do not serialize to something useful: + * Simplify a generic Node Error into a simpler map for customDimensions + * Custom errors can still implement toJSON to override this functionality + */ + Util.extractError = function (err) { + // Error is often subclassed so may have code OR id properties: + // https://nodejs.org/api/errors.html#errors_error_code + var looseError = err; + return { + message: err.message, + code: looseError.code || looseError.id || "" + }; + }; + /** + * Manually call toJSON if available to pre-convert the value. + * If a primitive is returned, then the consumer of this function can skip JSON.stringify. + * This avoids double escaping of quotes for Date objects, for example. + */ + Util.extractObject = function (origProperty) { + if (origProperty instanceof Error) { + return Util.extractError(origProperty); + } + if (typeof origProperty.toJSON === "function") { + return origProperty.toJSON(); + } + return origProperty; + }; + /** + * Validate that an object is of type { [key: string]: string } + */ + Util.validateStringMap = function (obj) { + if (typeof obj !== "object") { + Logging.info("Invalid properties dropped from payload"); + return; + } + var map = {}; + for (var field in obj) { + var property = ""; + var origProperty = obj[field]; + var propType = typeof origProperty; + if (Util.isPrimitive(origProperty)) { + property = origProperty.toString(); + } + else if (origProperty === null || propType === "undefined") { + property = ""; + } + else if (propType === "function") { + Logging.info("key: " + field + " was function; will not serialize"); + continue; + } + else { + var stringTarget = Util.isArray(origProperty) ? origProperty : Util.extractObject(origProperty); + try { + if (Util.isPrimitive(stringTarget)) { + property = stringTarget; + } + else { + property = JSON.stringify(stringTarget); + } + } + catch (e) { + property = origProperty.constructor.name.toString() + " (Error: " + e.message + ")"; + Logging.info("key: " + field + ", could not be serialized"); + } + } + map[field] = property.substring(0, Util.MAX_PROPERTY_LENGTH); + } + return map; + }; + /** + * Checks if a request url is not on a excluded domain list + * and if it is safe to add correlation headers + */ + Util.canIncludeCorrelationHeader = function (client, requestUrl) { + var excludedDomains = client && client.config && client.config.correlationHeaderExcludedDomains; + if (!excludedDomains || excludedDomains.length == 0 || !requestUrl) { + return true; + } + for (var i = 0; i < excludedDomains.length; i++) { + var regex = new RegExp(excludedDomains[i].replace(/\./g, "\.").replace(/\*/g, ".*")); + try { + if (regex.test(new url.URL(requestUrl).hostname)) { + return false; + } + } + catch (ex) { + // Ignore errors + } + } + return true; + }; + Util.getCorrelationContextTarget = function (response, key) { + var contextHeaders = response.headers && response.headers[RequestResponseHeaders.requestContextHeader]; + if (contextHeaders) { + var keyValues = contextHeaders.split(","); + for (var i = 0; i < keyValues.length; ++i) { + var keyValue = keyValues[i].split("="); + if (keyValue.length == 2 && keyValue[0] == key) { + return keyValue[1]; + } + } + } + }; + /** + * Generate request + * + * Proxify the request creation to handle proxy http + * + * @param {string} requestUrl url endpoint + * @param {Object} requestOptions Request option + * @param {Function} requestCallback callback on request + * @param {boolean} useProxy Use proxy URL from config + * @param {boolean} useAgent Set Http Agent in request + * @returns {http.ClientRequest} request object + */ + Util.makeRequest = function (config, requestUrl, requestOptions, requestCallback, useProxy, useAgent) { + if (useProxy === void 0) { useProxy = true; } + if (useAgent === void 0) { useAgent = true; } + if (requestUrl && requestUrl.indexOf("//") === 0) { + requestUrl = "https:" + requestUrl; + } + var requestUrlParsed = new url.URL(requestUrl); + var options = __assign(__assign({}, requestOptions), { host: requestUrlParsed.hostname, port: requestUrlParsed.port, path: requestUrlParsed.pathname }); + var proxyUrl = undefined; + if (useProxy) { + if (requestUrlParsed.protocol === "https:") { + proxyUrl = config.proxyHttpsUrl || undefined; + } + if (requestUrlParsed.protocol === "http:") { + proxyUrl = config.proxyHttpUrl || undefined; + } + if (proxyUrl) { + if (proxyUrl.indexOf("//") === 0) { + proxyUrl = "http:" + proxyUrl; + } + try { + var proxyUrlParsed = new url.URL(proxyUrl); + // https is not supported at the moment + if (proxyUrlParsed.protocol === "https:") { + Logging.info("Proxies that use HTTPS are not supported"); + proxyUrl = undefined; + } + else { + options = __assign(__assign({}, options), { host: proxyUrlParsed.hostname, port: proxyUrlParsed.port || "80", path: requestUrl, headers: __assign(__assign({}, options.headers), { Host: requestUrlParsed.hostname }) }); + } + } + catch (err) { + Logging.warn("Wrong proxy URL provided"); + } + } + } + var isHttps = requestUrlParsed.protocol === "https:" && !proxyUrl; + if (useAgent) { + if (isHttps && config.httpsAgent !== undefined) { + options.agent = config.httpsAgent; + } + else if (!isHttps && config.httpAgent !== undefined) { + options.agent = config.httpAgent; + } + else if (isHttps) { + // HTTPS without a passed in agent. Use one that enforces our TLS rules + options.agent = Util._useKeepAlive ? Util.keepAliveAgent : Util.tlsRestrictedAgent; + } + } + if (isHttps) { + return https.request(options, requestCallback); + } + else { + return http.request(options, requestCallback); + } + }; + /** + * Parse standard request-context header + */ + Util.safeIncludeCorrelationHeader = function (client, request, correlationHeader) { + var header; // attempt to cast correlationHeader to string + if (typeof correlationHeader === "string") { + header = correlationHeader; + } + else if (correlationHeader instanceof Array) { // string[] + header = correlationHeader.join(","); + } + else if (correlationHeader && typeof correlationHeader.toString === "function") { + // best effort attempt: requires well-defined toString + try { + header = correlationHeader.toString(); + } + catch (err) { + Logging.warn("Outgoing request-context header could not be read. Correlation of requests may be lost.", err, correlationHeader); + } + } + if (header) { + Util.addCorrelationIdHeaderFromString(client, request, header); + } + else { + request.setHeader(RequestResponseHeaders.requestContextHeader, RequestResponseHeaders.requestContextSourceKey + "=" + client.config.correlationId); + } + }; + /** + * Returns string representation of an object suitable for diagnostics logging. + */ + Util.dumpObj = function (object) { + if (object) { + try { + var objectTypeDump = Object["prototype"].toString.call(object); + var propertyValueDump = ""; + if (objectTypeDump === "[object Error]") { + propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'"; + } + else { + propertyValueDump = this.stringify(object); + } + return objectTypeDump + propertyValueDump; + } + catch (ex) { + return object.toString(); + } + } + }; + Util.stringify = function (payload) { + try { + return JSON.stringify(payload); + } + catch (error) { + Logging.warn("Failed to serialize payload", error, payload); + } + }; + Util.addCorrelationIdHeaderFromString = function (client, response, correlationHeader) { + var components = correlationHeader.split(","); + var key = RequestResponseHeaders.requestContextSourceKey + "="; + var found = components.some(function (value) { return value.substring(0, key.length) === key; }); + if (!found) { + response.setHeader(RequestResponseHeaders.requestContextHeader, correlationHeader + "," + RequestResponseHeaders.requestContextSourceKey + "=" + client.config.correlationId); + } + }; + Util._addCloseHandler = function () { + if (!Util._listenerAttached) { + process.on("exit", function () { + Util.isNodeExit = true; + Util._useKeepAlive = false; + }); + Util._listenerAttached = true; + } + }; + Util._useKeepAlive = !JsonConfig_1.JsonConfig.getInstance().noHttpAgentKeepAlive; + Util._listenerAttached = false; + Util.MAX_PROPERTY_LENGTH = 8192; + Util.keepAliveAgent = new https.Agent({ + keepAlive: true, + maxSockets: 25, + secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | + constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 + }); + Util.tlsRestrictedAgent = new https.Agent({ + secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | + constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 + }); + Util.isNodeExit = false; + return Util; +}()); +module.exports = Util; +//# sourceMappingURL=Util.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/Library/Util.js.map b/node_modules/applicationinsights/out/Library/Util.js.map new file mode 100644 index 0000000..6f71859 --- /dev/null +++ b/node_modules/applicationinsights/out/Library/Util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Util.js","sourceRoot":"","sources":["../../Library/Util.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2BAA8B;AAC9B,6BAAgC;AAChC,yBAA4B;AAC5B,qCAAwC;AAExC,mCAAsC;AAGtC,iEAAoE;AAEpE,2CAA0C;AAG1C;IAiBI;QACI,IAAI,CAAC,gBAAgB,EAAE,CAAC;IAC5B,CAAC;IAED;;OAEG;IACW,cAAS,GAAvB,UAAwB,IAAY,EAAE,MAAc;QAChD,IAAI,KAAK,GAAG,EAAE,CAAC;QACf,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YACnD,IAAI,UAAU,GAAG,IAAI,GAAG,GAAG,CAAC;YAC5B,IAAI,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAChC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACrC,IAAI,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;gBACxB,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;gBAC3B,IAAI,MAAM,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE;oBAC5C,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;oBAC/D,MAAM;iBACT;aACJ;SACJ;QAED,OAAO,KAAK,CAAC;IACjB,CAAC;IAED;;OAEG;IACW,SAAI,GAAlB,UAA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esContent":["import http = require(\"http\");\r\nimport https = require(\"https\");\r\nimport url = require(\"url\");\r\nimport constants = require(\"constants\");\r\n\r\nimport Logging = require(\"./Logging\");\r\nimport Config = require(\"./Config\");\r\nimport TelemetryClient = require(\"../Library/TelemetryClient\");\r\nimport RequestResponseHeaders = require(\"./RequestResponseHeaders\");\r\nimport { HttpRequest } from \"../Library/Functions\";\r\nimport { JsonConfig } from \"./JsonConfig\";\r\n\r\n\r\nclass Util {\r\n private static _useKeepAlive = !JsonConfig.getInstance().noHttpAgentKeepAlive;\r\n private static _listenerAttached = false;\r\n\r\n public static MAX_PROPERTY_LENGTH = 8192;\r\n public static keepAliveAgent: http.Agent = new https.Agent({\r\n keepAlive: true,\r\n maxSockets: 25,\r\n secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 |\r\n constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1\r\n });\r\n public static tlsRestrictedAgent: http.Agent = new https.Agent({\r\n secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 |\r\n constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1\r\n });\r\n public static isNodeExit = false;\r\n\r\n public constructor() {\r\n Util._addCloseHandler();\r\n }\r\n\r\n /**\r\n * helper method to access userId and sessionId cookie\r\n */\r\n public static getCookie(name: string, cookie: string) {\r\n var value = \"\";\r\n if (name && name.length && typeof cookie === \"string\") {\r\n var cookieName = name + \"=\";\r\n var cookies = cookie.split(\";\");\r\n for (var i = 0; i < cookies.length; i++) {\r\n var cookie = cookies[i];\r\n cookie = Util.trim(cookie);\r\n if (cookie && cookie.indexOf(cookieName) === 0) {\r\n value = cookie.substring(cookieName.length, cookies[i].length);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n /**\r\n * helper method to trim strings (IE8 does not implement String.prototype.trim)\r\n */\r\n public static trim(str: string): string {\r\n if (typeof str === \"string\") {\r\n return str.replace(/^\\s+|\\s+$/g, \"\");\r\n } else {\r\n return \"\";\r\n }\r\n }\r\n\r\n /**\r\n * Convert an array of int32 to Base64 (no '==' at the end).\r\n * MSB first.\r\n */\r\n public static int32ArrayToBase64(array: number[]) {\r\n let toChar = (v: number, i: number) =>\r\n String.fromCharCode((v >> i) & 0xFF);\r\n let int32AsString = (v: number) =>\r\n toChar(v, 24) + toChar(v, 16) + toChar(v, 8) + toChar(v, 0);\r\n let x = array.map(int32AsString).join(\"\");\r\n const b = Buffer.from ? Buffer.from(x, \"binary\") : new Buffer(x, \"binary\");\r\n let s = b.toString(\"base64\");\r\n return s.substr(0, s.indexOf(\"=\"));\r\n }\r\n\r\n /**\r\n * generate a random 32bit number (-0x80000000..0x7FFFFFFF).\r\n */\r\n public static random32() {\r\n return (0x100000000 * Math.random()) | 0;\r\n }\r\n\r\n /**\r\n * generate a random 32bit number (0x00000000..0xFFFFFFFF).\r\n */\r\n public static randomu32() {\r\n return Util.random32() + 0x80000000;\r\n }\r\n\r\n /**\r\n * generate W3C-compatible trace id\r\n * https://github.com/w3c/distributed-tracing/blob/master/trace_context/HTTP_HEADER_FORMAT.md#trace-id\r\n */\r\n public static w3cTraceId() {\r\n var hexValues = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\r\n\r\n // rfc4122 version 4 UUID without dashes and with lowercase letters\r\n var oct = \"\", tmp;\r\n for (var a = 0; a < 4; a++) {\r\n tmp = Util.random32();\r\n oct +=\r\n hexValues[tmp & 0xF] +\r\n hexValues[tmp >> 4 & 0xF] +\r\n hexValues[tmp >> 8 & 0xF] +\r\n hexValues[tmp >> 12 & 0xF] +\r\n hexValues[tmp >> 16 & 0xF] +\r\n hexValues[tmp >> 20 & 0xF] +\r\n hexValues[tmp >> 24 & 0xF] +\r\n hexValues[tmp >> 28 & 0xF];\r\n }\r\n\r\n // \"Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively\"\r\n var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0];\r\n return oct.substr(0, 8) + oct.substr(9, 4) + \"4\" + oct.substr(13, 3) + clockSequenceHi + oct.substr(16, 3) + oct.substr(19, 12);\r\n }\r\n\r\n public static w3cSpanId() {\r\n return Util.w3cTraceId().substring(16);\r\n }\r\n\r\n public static isValidW3CId(id: string): boolean {\r\n return id.length === 32 && id !== \"00000000000000000000000000000000\";\r\n }\r\n\r\n /**\r\n * Check if an object is of type Array\r\n */\r\n public static isArray(obj: any): boolean {\r\n return Object.prototype.toString.call(obj) === \"[object Array]\";\r\n }\r\n\r\n /**\r\n * Check if an object is of type Error\r\n */\r\n public static isError(obj: any): boolean {\r\n return Object.prototype.toString.call(obj) === \"[object Error]\";\r\n }\r\n\r\n public static isPrimitive(input: any): boolean {\r\n const propType = typeof input;\r\n return propType === \"string\" || propType === \"number\" || propType === \"boolean\";\r\n }\r\n\r\n /**\r\n * Check if an object is of type Date\r\n */\r\n public static isDate(obj: any): boolean {\r\n return Object.prototype.toString.call(obj) === \"[object Date]\";\r\n }\r\n\r\n /**\r\n * Convert ms to c# time span format\r\n */\r\n public static msToTimeSpan(totalms: number): string {\r\n if (isNaN(totalms) || totalms < 0) {\r\n totalms = 0;\r\n }\r\n\r\n var sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, \"\");\r\n var min = \"\" + Math.floor(totalms / (1000 * 60)) % 60;\r\n var hour = \"\" + Math.floor(totalms / (1000 * 60 * 60)) % 24;\r\n var days = Math.floor(totalms / (1000 * 60 * 60 * 24));\r\n\r\n sec = sec.indexOf(\".\") < 2 ? \"0\" + sec : sec;\r\n min = min.length < 2 ? \"0\" + min : min;\r\n hour = hour.length < 2 ? \"0\" + hour : hour;\r\n var daysText = days > 0 ? days + \".\" : \"\";\r\n\r\n return daysText + hour + \":\" + min + \":\" + sec;\r\n }\r\n\r\n /**\r\n * Using JSON.stringify, by default Errors do not serialize to something useful:\r\n * Simplify a generic Node Error into a simpler map for customDimensions\r\n * Custom errors can still implement toJSON to override this functionality\r\n */\r\n protected static extractError(err: Error): { message: string, code: string } {\r\n // Error is often subclassed so may have code OR id properties:\r\n // https://nodejs.org/api/errors.html#errors_error_code\r\n const looseError = err as any;\r\n return {\r\n message: err.message,\r\n code: looseError.code || looseError.id || \"\"\r\n }\r\n }\r\n\r\n /**\r\n * Manually call toJSON if available to pre-convert the value.\r\n * If a primitive is returned, then the consumer of this function can skip JSON.stringify.\r\n * This avoids double escaping of quotes for Date objects, for example.\r\n */\r\n protected static extractObject(origProperty: any): any {\r\n if (origProperty instanceof Error) {\r\n return Util.extractError(origProperty);\r\n }\r\n if (typeof origProperty.toJSON === \"function\") {\r\n return origProperty.toJSON();\r\n }\r\n return origProperty;\r\n }\r\n\r\n /**\r\n * Validate that an object is of type { [key: string]: string }\r\n */\r\n public static validateStringMap(obj: any): { [key: string]: string } {\r\n if (typeof obj !== \"object\") {\r\n Logging.info(\"Invalid properties dropped from payload\");\r\n return;\r\n }\r\n const map: { [key: string]: string } = {};\r\n for (let field in obj) {\r\n let property: string = \"\";\r\n const origProperty: any = obj[field];\r\n const propType = typeof origProperty;\r\n\r\n if (Util.isPrimitive(origProperty)) {\r\n property = origProperty.toString();\r\n } else if (origProperty === null || propType === \"undefined\") {\r\n property = \"\";\r\n } else if (propType === \"function\") {\r\n Logging.info(\"key: \" + field + \" was function; will not serialize\");\r\n continue;\r\n } else {\r\n const stringTarget = Util.isArray(origProperty) ? origProperty : Util.extractObject(origProperty);\r\n try {\r\n if (Util.isPrimitive(stringTarget)) {\r\n property = stringTarget;\r\n } else {\r\n property = JSON.stringify(stringTarget);\r\n }\r\n } catch (e) {\r\n property = origProperty.constructor.name.toString() + \" (Error: \" + e.message + \")\";\r\n Logging.info(\"key: \" + field + \", could not be serialized\");\r\n }\r\n }\r\n\r\n map[field] = property.substring(0, Util.MAX_PROPERTY_LENGTH);\r\n }\r\n return map;\r\n }\r\n\r\n\r\n /**\r\n * Checks if a request url is not on a excluded domain list\r\n * and if it is safe to add correlation headers\r\n */\r\n public static canIncludeCorrelationHeader(client: TelemetryClient, requestUrl: string) {\r\n let excludedDomains = client && client.config && client.config.correlationHeaderExcludedDomains;\r\n if (!excludedDomains || excludedDomains.length == 0 || !requestUrl) {\r\n return true;\r\n }\r\n\r\n for (let i = 0; i < excludedDomains.length; i++) {\r\n let regex = new RegExp(excludedDomains[i].replace(/\\./g, \"\\.\").replace(/\\*/g, \".*\"));\r\n try {\r\n if (regex.test(new url.URL(requestUrl).hostname)) {\r\n return false;\r\n }\r\n }\r\n catch (ex) {\r\n // Ignore errors\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public static getCorrelationContextTarget(response: http.ClientResponse | http.ServerRequest | HttpRequest, key: string) {\r\n const contextHeaders = response.headers && response.headers[RequestResponseHeaders.requestContextHeader];\r\n if (contextHeaders) {\r\n const keyValues = (contextHeaders).split(\",\");\r\n for (let i = 0; i < keyValues.length; ++i) {\r\n const keyValue = keyValues[i].split(\"=\");\r\n if (keyValue.length == 2 && keyValue[0] == key) {\r\n return keyValue[1];\r\n }\r\n }\r\n }\r\n }\r\n\r\n\r\n /**\r\n * Generate request\r\n *\r\n * Proxify the request creation to handle proxy http\r\n *\r\n * @param {string} requestUrl url endpoint\r\n * @param {Object} requestOptions Request option\r\n * @param {Function} requestCallback callback on request\r\n * @param {boolean} useProxy Use proxy URL from config\r\n * @param {boolean} useAgent Set Http Agent in request\r\n * @returns {http.ClientRequest} request object\r\n */\r\n public static makeRequest(\r\n config: Config,\r\n requestUrl: string,\r\n requestOptions: http.RequestOptions | https.RequestOptions,\r\n requestCallback: (res: http.IncomingMessage) => void,\r\n useProxy = true,\r\n useAgent = true): http.ClientRequest {\r\n\r\n if (requestUrl && requestUrl.indexOf(\"//\") === 0) {\r\n requestUrl = \"https:\" + requestUrl;\r\n }\r\n\r\n var requestUrlParsed = new url.URL(requestUrl);\r\n var options = {\r\n ...requestOptions,\r\n host: requestUrlParsed.hostname,\r\n port: requestUrlParsed.port,\r\n path: requestUrlParsed.pathname\r\n };\r\n\r\n var proxyUrl: string = undefined;\r\n if (useProxy) {\r\n if (requestUrlParsed.protocol === \"https:\") {\r\n proxyUrl = config.proxyHttpsUrl || undefined;\r\n }\r\n if (requestUrlParsed.protocol === \"http:\") {\r\n proxyUrl = config.proxyHttpUrl || undefined;\r\n }\r\n if (proxyUrl) {\r\n if (proxyUrl.indexOf(\"//\") === 0) {\r\n proxyUrl = \"http:\" + proxyUrl;\r\n }\r\n try {\r\n var proxyUrlParsed = new url.URL(proxyUrl);\r\n // https is not supported at the moment\r\n if (proxyUrlParsed.protocol === \"https:\") {\r\n Logging.info(\"Proxies that use HTTPS are not supported\");\r\n proxyUrl = undefined;\r\n } else {\r\n options = {\r\n ...options,\r\n host: proxyUrlParsed.hostname,\r\n port: proxyUrlParsed.port || \"80\",\r\n path: requestUrl,\r\n headers: {\r\n ...options.headers,\r\n Host: requestUrlParsed.hostname\r\n }\r\n };\r\n }\r\n }\r\n catch (err) {\r\n Logging.warn(\"Wrong proxy URL provided\");\r\n }\r\n }\r\n }\r\n\r\n var isHttps = requestUrlParsed.protocol === \"https:\" && !proxyUrl;\r\n if (useAgent) {\r\n if (isHttps && config.httpsAgent !== undefined) {\r\n options.agent = config.httpsAgent;\r\n } else if (!isHttps && config.httpAgent !== undefined) {\r\n options.agent = config.httpAgent;\r\n } else if (isHttps) {\r\n // HTTPS without a passed in agent. Use one that enforces our TLS rules\r\n options.agent = Util._useKeepAlive ? Util.keepAliveAgent : Util.tlsRestrictedAgent;\r\n }\r\n }\r\n if (isHttps) {\r\n return https.request(options, requestCallback);\r\n } else {\r\n return http.request(options, requestCallback);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Parse standard request-context header\r\n */\r\n public static safeIncludeCorrelationHeader(client: TelemetryClient, request: http.ClientRequest | http.ServerResponse, correlationHeader: any) {\r\n let header: string; // attempt to cast correlationHeader to string\r\n if (typeof correlationHeader === \"string\") {\r\n header = correlationHeader;\r\n } else if (correlationHeader instanceof Array) { // string[]\r\n header = correlationHeader.join(\",\");\r\n } else if (correlationHeader && typeof (correlationHeader as any).toString === \"function\") {\r\n // best effort attempt: requires well-defined toString\r\n try {\r\n header = (correlationHeader as any).toString();\r\n } catch (err) {\r\n Logging.warn(\"Outgoing request-context header could not be read. Correlation of requests may be lost.\", err, correlationHeader);\r\n }\r\n }\r\n\r\n if (header) {\r\n Util.addCorrelationIdHeaderFromString(client, request, header);\r\n } else {\r\n request.setHeader(\r\n RequestResponseHeaders.requestContextHeader,\r\n `${RequestResponseHeaders.requestContextSourceKey}=${client.config.correlationId}`);\r\n }\r\n }\r\n\r\n /**\r\n * Returns string representation of an object suitable for diagnostics logging.\r\n */\r\n public static dumpObj(object: any): string {\r\n if (object) {\r\n try {\r\n const objectTypeDump: string = Object[\"prototype\"].toString.call(object);\r\n let propertyValueDump: string = \"\";\r\n if (objectTypeDump === \"[object Error]\") {\r\n propertyValueDump = \"{ stack: '\" + object.stack + \"', message: '\" + object.message + \"', name: '\" + object.name + \"'\";\r\n } else {\r\n propertyValueDump = this.stringify(object);\r\n }\r\n\r\n return objectTypeDump + propertyValueDump;\r\n }\r\n catch (ex) {\r\n return object.toString();\r\n }\r\n }\r\n }\r\n\r\n public static stringify(payload: any) {\r\n try {\r\n return JSON.stringify(payload);\r\n } catch (error) {\r\n Logging.warn(\"Failed to serialize payload\", error, payload);\r\n }\r\n }\r\n\r\n private static addCorrelationIdHeaderFromString(client: TelemetryClient, response: http.ClientRequest | http.ServerResponse, correlationHeader: string) {\r\n const components = correlationHeader.split(\",\");\r\n const key = `${RequestResponseHeaders.requestContextSourceKey}=`;\r\n const found = components.some(value => value.substring(0, key.length) === key);\r\n\r\n if (!found) {\r\n response.setHeader(\r\n RequestResponseHeaders.requestContextHeader,\r\n `${correlationHeader},${RequestResponseHeaders.requestContextSourceKey}=${client.config.correlationId}`);\r\n }\r\n }\r\n\r\n private static _addCloseHandler() {\r\n if (!Util._listenerAttached) {\r\n process.on(\"exit\", () => {\r\n Util.isNodeExit = true;\r\n Util._useKeepAlive = false;\r\n });\r\n Util._listenerAttached = true;\r\n }\r\n }\r\n}\r\nexport = Util;\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.d.ts b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.d.ts new file mode 100644 index 0000000..dc880d2 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.d.ts @@ -0,0 +1,6 @@ +import Contracts = require("../Declarations/Contracts"); +import Context = require("../Library/Context"); +/** + * A telemetry processor that handles Azure specific variables. + */ +export declare function azureRoleEnvironmentTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, context: Context): void; diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js new file mode 100644 index 0000000..17cc8c9 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.azureRoleEnvironmentTelemetryProcessor = void 0; +/** + * A telemetry processor that handles Azure specific variables. + */ +function azureRoleEnvironmentTelemetryProcessor(envelope, context) { + if (process.env.WEBSITE_SITE_NAME) { // Azure Web apps and Functions + envelope.tags[context.keys.cloudRole] = process.env.WEBSITE_SITE_NAME; + } + if (process.env.WEBSITE_INSTANCE_ID) { + envelope.tags[context.keys.cloudRoleInstance] = process.env.WEBSITE_INSTANCE_ID; + } +} +exports.azureRoleEnvironmentTelemetryProcessor = azureRoleEnvironmentTelemetryProcessor; +//# sourceMappingURL=AzureRoleEnvironmentTelemetryInitializer.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js.map b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js.map new file mode 100644 index 0000000..353e8f9 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AzureRoleEnvironmentTelemetryInitializer.js","sourceRoot":"","sources":["../../TelemetryProcessors/AzureRoleEnvironmentTelemetryInitializer.ts"],"names":[],"mappings":";;;AAGA;;GAEG;AACH,SAAgB,sCAAsC,CAAC,QAAqC,EAAE,OAAgB;IAC1G,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAE,+BAA+B;QAChE,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;KACzE;IACD,IAAI,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE;QACjC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;KACnF;AACL,CAAC;AAPD,wFAOC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\");\r\nimport Context = require(\"../Library/Context\");\r\n\r\n/**\r\n * A telemetry processor that handles Azure specific variables.\r\n */\r\nexport function azureRoleEnvironmentTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, context: Context): void {\r\n if (process.env.WEBSITE_SITE_NAME) { // Azure Web apps and Functions\r\n envelope.tags[context.keys.cloudRole] = process.env.WEBSITE_SITE_NAME;\r\n }\r\n if (process.env.WEBSITE_INSTANCE_ID) {\r\n envelope.tags[context.keys.cloudRoleInstance] = process.env.WEBSITE_INSTANCE_ID;\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.d.ts b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.d.ts new file mode 100644 index 0000000..fa36030 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.d.ts @@ -0,0 +1,3 @@ +import Contracts = require("../Declarations/Contracts"); +import QuickPulseStateManager = require("../Library/QuickPulseStateManager"); +export declare function performanceMetricsTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, client?: QuickPulseStateManager): boolean; diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js new file mode 100644 index 0000000..9283ab6 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.performanceMetricsTelemetryProcessor = void 0; +var AutoCollectPerformance = require("../AutoCollection/Performance"); +var TelemetryType = require("../Declarations/Contracts"); +function performanceMetricsTelemetryProcessor(envelope, client) { + // If live metrics is enabled, forward all telemetry there + if (client) { + client.addDocument(envelope); + } + // Increment rate counters (for standard metrics and live metrics) + switch (envelope.data.baseType) { + case TelemetryType.TelemetryTypeString.Exception: + AutoCollectPerformance.countException(); + break; + case TelemetryType.TelemetryTypeString.Request: + var requestData = envelope.data.baseData; + AutoCollectPerformance.countRequest(requestData.duration, requestData.success); + break; + case TelemetryType.TelemetryTypeString.Dependency: + var remoteDependencyData = envelope.data.baseData; + AutoCollectPerformance.countDependency(remoteDependencyData.duration, remoteDependencyData.success); + break; + } + return true; +} +exports.performanceMetricsTelemetryProcessor = performanceMetricsTelemetryProcessor; +//# sourceMappingURL=PerformanceMetricsTelemetryProcessor.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js.map b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js.map new file mode 100644 index 0000000..6cbf521 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PerformanceMetricsTelemetryProcessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PerformanceMetricsTelemetryProcessor.js","sourceRoot":"","sources":["../../TelemetryProcessors/PerformanceMetricsTelemetryProcessor.ts"],"names":[],"mappings":";;;AAEA,sEAAyE;AACzE,yDAA2D;AAE3D,SAAgB,oCAAoC,CAAC,QAAqC,EAAE,MAA+B;IACvH,0DAA0D;IAC1D,IAAI,MAAM,EAAE;QACR,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;KAChC;IAED,kEAAkE;IAClE,QAAQ,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE;QAC5B,KAAK,aAAa,CAAC,mBAAmB,CAAC,SAAS;YAC5C,sBAAsB,CAAC,cAAc,EAAE,CAAC;YACxC,MAAM;QACV,KAAK,aAAa,CAAC,mBAAmB,CAAC,OAAO;YAC1C,IAAM,WAAW,GAA2B,QAAQ,CAAC,IAAY,CAAC,QAAQ,CAAC;YAC3E,sBAAsB,CAAC,YAAY,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;YAC/E,MAAM;QACV,KAAK,aAAa,CAAC,mBAAmB,CAAC,UAAU;YAC7C,IAAM,oBAAoB,GAAoC,QAAQ,CAAC,IAAY,CAAC,QAAQ,CAAC;YAC7F,sBAAsB,CAAC,eAAe,CAAC,oBAAoB,CAAC,QAAQ,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC;YACpG,MAAM;KACb;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AArBD,oFAqBC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\");\r\nimport QuickPulseStateManager = require(\"../Library/QuickPulseStateManager\")\r\nimport AutoCollectPerformance = require(\"../AutoCollection/Performance\");\r\nimport * as TelemetryType from \"../Declarations/Contracts\";\r\n\r\nexport function performanceMetricsTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, client?: QuickPulseStateManager): boolean {\r\n // If live metrics is enabled, forward all telemetry there\r\n if (client) {\r\n client.addDocument(envelope);\r\n }\r\n\r\n // Increment rate counters (for standard metrics and live metrics)\r\n switch (envelope.data.baseType) {\r\n case TelemetryType.TelemetryTypeString.Exception:\r\n AutoCollectPerformance.countException();\r\n break;\r\n case TelemetryType.TelemetryTypeString.Request:\r\n const requestData: Contracts.RequestData = (envelope.data as any).baseData;\r\n AutoCollectPerformance.countRequest(requestData.duration, requestData.success);\r\n break;\r\n case TelemetryType.TelemetryTypeString.Dependency:\r\n const remoteDependencyData: Contracts.RemoteDependencyData = (envelope.data as any).baseData;\r\n AutoCollectPerformance.countDependency(remoteDependencyData.duration, remoteDependencyData.success);\r\n break;\r\n }\r\n return true;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.d.ts b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.d.ts new file mode 100644 index 0000000..442b005 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.d.ts @@ -0,0 +1,3 @@ +import Contracts = require("../Declarations/Contracts"); +import Context = require("../Library/Context"); +export declare function preAggregatedMetricsTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, context: Context): boolean; diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js new file mode 100644 index 0000000..e8e8308 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js @@ -0,0 +1,72 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.preAggregatedMetricsTelemetryProcessor = void 0; +var Contracts = require("../Declarations/Contracts"); +var AutoCollecPreAggregatedMetrics = require("../AutoCollection/PreAggregatedMetrics"); +var TelemetryType = require("../Declarations/Contracts"); +function preAggregatedMetricsTelemetryProcessor(envelope, context) { + if (AutoCollecPreAggregatedMetrics.isEnabled()) { + // Increment rate counters + switch (envelope.data.baseType) { + case TelemetryType.TelemetryTypeString.Exception: + var exceptionData = envelope.data.baseData; + exceptionData.properties = __assign(__assign({}, exceptionData.properties), { "_MS.ProcessedByMetricExtractors": "(Name:'Exceptions', Ver:'1.1')" }); + var exceptionDimensions = { + cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance], + cloudRoleName: envelope.tags[context.keys.cloudRole] + }; + AutoCollecPreAggregatedMetrics.countException(exceptionDimensions); + break; + case TelemetryType.TelemetryTypeString.Trace: + var traceData = envelope.data.baseData; + traceData.properties = __assign(__assign({}, traceData.properties), { "_MS.ProcessedByMetricExtractors": "(Name:'Traces', Ver:'1.1')" }); + var traceDimensions = { + cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance], + cloudRoleName: envelope.tags[context.keys.cloudRole], + traceSeverityLevel: Contracts.SeverityLevel[traceData.severity] + }; + AutoCollecPreAggregatedMetrics.countTrace(traceDimensions); + break; + case TelemetryType.TelemetryTypeString.Request: + var requestData = envelope.data.baseData; + requestData.properties = __assign(__assign({}, requestData.properties), { "_MS.ProcessedByMetricExtractors": "(Name:'Requests', Ver:'1.1')" }); + var requestDimensions = { + cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance], + cloudRoleName: envelope.tags[context.keys.cloudRole], + operationSynthetic: envelope.tags[context.keys.operationSyntheticSource], + requestSuccess: requestData.success, + requestResultCode: requestData.responseCode + }; + AutoCollecPreAggregatedMetrics.countRequest(requestData.duration, requestDimensions); + break; + case TelemetryType.TelemetryTypeString.Dependency: + var remoteDependencyData = envelope.data.baseData; + remoteDependencyData.properties = __assign(__assign({}, remoteDependencyData.properties), { "_MS.ProcessedByMetricExtractors": "(Name:'Dependencies', Ver:'1.1')" }); + var dependencyDimensions = { + cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance], + cloudRoleName: envelope.tags[context.keys.cloudRole], + operationSynthetic: envelope.tags[context.keys.operationSyntheticSource], + dependencySuccess: remoteDependencyData.success, + dependencyType: remoteDependencyData.type, + dependencyTarget: remoteDependencyData.target, + dependencyResultCode: remoteDependencyData.resultCode + }; + AutoCollecPreAggregatedMetrics.countDependency(remoteDependencyData.duration, dependencyDimensions); + break; + } + } + return true; +} +exports.preAggregatedMetricsTelemetryProcessor = preAggregatedMetricsTelemetryProcessor; +//# sourceMappingURL=PreAggregatedMetricsTelemetryProcessor.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js.map b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js.map new file mode 100644 index 0000000..baf5472 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PreAggregatedMetricsTelemetryProcessor.js","sourceRoot":"","sources":["../../TelemetryProcessors/PreAggregatedMetricsTelemetryProcessor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,qDAAwD;AACxD,uFAA0F;AAC1F,yDAA2D;AAS3D,SAAgB,sCAAsC,CAAC,QAAqC,EAAE,OAAgB;IAC1G,IAAI,8BAA8B,CAAC,SAAS,EAAE,EAAE;QAC5C,0BAA0B;QAC1B,QAAQ,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE;YAC5B,KAAK,aAAa,CAAC,mBAAmB,CAAC,SAAS;gBAC5C,IAAM,aAAa,GAA6B,Q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racts\");\r\nimport AutoCollecPreAggregatedMetrics = require(\"../AutoCollection/PreAggregatedMetrics\");\r\nimport * as TelemetryType from \"../Declarations/Contracts\";\r\nimport {\r\n MetricDependencyDimensions,\r\n MetricExceptionDimensions,\r\n MetricRequestDimensions,\r\n MetricTraceDimensions\r\n} from \"../Declarations/Metrics/AggregatedMetricDimensions\";\r\nimport Context = require(\"../Library/Context\");\r\n\r\nexport function preAggregatedMetricsTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, context: Context): boolean {\r\n if (AutoCollecPreAggregatedMetrics.isEnabled()) {\r\n // Increment rate counters\r\n switch (envelope.data.baseType) {\r\n case TelemetryType.TelemetryTypeString.Exception:\r\n const exceptionData: Contracts.ExceptionData = (envelope.data as any).baseData;\r\n exceptionData.properties = {\r\n ...exceptionData.properties,\r\n \"_MS.ProcessedByMetricExtractors\": \"(Name:'Exceptions', Ver:'1.1')\"\r\n };\r\n let exceptionDimensions: MetricExceptionDimensions = {\r\n cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance],\r\n cloudRoleName: envelope.tags[context.keys.cloudRole]\r\n };\r\n AutoCollecPreAggregatedMetrics.countException(exceptionDimensions);\r\n break;\r\n case TelemetryType.TelemetryTypeString.Trace:\r\n const traceData: Contracts.TraceTelemetry = (envelope.data as any).baseData;\r\n traceData.properties = {\r\n ...traceData.properties,\r\n \"_MS.ProcessedByMetricExtractors\": \"(Name:'Traces', Ver:'1.1')\"\r\n }\r\n let traceDimensions: MetricTraceDimensions = {\r\n cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance],\r\n cloudRoleName: envelope.tags[context.keys.cloudRole],\r\n traceSeverityLevel: Contracts.SeverityLevel[traceData.severity]\r\n };\r\n AutoCollecPreAggregatedMetrics.countTrace(traceDimensions);\r\n break;\r\n case TelemetryType.TelemetryTypeString.Request:\r\n const requestData: Contracts.RequestData = (envelope.data as any).baseData;\r\n requestData.properties = {\r\n ...requestData.properties,\r\n \"_MS.ProcessedByMetricExtractors\": \"(Name:'Requests', Ver:'1.1')\"\r\n }\r\n let requestDimensions: MetricRequestDimensions = {\r\n cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance],\r\n cloudRoleName: envelope.tags[context.keys.cloudRole],\r\n operationSynthetic: envelope.tags[context.keys.operationSyntheticSource],\r\n requestSuccess: requestData.success,\r\n requestResultCode: requestData.responseCode\r\n };\r\n AutoCollecPreAggregatedMetrics.countRequest(requestData.duration, requestDimensions);\r\n break;\r\n case TelemetryType.TelemetryTypeString.Dependency:\r\n const remoteDependencyData: Contracts.RemoteDependencyData = (envelope.data as any).baseData;\r\n remoteDependencyData.properties = {\r\n ...remoteDependencyData.properties,\r\n \"_MS.ProcessedByMetricExtractors\": \"(Name:'Dependencies', Ver:'1.1')\"\r\n }\r\n let dependencyDimensions: MetricDependencyDimensions = {\r\n cloudRoleInstance: envelope.tags[context.keys.cloudRoleInstance],\r\n cloudRoleName: envelope.tags[context.keys.cloudRole],\r\n operationSynthetic: envelope.tags[context.keys.operationSyntheticSource],\r\n dependencySuccess: remoteDependencyData.success,\r\n dependencyType: remoteDependencyData.type,\r\n dependencyTarget: remoteDependencyData.target,\r\n dependencyResultCode: remoteDependencyData.resultCode\r\n };\r\n AutoCollecPreAggregatedMetrics.countDependency(remoteDependencyData.duration, dependencyDimensions);\r\n break;\r\n }\r\n }\r\n return true;\r\n}\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.d.ts b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.d.ts new file mode 100644 index 0000000..4b82d7b --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.d.ts @@ -0,0 +1,10 @@ +import Contracts = require("../Declarations/Contracts"); +import { CorrelationContext } from "../AutoCollection/CorrelationContextManager"; +/** + * A telemetry processor that handles sampling. + */ +export declare function samplingTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, contextObjects: { + correlationContext: CorrelationContext; +}): boolean; +/** Ported from AI .NET SDK */ +export declare function getSamplingHashCode(input: string): number; diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js new file mode 100644 index 0000000..edd45cd --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSamplingHashCode = exports.samplingTelemetryProcessor = void 0; +var Contracts = require("../Declarations/Contracts"); +/** + * A telemetry processor that handles sampling. + */ +function samplingTelemetryProcessor(envelope, contextObjects) { + var samplingPercentage = envelope.sampleRate; // Set for us in Client.getEnvelope + var isSampledIn = false; + if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) { + return true; + } + else if (envelope.data && Contracts.TelemetryType.Metric === Contracts.baseTypeToTelemetryType(envelope.data.baseType)) { + // Exclude MetricData telemetry from sampling + return true; + } + else if (contextObjects.correlationContext && contextObjects.correlationContext.operation) { + // If we're using dependency correlation, sampling should retain all telemetry from a given request + isSampledIn = getSamplingHashCode(contextObjects.correlationContext.operation.id) < samplingPercentage; + } + else { + // If we're not using dependency correlation, sampling should use a random distribution on each item + isSampledIn = (Math.random() * 100) < samplingPercentage; + } + return isSampledIn; +} +exports.samplingTelemetryProcessor = samplingTelemetryProcessor; +/** Ported from AI .NET SDK */ +function getSamplingHashCode(input) { + var csharpMin = -2147483648; + var csharpMax = 2147483647; + var hash = 5381; + if (!input) { + return 0; + } + while (input.length < 8) { + input = input + input; + } + for (var i = 0; i < input.length; i++) { + // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0) + hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i) | 0); + } + hash = hash <= csharpMin ? csharpMax : Math.abs(hash); + return (hash / csharpMax) * 100; +} +exports.getSamplingHashCode = getSamplingHashCode; +//# sourceMappingURL=SamplingTelemetryProcessor.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js.map b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js.map new file mode 100644 index 0000000..9679b7e --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/SamplingTelemetryProcessor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SamplingTelemetryProcessor.js","sourceRoot":"","sources":["../../TelemetryProcessors/SamplingTelemetryProcessor.ts"],"names":[],"mappings":";;;AAAA,qDAAwD;AAGxD;;GAEG;AACH,SAAgB,0BAA0B,CAAC,QAAqC,EAAE,cAA0D;IACxI,IAAI,kBAAkB,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,mCAAmC;IACjF,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,IAAI,kBAAkB,KAAK,IAAI,IAAI,kBAAkB,KAAK,SAAS,IAAI,kBAAkB,IAAI,GAAG,EAAE;QAC9F,OAAO,IAAI,CAAC;KACf;SAAM,IAAI,QAAQ,CAAC,IAAI,IAAI,SAAS,CAAC,aAAa,CAAC,MAAM,KAAK,SAAS,CAAC,uBAAuB,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAyC,CAAC,EAAE;QACvJ,6CAA6C;QAC7C,OAAO,IAAI,CAAC;KACf;SAAM,IAAI,cAAc,CAAC,kBAAkB,IAAI,cAAc,CAAC,kBAAkB,CAAC,SAAS,EAAE;QACzF,mGAAmG;QACnG,WAAW,GAAG,mBAAmB,CAAC,cAAc,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,CAAC,GAAG,kBAAkB,CAAC;KAC1G;SAAM;QACH,oGAAoG;QACpG,WAAW,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,GAAG,kBAAkB,CAAC;KAC5D;IAED,OAAO,WAAW,CAAC;AACvB,CAAC;AAlBD,gEAkBC;AAED,8BAA8B;AAC9B,SAAgB,mBAAmB,CAAC,KAAa;IAC7C,IAAI,SAAS,GAAG,CAAC,UAAU,CAAC;IAC5B,IAAI,SAAS,GAAG,UAAU,CAAC;IAC3B,IAAI,IAAI,GAAG,IAAI,CAAC;IAEhB,IAAI,CAAC,KAAK,EAAE;QACR,OAAO,CAAC,CAAC;KACZ;IAED,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;QACrB,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;KACzB;IAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,uGAAuG;QACvG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;KACjE;IAED,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACtD,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC;AACpC,CAAC;AApBD,kDAoBC","sourcesContent":["import Contracts = require(\"../Declarations/Contracts\");\r\nimport { CorrelationContext } from \"../AutoCollection/CorrelationContextManager\";\r\n\r\n/**\r\n * A telemetry processor that handles sampling.\r\n */\r\nexport function samplingTelemetryProcessor(envelope: Contracts.EnvelopeTelemetry, contextObjects: { correlationContext: CorrelationContext }): boolean {\r\n var samplingPercentage = envelope.sampleRate; // Set for us in Client.getEnvelope\r\n var isSampledIn = false;\r\n\r\n if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {\r\n return true;\r\n } else if (envelope.data && Contracts.TelemetryType.Metric === Contracts.baseTypeToTelemetryType(envelope.data.baseType as Contracts.TelemetryTypeValues)) {\r\n // Exclude MetricData telemetry from sampling\r\n return true;\r\n } else if (contextObjects.correlationContext && contextObjects.correlationContext.operation) {\r\n // If we're using dependency correlation, sampling should retain all telemetry from a given request\r\n isSampledIn = getSamplingHashCode(contextObjects.correlationContext.operation.id) < samplingPercentage;\r\n } else {\r\n // If we're not using dependency correlation, sampling should use a random distribution on each item\r\n isSampledIn = (Math.random() * 100) < samplingPercentage;\r\n }\r\n\r\n return isSampledIn;\r\n}\r\n\r\n/** Ported from AI .NET SDK */\r\nexport function getSamplingHashCode(input: string): number {\r\n var csharpMin = -2147483648;\r\n var csharpMax = 2147483647;\r\n var hash = 5381;\r\n\r\n if (!input) {\r\n return 0;\r\n }\r\n\r\n while (input.length < 8) {\r\n input = input + input;\r\n }\r\n\r\n for (var i = 0; i < input.length; i++) {\r\n // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)\r\n hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i) | 0);\r\n }\r\n\r\n hash = hash <= csharpMin ? csharpMax : Math.abs(hash);\r\n return (hash / csharpMax) * 100;\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/index.d.ts b/node_modules/applicationinsights/out/TelemetryProcessors/index.d.ts new file mode 100644 index 0000000..0e3aab5 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/index.d.ts @@ -0,0 +1,4 @@ +export * from "./AzureRoleEnvironmentTelemetryInitializer"; +export * from "./SamplingTelemetryProcessor"; +export * from "./PerformanceMetricsTelemetryProcessor"; +export * from "./PreAggregatedMetricsTelemetryProcessor"; diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/index.js b/node_modules/applicationinsights/out/TelemetryProcessors/index.js new file mode 100644 index 0000000..2459468 --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/index.js @@ -0,0 +1,17 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./AzureRoleEnvironmentTelemetryInitializer"), exports); +__exportStar(require("./SamplingTelemetryProcessor"), exports); +__exportStar(require("./PerformanceMetricsTelemetryProcessor"), exports); +__exportStar(require("./PreAggregatedMetricsTelemetryProcessor"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/TelemetryProcessors/index.js.map b/node_modules/applicationinsights/out/TelemetryProcessors/index.js.map new file mode 100644 index 0000000..56734fd --- /dev/null +++ b/node_modules/applicationinsights/out/TelemetryProcessors/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../TelemetryProcessors/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6EAA2D;AAC3D,+DAA6C;AAC7C,yEAAuD;AACvD,2EAAyD","sourcesContent":["export * from \"./AzureRoleEnvironmentTelemetryInitializer\";\r\nexport * from \"./SamplingTelemetryProcessor\";\r\nexport * from \"./PerformanceMetricsTelemetryProcessor\";\r\nexport * from \"./PreAggregatedMetricsTelemetryProcessor\";\r\n"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/out/applicationinsights.d.ts b/node_modules/applicationinsights/out/applicationinsights.d.ts new file mode 100644 index 0000000..06dbe7f --- /dev/null +++ b/node_modules/applicationinsights/out/applicationinsights.d.ts @@ -0,0 +1,185 @@ +/// +import CorrelationContextManager = require("./AutoCollection/CorrelationContextManager"); +import QuickPulseClient = require("./Library/QuickPulseStateManager"); +import { IncomingMessage } from "http"; +import { SpanContext } from "@opentelemetry/api"; +import { IDisabledExtendedMetrics } from "./AutoCollection/NativePerformance"; +export import TelemetryClient = require("./Library/NodeClient"); +export import Contracts = require("./Declarations/Contracts"); +export import azureFunctionsTypes = require("./Library/Functions"); +export declare enum DistributedTracingModes { + /** + * Send Application Insights correlation headers + */ + AI = 0, + /** + * (Default) Send both W3C Trace Context headers and back-compatibility Application Insights headers + */ + AI_AND_W3C = 1 +} +/** +* The default client, initialized when setup was called. To initialize a different client +* with its own configuration, use `new TelemetryClient(instrumentationKey?)`. +*/ +export declare let defaultClient: TelemetryClient; +export declare let liveMetricsClient: QuickPulseClient; +/** + * Initializes the default client. Should be called after setting + * configuration options. + * + * @param setupString the Connection String or Instrumentation Key to use. Optional, if + * this is not specified, the value will be read from the environment + * variable APPLICATIONINSIGHTS_CONNECTION_STRING. + * @returns {Configuration} the configuration class to initialize + * and start the SDK. + */ +export declare function setup(setupString?: string): typeof Configuration; +/** + * Starts automatic collection of telemetry. Prior to calling start no + * telemetry will be *automatically* collected, though manual collection + * is enabled. + * @returns {ApplicationInsights} this class + */ +export declare function start(): typeof Configuration; +/** + * Returns an object that is shared across all code handling a given request. + * This can be used similarly to thread-local storage in other languages. + * Properties set on this object will be available to telemetry processors. + * + * Do not store sensitive information here. + * Custom properties set on this object can be exposed in a future SDK + * release via outgoing HTTP headers. + * This is to allow for correlating data cross-component. + * + * This method will return null if automatic dependency correlation is disabled. + * @returns A plain object for request storage or null if automatic dependency correlation is disabled. + */ +export declare function getCorrelationContext(): CorrelationContextManager.CorrelationContext; +/** + * **(Experimental!)** + * Starts a fresh context or propagates the current internal one. + */ +export declare function startOperation(context: SpanContext, name: string): CorrelationContextManager.CorrelationContext | null; +export declare function startOperation(context: azureFunctionsTypes.Context, request: azureFunctionsTypes.HttpRequest): CorrelationContextManager.CorrelationContext | null; +export declare function startOperation(context: azureFunctionsTypes.Context, name: string): CorrelationContextManager.CorrelationContext | null; +export declare function startOperation(context: IncomingMessage | azureFunctionsTypes.HttpRequest, request?: never): CorrelationContextManager.CorrelationContext | null; +/** + * Returns a function that will get the same correlation context within its + * function body as the code executing this function. + * Use this method if automatic dependency correlation is not propagating + * correctly to an asynchronous callback. + */ +export declare function wrapWithCorrelationContext(fn: T, context?: CorrelationContextManager.CorrelationContext): T; +/** + * The active configuration for global SDK behaviors, such as autocollection. + */ +export declare class Configuration { + static start: typeof start; + /** + * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context + * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing + * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included. + * Enabling W3C mode will not break existing correlation with other Application Insights instrumented + * services. Default=AI + */ + static setDistributedTracingMode(value: DistributedTracingModes): typeof Configuration; + /** + * Sets the state of console and logger tracking (enabled by default for third-party loggers only) + * @param value if true logger activity will be sent to Application Insights + * @param collectConsoleLog if true, logger autocollection will include console.log calls (default false) + * @returns {Configuration} this class + */ + static setAutoCollectConsole(value: boolean, collectConsoleLog?: boolean): typeof Configuration; + /** + * Sets the state of exception tracking (enabled by default) + * @param value if true uncaught exceptions will be sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectExceptions(value: boolean): typeof Configuration; + /** + * Sets the state of performance tracking (enabled by default) + * @param value if true performance counters will be collected every second and sent to Application Insights + * @param collectExtendedMetrics if true, extended metrics counters will be collected every minute and sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectPerformance(value: boolean, collectExtendedMetrics?: boolean | IDisabledExtendedMetrics): typeof Configuration; + /** + * Sets the state of pre aggregated metrics tracking (enabled by default) + * @param value if true pre aggregated metrics will be collected every minute and sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectPreAggregatedMetrics(value: boolean): typeof Configuration; + /** + * Sets the state of request tracking (enabled by default) + * @param value if true HeartBeat metric data will be collected every 15 mintues and sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectHeartbeat(value: boolean): typeof Configuration; + /** + * Sets the state of Web snippet injection, this config is NOT exposed in documentation after version 2.3.5 + * @deprecated, please use enableWebInstrumentation instead. + * @param value if true Web snippet will be tried to be injected in server response + * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization + * @returns {Configuration} this class + */ + static enableAutoWebSnippetInjection(value: boolean, WebSnippetConnectionString?: string): typeof Configuration; + /** + * Sets the state of Web snippet injection + * @param value if true Web snippet will be tried to be injected in server response + * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization + * @returns {Configuration} this class + */ + static enableWebInstrumentation(value: boolean, WebSnippetConnectionString?: string): typeof Configuration; + /** + * Sets the state of request tracking (enabled by default) + * @param value if true requests will be sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectRequests(value: boolean): typeof Configuration; + /** + * Sets the state of dependency tracking (enabled by default) + * @param value if true dependencies will be sent to Application Insights + * @returns {Configuration} this class + */ + static setAutoCollectDependencies(value: boolean): typeof Configuration; + /** + * Sets the state of automatic dependency correlation (enabled by default) + * @param value if true dependencies will be correlated with requests + * @param useAsyncHooks if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. + * @returns {Configuration} this class + */ + static setAutoDependencyCorrelation(value: boolean, useAsyncHooks?: boolean): typeof Configuration; + /** + * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) + * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients. + * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true). + * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. + * @param value if true events that occured while client is offline will be cached on disk + * @param resendInterval The wait interval for resending cached events. + * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. + * @returns {Configuration} this class + */ + static setUseDiskRetryCaching(value: boolean, resendInterval?: number, maxBytesOnDisk?: number): typeof Configuration; + /** + * Enables debug and warning logging for AppInsights itself. + * @param enableDebugLogging if true, enables debug logging + * @param enableWarningLogging if true, enables warning logging + * @returns {Configuration} this class + */ + static setInternalLogging(enableDebugLogging?: boolean, enableWarningLogging?: boolean): typeof Configuration; + /** + * Enable automatic incoming request tracking when using Azure Functions + * @param value if true auto collection of incoming requests will be enabled + * @returns {Configuration} this class + */ + static setAutoCollectIncomingRequestAzureFunctions(value: boolean): typeof Configuration; + /** + * Enables communication with Application Insights Live Metrics. + * @param enable if true, enables communication with the live metrics service + */ + static setSendLiveMetrics(enable?: boolean): typeof Configuration; +} +/** + * Disposes the default client and all the auto collectors so they can be reinitialized with different configuration +*/ +export declare function dispose(): void; diff --git a/node_modules/applicationinsights/out/applicationinsights.js b/node_modules/applicationinsights/out/applicationinsights.js new file mode 100644 index 0000000..9566e02 --- /dev/null +++ b/node_modules/applicationinsights/out/applicationinsights.js @@ -0,0 +1,474 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dispose = exports.Configuration = exports.wrapWithCorrelationContext = exports.startOperation = exports.getCorrelationContext = exports.start = exports.setup = exports.liveMetricsClient = exports.defaultClient = exports.DistributedTracingModes = void 0; +var CorrelationContextManager = require("./AutoCollection/CorrelationContextManager"); // Keep this first +var AutoCollectConsole = require("./AutoCollection/Console"); +var AutoCollectExceptions = require("./AutoCollection/Exceptions"); +var AutoCollectPerformance = require("./AutoCollection/Performance"); +var AutoCollecPreAggregatedMetrics = require("./AutoCollection/PreAggregatedMetrics"); +var HeartBeat = require("./AutoCollection/HeartBeat"); +var WebSnippet = require("./AutoCollection/WebSnippet"); +var AutoCollectHttpDependencies = require("./AutoCollection/HttpDependencies"); +var AutoCollectHttpRequests = require("./AutoCollection/HttpRequests"); +var CorrelationIdManager = require("./Library/CorrelationIdManager"); +var Logging = require("./Library/Logging"); +var QuickPulseClient = require("./Library/QuickPulseStateManager"); +var NativePerformance_1 = require("./AutoCollection/NativePerformance"); +var AzureFunctionsHook_1 = require("./AutoCollection/AzureFunctionsHook"); +// We export these imports so that SDK users may use these classes directly. +// They're exposed using "export import" so that types are passed along as expected +exports.TelemetryClient = require("./Library/NodeClient"); +exports.Contracts = require("./Declarations/Contracts"); +exports.azureFunctionsTypes = require("./Library/Functions"); +var DistributedTracingModes; +(function (DistributedTracingModes) { + /** + * Send Application Insights correlation headers + */ + DistributedTracingModes[DistributedTracingModes["AI"] = 0] = "AI"; + /** + * (Default) Send both W3C Trace Context headers and back-compatibility Application Insights headers + */ + DistributedTracingModes[DistributedTracingModes["AI_AND_W3C"] = 1] = "AI_AND_W3C"; +})(DistributedTracingModes = exports.DistributedTracingModes || (exports.DistributedTracingModes = {})); +// Default autocollection configuration +var defaultConfig = _getDefaultAutoCollectConfig(); +var _isConsole = defaultConfig.isConsole(); +var _isConsoleLog = defaultConfig.isConsoleLog(); +var _isExceptions = defaultConfig.isExceptions(); +var _isPerformance = defaultConfig.isPerformance(); +var _isPreAggregatedMetrics = defaultConfig.isPreAggregatedMetrics(); +var _isHeartBeat = defaultConfig.isHeartBeat(); // off by default for now +var _isRequests = defaultConfig.isRequests(); +var _isDependencies = defaultConfig.isDependencies(); +var _isDiskRetry = defaultConfig.isDiskRetry(); +var _isCorrelating = defaultConfig.isCorrelating(); +var _forceClsHooked; +var _isSendingLiveMetrics = defaultConfig.isSendingLiveMetrics(); // Off by default +var _isNativePerformance = defaultConfig.isNativePerformance(); +var _disabledExtendedMetrics; +var _isSnippetInjection = defaultConfig.isSnippetInjection(); // default to false +var _isAzureFunctions = defaultConfig.isAzureFunctions(); // default to false +function _getDefaultAutoCollectConfig() { + return { + isConsole: function () { return true; }, + isConsoleLog: function () { return false; }, + isExceptions: function () { return true; }, + isPerformance: function () { return true; }, + isPreAggregatedMetrics: function () { return true; }, + isHeartBeat: function () { return false; }, + isRequests: function () { return true; }, + isDependencies: function () { return true; }, + isDiskRetry: function () { return true; }, + isCorrelating: function () { return true; }, + isSendingLiveMetrics: function () { return false; }, + isNativePerformance: function () { return true; }, + isSnippetInjection: function () { return false; }, + isAzureFunctions: function () { return false; } + }; +} +var _diskRetryInterval = undefined; +var _diskRetryMaxBytes = undefined; +var _webSnippetConnectionString = undefined; +var _console; +var _exceptions; +var _performance; +var _preAggregatedMetrics; +var _heartbeat; +var _webSnippet; +var _nativePerformance; +var _serverRequests; +var _clientRequests; +var _azureFunctions; +var _isStarted = false; +var _performanceLiveMetrics; +/** + * Initializes the default client. Should be called after setting + * configuration options. + * + * @param setupString the Connection String or Instrumentation Key to use. Optional, if + * this is not specified, the value will be read from the environment + * variable APPLICATIONINSIGHTS_CONNECTION_STRING. + * @returns {Configuration} the configuration class to initialize + * and start the SDK. + */ +function setup(setupString) { + if (!exports.defaultClient) { + exports.defaultClient = new exports.TelemetryClient(setupString); + _initializeConfig(); + _console = new AutoCollectConsole(exports.defaultClient); + _exceptions = new AutoCollectExceptions(exports.defaultClient); + _performance = new AutoCollectPerformance(exports.defaultClient); + _preAggregatedMetrics = new AutoCollecPreAggregatedMetrics(exports.defaultClient); + _heartbeat = new HeartBeat(exports.defaultClient); + _webSnippet = new WebSnippet(exports.defaultClient); + _serverRequests = new AutoCollectHttpRequests(exports.defaultClient); + _clientRequests = new AutoCollectHttpDependencies(exports.defaultClient); + if (!_nativePerformance) { + _nativePerformance = new NativePerformance_1.AutoCollectNativePerformance(exports.defaultClient); + } + _azureFunctions = new AzureFunctionsHook_1.AzureFunctionsHook(exports.defaultClient); + } + else { + Logging.info("The default client is already setup"); + } + if (exports.defaultClient && exports.defaultClient.channel) { + exports.defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes); + } + return Configuration; +} +exports.setup = setup; +/** + * Starts automatic collection of telemetry. Prior to calling start no + * telemetry will be *automatically* collected, though manual collection + * is enabled. + * @returns {ApplicationInsights} this class + */ +function start() { + if (!!exports.defaultClient) { + _isStarted = true; + _console.enable(_isConsole, _isConsoleLog); + _exceptions.enable(_isExceptions); + _performance.enable(_isPerformance); + _preAggregatedMetrics.enable(_isPreAggregatedMetrics); + _heartbeat.enable(_isHeartBeat); + _nativePerformance.enable(_isNativePerformance, _disabledExtendedMetrics); + _serverRequests.useAutoCorrelation(_isCorrelating, _forceClsHooked); + _serverRequests.enable(_isRequests); + _clientRequests.enable(_isDependencies); + _webSnippet.enable(_isSnippetInjection, _webSnippetConnectionString); + if (exports.liveMetricsClient && _isSendingLiveMetrics) { + exports.liveMetricsClient.enable(_isSendingLiveMetrics); + } + _azureFunctions.enable(_isAzureFunctions); + } + else { + Logging.warn("Start cannot be called before setup"); + } + return Configuration; +} +exports.start = start; +function _initializeConfig() { + _isConsole = exports.defaultClient.config.enableAutoCollectExternalLoggers !== undefined ? exports.defaultClient.config.enableAutoCollectExternalLoggers : _isConsole; + _isConsoleLog = exports.defaultClient.config.enableAutoCollectConsole !== undefined ? exports.defaultClient.config.enableAutoCollectConsole : _isConsoleLog; + _isExceptions = exports.defaultClient.config.enableAutoCollectExceptions !== undefined ? exports.defaultClient.config.enableAutoCollectExceptions : _isExceptions; + _isPerformance = exports.defaultClient.config.enableAutoCollectPerformance !== undefined ? exports.defaultClient.config.enableAutoCollectPerformance : _isPerformance; + _isPreAggregatedMetrics = exports.defaultClient.config.enableAutoCollectPreAggregatedMetrics !== undefined ? exports.defaultClient.config.enableAutoCollectPreAggregatedMetrics : _isPreAggregatedMetrics; + _isHeartBeat = exports.defaultClient.config.enableAutoCollectHeartbeat !== undefined ? exports.defaultClient.config.enableAutoCollectHeartbeat : _isHeartBeat; + _isRequests = exports.defaultClient.config.enableAutoCollectRequests !== undefined ? exports.defaultClient.config.enableAutoCollectRequests : _isRequests; + _isDependencies = exports.defaultClient.config.enableAutoDependencyCorrelation !== undefined ? exports.defaultClient.config.enableAutoDependencyCorrelation : _isDependencies; + _isCorrelating = exports.defaultClient.config.enableAutoDependencyCorrelation !== undefined ? exports.defaultClient.config.enableAutoDependencyCorrelation : _isCorrelating; + _forceClsHooked = exports.defaultClient.config.enableUseAsyncHooks !== undefined ? exports.defaultClient.config.enableUseAsyncHooks : _forceClsHooked; + _isSnippetInjection = exports.defaultClient.config.enableWebInstrumentation !== undefined ? exports.defaultClient.config.enableWebInstrumentation : _isSnippetInjection; + _isSnippetInjection = exports.defaultClient.config.enableAutoWebSnippetInjection === true ? true : _isSnippetInjection; + _isAzureFunctions = exports.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions !== undefined ? exports.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions : _isAzureFunctions; + var extendedMetricsConfig = NativePerformance_1.AutoCollectNativePerformance.parseEnabled(exports.defaultClient.config.enableAutoCollectExtendedMetrics, exports.defaultClient.config); + _isNativePerformance = extendedMetricsConfig.isEnabled; + _disabledExtendedMetrics = extendedMetricsConfig.disabledMetrics; +} +/** + * Returns an object that is shared across all code handling a given request. + * This can be used similarly to thread-local storage in other languages. + * Properties set on this object will be available to telemetry processors. + * + * Do not store sensitive information here. + * Custom properties set on this object can be exposed in a future SDK + * release via outgoing HTTP headers. + * This is to allow for correlating data cross-component. + * + * This method will return null if automatic dependency correlation is disabled. + * @returns A plain object for request storage or null if automatic dependency correlation is disabled. + */ +function getCorrelationContext() { + if (_isCorrelating) { + return CorrelationContextManager.CorrelationContextManager.getCurrentContext(); + } + return null; +} +exports.getCorrelationContext = getCorrelationContext; +function startOperation(context, request) { + return CorrelationContextManager.CorrelationContextManager.startOperation(context, request); +} +exports.startOperation = startOperation; +/** + * Returns a function that will get the same correlation context within its + * function body as the code executing this function. + * Use this method if automatic dependency correlation is not propagating + * correctly to an asynchronous callback. + */ +function wrapWithCorrelationContext(fn, context) { + return CorrelationContextManager.CorrelationContextManager.wrapCallback(fn, context); +} +exports.wrapWithCorrelationContext = wrapWithCorrelationContext; +/** + * The active configuration for global SDK behaviors, such as autocollection. + */ +var Configuration = /** @class */ (function () { + function Configuration() { + } + /** + * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context + * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing + * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included. + * Enabling W3C mode will not break existing correlation with other Application Insights instrumented + * services. Default=AI + */ + Configuration.setDistributedTracingMode = function (value) { + CorrelationIdManager.w3cEnabled = value === DistributedTracingModes.AI_AND_W3C; + return Configuration; + }; + /** + * Sets the state of console and logger tracking (enabled by default for third-party loggers only) + * @param value if true logger activity will be sent to Application Insights + * @param collectConsoleLog if true, logger autocollection will include console.log calls (default false) + * @returns {Configuration} this class + */ + Configuration.setAutoCollectConsole = function (value, collectConsoleLog) { + if (collectConsoleLog === void 0) { collectConsoleLog = false; } + _isConsole = value; + _isConsoleLog = collectConsoleLog; + if (_isStarted) { + _console.enable(value, collectConsoleLog); + } + return Configuration; + }; + /** + * Sets the state of exception tracking (enabled by default) + * @param value if true uncaught exceptions will be sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectExceptions = function (value) { + _isExceptions = value; + if (_isStarted) { + _exceptions.enable(value); + } + return Configuration; + }; + /** + * Sets the state of performance tracking (enabled by default) + * @param value if true performance counters will be collected every second and sent to Application Insights + * @param collectExtendedMetrics if true, extended metrics counters will be collected every minute and sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectPerformance = function (value, collectExtendedMetrics) { + if (collectExtendedMetrics === void 0) { collectExtendedMetrics = true; } + _isPerformance = value; + var extendedMetricsConfig = NativePerformance_1.AutoCollectNativePerformance.parseEnabled(collectExtendedMetrics, exports.defaultClient.config); + _isNativePerformance = extendedMetricsConfig.isEnabled; + _disabledExtendedMetrics = extendedMetricsConfig.disabledMetrics; + if (_isStarted) { + _performance.enable(value); + _nativePerformance.enable(extendedMetricsConfig.isEnabled, extendedMetricsConfig.disabledMetrics); + } + return Configuration; + }; + /** + * Sets the state of pre aggregated metrics tracking (enabled by default) + * @param value if true pre aggregated metrics will be collected every minute and sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectPreAggregatedMetrics = function (value) { + _isPreAggregatedMetrics = value; + if (_isStarted) { + _preAggregatedMetrics.enable(value); + } + return Configuration; + }; + /** + * Sets the state of request tracking (enabled by default) + * @param value if true HeartBeat metric data will be collected every 15 mintues and sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectHeartbeat = function (value) { + _isHeartBeat = value; + if (_isStarted) { + _heartbeat.enable(value); + } + return Configuration; + }; + /** + * Sets the state of Web snippet injection, this config is NOT exposed in documentation after version 2.3.5 + * @deprecated, please use enableWebInstrumentation instead. + * @param value if true Web snippet will be tried to be injected in server response + * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization + * @returns {Configuration} this class + */ + Configuration.enableAutoWebSnippetInjection = function (value, WebSnippetConnectionString) { + _isSnippetInjection = value; + _webSnippetConnectionString = WebSnippetConnectionString; + if (_isStarted) { + _webSnippet.enable(value, _webSnippetConnectionString); + } + return Configuration; + }; + /** + * Sets the state of Web snippet injection + * @param value if true Web snippet will be tried to be injected in server response + * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization + * @returns {Configuration} this class + */ + Configuration.enableWebInstrumentation = function (value, WebSnippetConnectionString) { + _isSnippetInjection = value; + _webSnippetConnectionString = WebSnippetConnectionString; + if (_isStarted) { + _webSnippet.enable(value, _webSnippetConnectionString); + } + return Configuration; + }; + /** + * Sets the state of request tracking (enabled by default) + * @param value if true requests will be sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectRequests = function (value) { + _isRequests = value; + if (_isStarted) { + _serverRequests.enable(value); + } + return Configuration; + }; + /** + * Sets the state of dependency tracking (enabled by default) + * @param value if true dependencies will be sent to Application Insights + * @returns {Configuration} this class + */ + Configuration.setAutoCollectDependencies = function (value) { + _isDependencies = value; + if (_isStarted) { + _clientRequests.enable(value); + } + return Configuration; + }; + /** + * Sets the state of automatic dependency correlation (enabled by default) + * @param value if true dependencies will be correlated with requests + * @param useAsyncHooks if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js. + * @returns {Configuration} this class + */ + Configuration.setAutoDependencyCorrelation = function (value, useAsyncHooks) { + _isCorrelating = value; + _forceClsHooked = useAsyncHooks; + if (_isStarted) { + _serverRequests.useAutoCorrelation(value, useAsyncHooks); + } + return Configuration; + }; + /** + * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default) + * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients. + * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true). + * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible. + * @param value if true events that occured while client is offline will be cached on disk + * @param resendInterval The wait interval for resending cached events. + * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled. + * @returns {Configuration} this class + */ + Configuration.setUseDiskRetryCaching = function (value, resendInterval, maxBytesOnDisk) { + _isDiskRetry = value; + _diskRetryInterval = resendInterval; + _diskRetryMaxBytes = maxBytesOnDisk; + if (exports.defaultClient && exports.defaultClient.channel) { + exports.defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes); + } + return Configuration; + }; + /** + * Enables debug and warning logging for AppInsights itself. + * @param enableDebugLogging if true, enables debug logging + * @param enableWarningLogging if true, enables warning logging + * @returns {Configuration} this class + */ + Configuration.setInternalLogging = function (enableDebugLogging, enableWarningLogging) { + if (enableDebugLogging === void 0) { enableDebugLogging = false; } + if (enableWarningLogging === void 0) { enableWarningLogging = true; } + Logging.enableDebug = enableDebugLogging; + Logging.disableWarnings = !enableWarningLogging; + return Configuration; + }; + /** + * Enable automatic incoming request tracking when using Azure Functions + * @param value if true auto collection of incoming requests will be enabled + * @returns {Configuration} this class + */ + Configuration.setAutoCollectIncomingRequestAzureFunctions = function (value) { + _isAzureFunctions = value; + if (_isStarted) { + _azureFunctions.enable(value); + } + return Configuration; + }; + /** + * Enables communication with Application Insights Live Metrics. + * @param enable if true, enables communication with the live metrics service + */ + Configuration.setSendLiveMetrics = function (enable) { + if (enable === void 0) { enable = false; } + if (!exports.defaultClient) { + // Need a defaultClient so that we can add the QPS telemetry processor to it + Logging.warn("Live metrics client cannot be setup without the default client"); + return Configuration; + } + if (!exports.liveMetricsClient && enable) { + // No qps client exists. Create one and prepare it to be enabled at .start() + exports.liveMetricsClient = new QuickPulseClient(exports.defaultClient.config, exports.defaultClient.context, exports.defaultClient.getAuthorizationHandler); + _performanceLiveMetrics = new AutoCollectPerformance(exports.liveMetricsClient, 1000, true); + exports.liveMetricsClient.addCollector(_performanceLiveMetrics); + exports.defaultClient.quickPulseClient = exports.liveMetricsClient; // Need this so we can forward all manual tracks to live metrics via PerformanceMetricsTelemetryProcessor + } + else if (exports.liveMetricsClient) { + // qps client already exists; enable/disable it + exports.liveMetricsClient.enable(enable); + } + _isSendingLiveMetrics = enable; + return Configuration; + }; + // Convenience shortcut to ApplicationInsights.start + Configuration.start = start; + return Configuration; +}()); +exports.Configuration = Configuration; +/** + * Disposes the default client and all the auto collectors so they can be reinitialized with different configuration +*/ +function dispose() { + CorrelationIdManager.w3cEnabled = true; // reset to default + exports.defaultClient = null; + _isStarted = false; + if (_console) { + _console.dispose(); + } + if (_exceptions) { + _exceptions.dispose(); + } + if (_performance) { + _performance.dispose(); + } + if (_preAggregatedMetrics) { + _preAggregatedMetrics.dispose(); + } + if (_heartbeat) { + _heartbeat.dispose(); + } + if (_webSnippet) { + _webSnippet.dispose(); + } + if (_nativePerformance) { + _nativePerformance.dispose(); + } + if (_serverRequests) { + _serverRequests.dispose(); + } + if (_clientRequests) { + _clientRequests.dispose(); + } + if (exports.liveMetricsClient) { + exports.liveMetricsClient.enable(false); + _isSendingLiveMetrics = false; + exports.liveMetricsClient = undefined; + } + if (_azureFunctions) { + _azureFunctions.dispose(); + } +} +exports.dispose = dispose; +//# sourceMappingURL=applicationinsights.js.map \ No newline at end of file diff --git a/node_modules/applicationinsights/out/applicationinsights.js.map b/node_modules/applicationinsights/out/applicationinsights.js.map new file mode 100644 index 0000000..7b6081e --- /dev/null +++ b/node_modules/applicationinsights/out/applicationinsights.js.map @@ -0,0 +1 @@ +{"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../applicationinsights.ts"],"names":[],"mappings":";;;AAAA,s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,OAAO,EAAE,CAAC;KAC7B;IACD,IAAI,eAAe,EAAE;QACjB,eAAe,CAAC,OAAO,EAAE,CAAC;KAC7B;IACD,IAAI,yBAAiB,EAAE;QACnB,yBAAiB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChC,qBAAqB,GAAG,KAAK,CAAC;QAC9B,yBAAiB,GAAG,SAAS,CAAC;KACjC;IACD,IAAI,eAAe,EAAE;QACjB,eAAe,CAAC,OAAO,EAAE,CAAC;KAC7B;AACL,CAAC;AAvCD,0BAuCC","sourcesContent":["import CorrelationContextManager = require(\"./AutoCollection/CorrelationContextManager\"); // Keep this first\r\nimport AutoCollectConsole = require(\"./AutoCollection/Console\");\r\nimport AutoCollectExceptions = require(\"./AutoCollection/Exceptions\");\r\nimport AutoCollectPerformance = require(\"./AutoCollection/Performance\");\r\nimport AutoCollecPreAggregatedMetrics = require(\"./AutoCollection/PreAggregatedMetrics\");\r\nimport HeartBeat = require(\"./AutoCollection/HeartBeat\");\r\nimport WebSnippet = require(\"./AutoCollection/WebSnippet\");\r\nimport AutoCollectHttpDependencies = require(\"./AutoCollection/HttpDependencies\");\r\nimport AutoCollectHttpRequests = require(\"./AutoCollection/HttpRequests\");\r\nimport CorrelationIdManager = require(\"./Library/CorrelationIdManager\");\r\nimport Logging = require(\"./Library/Logging\");\r\nimport QuickPulseClient = require(\"./Library/QuickPulseStateManager\");\r\nimport { IncomingMessage } from \"http\";\r\nimport { SpanContext } from \"@opentelemetry/api\";\r\nimport { AutoCollectNativePerformance, IDisabledExtendedMetrics } from \"./AutoCollection/NativePerformance\";\r\nimport { AzureFunctionsHook } from \"./AutoCollection/AzureFunctionsHook\";\r\n\r\n// We export these imports so that SDK users may use these classes directly.\r\n// They're exposed using \"export import\" so that types are passed along as expected\r\nexport import TelemetryClient = require(\"./Library/NodeClient\");\r\nexport import Contracts = require(\"./Declarations/Contracts\");\r\nexport import azureFunctionsTypes = require(\"./Library/Functions\");\r\n\r\nexport enum DistributedTracingModes {\r\n /**\r\n * Send Application Insights correlation headers\r\n */\r\n\r\n AI = 0,\r\n\r\n /**\r\n * (Default) Send both W3C Trace Context headers and back-compatibility Application Insights headers\r\n */\r\n AI_AND_W3C\r\n}\r\n\r\n// Default autocollection configuration\r\nlet defaultConfig = _getDefaultAutoCollectConfig();\r\nlet _isConsole = defaultConfig.isConsole();\r\nlet _isConsoleLog = defaultConfig.isConsoleLog();\r\nlet _isExceptions = defaultConfig.isExceptions();\r\nlet _isPerformance = defaultConfig.isPerformance();\r\nlet _isPreAggregatedMetrics = defaultConfig.isPreAggregatedMetrics();\r\nlet _isHeartBeat = defaultConfig.isHeartBeat(); // off by default for now\r\nlet _isRequests = defaultConfig.isRequests();\r\nlet _isDependencies = defaultConfig.isDependencies();\r\nlet _isDiskRetry = defaultConfig.isDiskRetry();\r\nlet _isCorrelating = defaultConfig.isCorrelating();\r\nlet _forceClsHooked: boolean;\r\nlet _isSendingLiveMetrics = defaultConfig.isSendingLiveMetrics(); // Off by default\r\nlet _isNativePerformance = defaultConfig.isNativePerformance();\r\nlet _disabledExtendedMetrics: IDisabledExtendedMetrics;\r\nlet _isSnippetInjection = defaultConfig.isSnippetInjection(); // default to false\r\nlet _isAzureFunctions = defaultConfig.isAzureFunctions(); // default to false\r\n\r\nfunction _getDefaultAutoCollectConfig() {\r\n return {\r\n isConsole: () => true,\r\n isConsoleLog: () => false,\r\n isExceptions: () => true,\r\n isPerformance: () => true,\r\n isPreAggregatedMetrics: () => true,\r\n isHeartBeat: () => false, // off by default for now\r\n isRequests: () => true,\r\n isDependencies: () => true,\r\n isDiskRetry: () => true,\r\n isCorrelating: () => true,\r\n isSendingLiveMetrics: () => false, // Off by default\r\n isNativePerformance: () => true,\r\n isSnippetInjection: () => false,\r\n isAzureFunctions: () => false\r\n }\r\n}\r\n\r\nlet _diskRetryInterval: number = undefined;\r\nlet _diskRetryMaxBytes: number = undefined;\r\nlet _webSnippetConnectionString: string = undefined;\r\n\r\nlet _console: AutoCollectConsole;\r\nlet _exceptions: AutoCollectExceptions;\r\nlet _performance: AutoCollectPerformance;\r\nlet _preAggregatedMetrics: AutoCollecPreAggregatedMetrics;\r\nlet _heartbeat: HeartBeat;\r\nlet _webSnippet: WebSnippet;\r\nlet _nativePerformance: AutoCollectNativePerformance;\r\nlet _serverRequests: AutoCollectHttpRequests;\r\nlet _clientRequests: AutoCollectHttpDependencies;\r\nlet _azureFunctions: AzureFunctionsHook;\r\n\r\nlet _isStarted = false;\r\n\r\n/**\r\n* The default client, initialized when setup was called. To initialize a different client\r\n* with its own configuration, use `new TelemetryClient(instrumentationKey?)`.\r\n*/\r\nexport let defaultClient: TelemetryClient;\r\nexport let liveMetricsClient: QuickPulseClient;\r\nlet _performanceLiveMetrics: AutoCollectPerformance;\r\n\r\n/**\r\n * Initializes the default client. Should be called after setting\r\n * configuration options.\r\n *\r\n * @param setupString the Connection String or Instrumentation Key to use. Optional, if\r\n * this is not specified, the value will be read from the environment\r\n * variable APPLICATIONINSIGHTS_CONNECTION_STRING.\r\n * @returns {Configuration} the configuration class to initialize\r\n * and start the SDK.\r\n */\r\nexport function setup(setupString?: string) {\r\n if (!defaultClient) {\r\n defaultClient = new TelemetryClient(setupString);\r\n _initializeConfig();\r\n _console = new AutoCollectConsole(defaultClient);\r\n _exceptions = new AutoCollectExceptions(defaultClient);\r\n _performance = new AutoCollectPerformance(defaultClient);\r\n _preAggregatedMetrics = new AutoCollecPreAggregatedMetrics(defaultClient);\r\n _heartbeat = new HeartBeat(defaultClient);\r\n _webSnippet = new WebSnippet(defaultClient);\r\n _serverRequests = new AutoCollectHttpRequests(defaultClient);\r\n _clientRequests = new AutoCollectHttpDependencies(defaultClient);\r\n if (!_nativePerformance) {\r\n _nativePerformance = new AutoCollectNativePerformance(defaultClient);\r\n }\r\n _azureFunctions = new AzureFunctionsHook(defaultClient);\r\n } else {\r\n Logging.info(\"The default client is already setup\");\r\n }\r\n\r\n if (defaultClient && defaultClient.channel) {\r\n defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes);\r\n }\r\n\r\n return Configuration;\r\n}\r\n\r\n/**\r\n * Starts automatic collection of telemetry. Prior to calling start no\r\n * telemetry will be *automatically* collected, though manual collection\r\n * is enabled.\r\n * @returns {ApplicationInsights} this class\r\n */\r\nexport function start() {\r\n if (!!defaultClient) {\r\n _isStarted = true;\r\n _console.enable(_isConsole, _isConsoleLog);\r\n _exceptions.enable(_isExceptions);\r\n _performance.enable(_isPerformance);\r\n _preAggregatedMetrics.enable(_isPreAggregatedMetrics);\r\n _heartbeat.enable(_isHeartBeat);\r\n _nativePerformance.enable(_isNativePerformance, _disabledExtendedMetrics);\r\n _serverRequests.useAutoCorrelation(_isCorrelating, _forceClsHooked);\r\n _serverRequests.enable(_isRequests);\r\n _clientRequests.enable(_isDependencies);\r\n _webSnippet.enable(_isSnippetInjection, _webSnippetConnectionString);\r\n if (liveMetricsClient && _isSendingLiveMetrics) {\r\n liveMetricsClient.enable(_isSendingLiveMetrics);\r\n }\r\n _azureFunctions.enable(_isAzureFunctions);\r\n } else {\r\n Logging.warn(\"Start cannot be called before setup\");\r\n }\r\n\r\n return Configuration;\r\n}\r\n\r\nfunction _initializeConfig() {\r\n _isConsole = defaultClient.config.enableAutoCollectExternalLoggers !== undefined ? defaultClient.config.enableAutoCollectExternalLoggers : _isConsole;\r\n _isConsoleLog = defaultClient.config.enableAutoCollectConsole !== undefined ? defaultClient.config.enableAutoCollectConsole : _isConsoleLog;\r\n _isExceptions = defaultClient.config.enableAutoCollectExceptions !== undefined ? defaultClient.config.enableAutoCollectExceptions : _isExceptions;\r\n _isPerformance = defaultClient.config.enableAutoCollectPerformance !== undefined ? defaultClient.config.enableAutoCollectPerformance : _isPerformance;\r\n _isPreAggregatedMetrics = defaultClient.config.enableAutoCollectPreAggregatedMetrics !== undefined ? defaultClient.config.enableAutoCollectPreAggregatedMetrics : _isPreAggregatedMetrics;\r\n _isHeartBeat = defaultClient.config.enableAutoCollectHeartbeat !== undefined ? defaultClient.config.enableAutoCollectHeartbeat : _isHeartBeat;\r\n _isRequests = defaultClient.config.enableAutoCollectRequests !== undefined ? defaultClient.config.enableAutoCollectRequests : _isRequests;\r\n _isDependencies = defaultClient.config.enableAutoDependencyCorrelation !== undefined ? defaultClient.config.enableAutoDependencyCorrelation : _isDependencies;\r\n _isCorrelating = defaultClient.config.enableAutoDependencyCorrelation !== undefined ? defaultClient.config.enableAutoDependencyCorrelation : _isCorrelating;\r\n _forceClsHooked = defaultClient.config.enableUseAsyncHooks !== undefined ? defaultClient.config.enableUseAsyncHooks : _forceClsHooked;\r\n _isSnippetInjection = defaultClient.config.enableWebInstrumentation !== undefined ? defaultClient.config.enableWebInstrumentation : _isSnippetInjection;\r\n _isSnippetInjection = defaultClient.config.enableAutoWebSnippetInjection === true ? true : _isSnippetInjection;\r\n _isAzureFunctions = defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions !== undefined ? defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions : _isAzureFunctions;\r\n const extendedMetricsConfig = AutoCollectNativePerformance.parseEnabled(defaultClient.config.enableAutoCollectExtendedMetrics, defaultClient.config);\r\n _isNativePerformance = extendedMetricsConfig.isEnabled;\r\n _disabledExtendedMetrics = extendedMetricsConfig.disabledMetrics;\r\n\r\n}\r\n\r\n/**\r\n * Returns an object that is shared across all code handling a given request.\r\n * This can be used similarly to thread-local storage in other languages.\r\n * Properties set on this object will be available to telemetry processors.\r\n *\r\n * Do not store sensitive information here.\r\n * Custom properties set on this object can be exposed in a future SDK\r\n * release via outgoing HTTP headers.\r\n * This is to allow for correlating data cross-component.\r\n *\r\n * This method will return null if automatic dependency correlation is disabled.\r\n * @returns A plain object for request storage or null if automatic dependency correlation is disabled.\r\n */\r\nexport function getCorrelationContext(): CorrelationContextManager.CorrelationContext {\r\n if (_isCorrelating) {\r\n return CorrelationContextManager.CorrelationContextManager.getCurrentContext();\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * **(Experimental!)**\r\n * Starts a fresh context or propagates the current internal one.\r\n */\r\nexport function startOperation(context: SpanContext, name: string): CorrelationContextManager.CorrelationContext | null;\r\nexport function startOperation(context: azureFunctionsTypes.Context, request: azureFunctionsTypes.HttpRequest): CorrelationContextManager.CorrelationContext | null;\r\nexport function startOperation(context: azureFunctionsTypes.Context, name: string): CorrelationContextManager.CorrelationContext | null;\r\nexport function startOperation(context: IncomingMessage | azureFunctionsTypes.HttpRequest, request?: never): CorrelationContextManager.CorrelationContext | null;\r\nexport function startOperation(context: azureFunctionsTypes.Context | (IncomingMessage | azureFunctionsTypes.HttpRequest) | (SpanContext), request?: azureFunctionsTypes.HttpRequest | string): CorrelationContextManager.CorrelationContext | null {\r\n return CorrelationContextManager.CorrelationContextManager.startOperation(context, request);\r\n}\r\n\r\n/**\r\n * Returns a function that will get the same correlation context within its\r\n * function body as the code executing this function.\r\n * Use this method if automatic dependency correlation is not propagating\r\n * correctly to an asynchronous callback.\r\n */\r\nexport function wrapWithCorrelationContext(fn: T, context?: CorrelationContextManager.CorrelationContext): T {\r\n return CorrelationContextManager.CorrelationContextManager.wrapCallback(fn, context);\r\n}\r\n\r\n/**\r\n * The active configuration for global SDK behaviors, such as autocollection.\r\n */\r\nexport class Configuration {\r\n // Convenience shortcut to ApplicationInsights.start\r\n public static start = start;\r\n\r\n /**\r\n * Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context\r\n * headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing\r\n * requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included.\r\n * Enabling W3C mode will not break existing correlation with other Application Insights instrumented\r\n * services. Default=AI\r\n */\r\n public static setDistributedTracingMode(value: DistributedTracingModes) {\r\n CorrelationIdManager.w3cEnabled = value === DistributedTracingModes.AI_AND_W3C;\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of console and logger tracking (enabled by default for third-party loggers only)\r\n * @param value if true logger activity will be sent to Application Insights\r\n * @param collectConsoleLog if true, logger autocollection will include console.log calls (default false)\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectConsole(value: boolean, collectConsoleLog: boolean = false) {\r\n _isConsole = value;\r\n _isConsoleLog = collectConsoleLog;\r\n if (_isStarted) {\r\n _console.enable(value, collectConsoleLog);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of exception tracking (enabled by default)\r\n * @param value if true uncaught exceptions will be sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectExceptions(value: boolean) {\r\n _isExceptions = value;\r\n if (_isStarted) {\r\n _exceptions.enable(value);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of performance tracking (enabled by default)\r\n * @param value if true performance counters will be collected every second and sent to Application Insights\r\n * @param collectExtendedMetrics if true, extended metrics counters will be collected every minute and sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectPerformance(value: boolean, collectExtendedMetrics: boolean | IDisabledExtendedMetrics = true) {\r\n _isPerformance = value;\r\n const extendedMetricsConfig = AutoCollectNativePerformance.parseEnabled(collectExtendedMetrics, defaultClient.config);\r\n _isNativePerformance = extendedMetricsConfig.isEnabled;\r\n _disabledExtendedMetrics = extendedMetricsConfig.disabledMetrics;\r\n if (_isStarted) {\r\n _performance.enable(value);\r\n _nativePerformance.enable(extendedMetricsConfig.isEnabled, extendedMetricsConfig.disabledMetrics);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of pre aggregated metrics tracking (enabled by default)\r\n * @param value if true pre aggregated metrics will be collected every minute and sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectPreAggregatedMetrics(value: boolean) {\r\n _isPreAggregatedMetrics = value;\r\n if (_isStarted) {\r\n _preAggregatedMetrics.enable(value);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of request tracking (enabled by default)\r\n * @param value if true HeartBeat metric data will be collected every 15 mintues and sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectHeartbeat(value: boolean) {\r\n _isHeartBeat = value;\r\n if (_isStarted) {\r\n _heartbeat.enable(value);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of Web snippet injection, this config is NOT exposed in documentation after version 2.3.5\r\n * @deprecated, please use enableWebInstrumentation instead.\r\n * @param value if true Web snippet will be tried to be injected in server response\r\n * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization\r\n * @returns {Configuration} this class\r\n */\r\n public static enableAutoWebSnippetInjection(value: boolean, WebSnippetConnectionString?: string) {\r\n _isSnippetInjection = value;\r\n _webSnippetConnectionString = WebSnippetConnectionString;\r\n if (_isStarted) {\r\n _webSnippet.enable(value, _webSnippetConnectionString);\r\n }\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of Web snippet injection\r\n * @param value if true Web snippet will be tried to be injected in server response\r\n * @param WebSnippetConnectionString if provided, web snippet injection will use this ConnectionString. Default to use the connectionString in Node.js app initialization\r\n * @returns {Configuration} this class\r\n */\r\n public static enableWebInstrumentation(value: boolean, WebSnippetConnectionString?: string) {\r\n _isSnippetInjection = value;\r\n _webSnippetConnectionString = WebSnippetConnectionString;\r\n if (_isStarted) {\r\n _webSnippet.enable(value, _webSnippetConnectionString);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of request tracking (enabled by default)\r\n * @param value if true requests will be sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectRequests(value: boolean) {\r\n _isRequests = value;\r\n if (_isStarted) {\r\n _serverRequests.enable(value);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of dependency tracking (enabled by default)\r\n * @param value if true dependencies will be sent to Application Insights\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectDependencies(value: boolean) {\r\n _isDependencies = value;\r\n if (_isStarted) {\r\n _clientRequests.enable(value);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Sets the state of automatic dependency correlation (enabled by default)\r\n * @param value if true dependencies will be correlated with requests\r\n * @param useAsyncHooks if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js.\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoDependencyCorrelation(value: boolean, useAsyncHooks?: boolean) {\r\n _isCorrelating = value;\r\n _forceClsHooked = useAsyncHooks;\r\n if (_isStarted) {\r\n _serverRequests.useAutoCorrelation(value, useAsyncHooks);\r\n }\r\n\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default)\r\n * Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients.\r\n * For enable for additional clients, use client.channel.setUseDiskRetryCaching(true).\r\n * These cached events are stored in your system or user's temporary directory and access restricted to your user when possible.\r\n * @param value if true events that occured while client is offline will be cached on disk\r\n * @param resendInterval The wait interval for resending cached events.\r\n * @param maxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled.\r\n * @returns {Configuration} this class\r\n */\r\n public static setUseDiskRetryCaching(value: boolean, resendInterval?: number, maxBytesOnDisk?: number) {\r\n _isDiskRetry = value;\r\n _diskRetryInterval = resendInterval;\r\n _diskRetryMaxBytes = maxBytesOnDisk;\r\n if (defaultClient && defaultClient.channel) {\r\n defaultClient.channel.setUseDiskRetryCaching(_isDiskRetry, _diskRetryInterval, _diskRetryMaxBytes);\r\n }\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Enables debug and warning logging for AppInsights itself.\r\n * @param enableDebugLogging if true, enables debug logging\r\n * @param enableWarningLogging if true, enables warning logging\r\n * @returns {Configuration} this class\r\n */\r\n public static setInternalLogging(enableDebugLogging = false, enableWarningLogging = true) {\r\n Logging.enableDebug = enableDebugLogging;\r\n Logging.disableWarnings = !enableWarningLogging;\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Enable automatic incoming request tracking when using Azure Functions\r\n * @param value if true auto collection of incoming requests will be enabled\r\n * @returns {Configuration} this class\r\n */\r\n public static setAutoCollectIncomingRequestAzureFunctions(value: boolean) {\r\n _isAzureFunctions = value;\r\n if (_isStarted) {\r\n _azureFunctions.enable(value);\r\n }\r\n return Configuration;\r\n }\r\n\r\n /**\r\n * Enables communication with Application Insights Live Metrics.\r\n * @param enable if true, enables communication with the live metrics service\r\n */\r\n public static setSendLiveMetrics(enable = false) {\r\n if (!defaultClient) {\r\n // Need a defaultClient so that we can add the QPS telemetry processor to it\r\n Logging.warn(\"Live metrics client cannot be setup without the default client\");\r\n return Configuration;\r\n }\r\n\r\n if (!liveMetricsClient && enable) {\r\n // No qps client exists. Create one and prepare it to be enabled at .start()\r\n liveMetricsClient = new QuickPulseClient(defaultClient.config, defaultClient.context, defaultClient.getAuthorizationHandler);\r\n _performanceLiveMetrics = new AutoCollectPerformance(liveMetricsClient as any, 1000, true);\r\n liveMetricsClient.addCollector(_performanceLiveMetrics);\r\n defaultClient.quickPulseClient = liveMetricsClient; // Need this so we can forward all manual tracks to live metrics via PerformanceMetricsTelemetryProcessor\r\n } else if (liveMetricsClient) {\r\n // qps client already exists; enable/disable it\r\n liveMetricsClient.enable(enable);\r\n }\r\n _isSendingLiveMetrics = enable;\r\n return Configuration;\r\n }\r\n}\r\n\r\n/**\r\n * Disposes the default client and all the auto collectors so they can be reinitialized with different configuration\r\n*/\r\nexport function dispose() {\r\n CorrelationIdManager.w3cEnabled = true; // reset to default\r\n defaultClient = null;\r\n _isStarted = false;\r\n if (_console) {\r\n _console.dispose();\r\n }\r\n if (_exceptions) {\r\n _exceptions.dispose();\r\n }\r\n if (_performance) {\r\n _performance.dispose();\r\n }\r\n if (_preAggregatedMetrics) {\r\n _preAggregatedMetrics.dispose();\r\n }\r\n if (_heartbeat) {\r\n _heartbeat.dispose();\r\n }\r\n if (_webSnippet) {\r\n _webSnippet.dispose();\r\n }\r\n if (_nativePerformance) {\r\n _nativePerformance.dispose();\r\n }\r\n if (_serverRequests) {\r\n _serverRequests.dispose();\r\n }\r\n if (_clientRequests) {\r\n _clientRequests.dispose();\r\n }\r\n if (liveMetricsClient) {\r\n liveMetricsClient.enable(false);\r\n _isSendingLiveMetrics = false;\r\n liveMetricsClient = undefined;\r\n }\r\n if (_azureFunctions) {\r\n _azureFunctions.dispose();\r\n }\r\n}"]} \ No newline at end of file diff --git a/node_modules/applicationinsights/package.json b/node_modules/applicationinsights/package.json new file mode 100644 index 0000000..26fb142 --- /dev/null +++ b/node_modules/applicationinsights/package.json @@ -0,0 +1,89 @@ +{ + "name": "applicationinsights", + "author": "Microsoft Application Insights Team", + "license": "MIT", + "bugs": "https://github.com/microsoft/ApplicationInsights-node.js/issues", + "version": "2.5.0", + "description": "Microsoft Application Insights module for Node.js", + "repository": { + "type": "git", + "url": "https://github.com/microsoft/ApplicationInsights-node.js" + }, + "main": "./out/applicationinsights.js", + "types": "./out/applicationinsights.d.ts", + "keywords": [ + "exception monitoring", + "request monitoring", + "performance monitoring", + "application insights", + "microsoft", + "azure", + "cloud", + "tracing", + "telemetry", + "analytics", + "apm" + ], + "scripts": { + "clean": "rm -rf ./out && rm -rf ./node_modules", + "build": "npm run build:deps && npm run build:compile", + "build:deps": "npm update --dev", + "build:compile": "tsc --project ./tsconfig.json", + "prepare": "npm run build:compile", + "prepublishOnly": "npm run build", + "lint": "eslint ./ --fix", + "pretest": "npm run build", + "test": "npm run test:ts && npm run test:js", + "test:debug": "mocha ./out/Tests --inspect-brk --recursive --no-exit", + "test:ts": "mocha ./out/Tests --recursive --exit", + "test:js": "mocha ./Tests/js --recursive --exit", + "functionaltest": "npm run build && npm pack && node --use_strict ./Tests/FunctionalTests/RunFunctionalTests.js", + "backcompattest": "npm run build && npm pack && node --use_strict ./Tests/BackCompatibility/RunBackCompatTests.js" + }, + "engines": { + "node": ">=8.0.0" + }, + "devDependencies": { + "@azure/functions": "^3.5.0", + "@types/cls-hooked": "^4.3.3", + "@types/long": "^4.0.2", + "@types/mocha": "^7.0.2", + "@types/node": "^8.0.0", + "@types/sinon": "2.1.2", + "@typescript-eslint/eslint-plugin": "^5.11.0", + "@typescript-eslint/parser": "^5.11.0", + "applicationinsights-native-metrics": "0.0.7", + "eslint": "^7.29.0", + "eslint-config-standard": "^16.0.3", + "eslint-plugin-import": "^2.23.4", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^5.1.0", + "eslint-plugin-security": "^1.4.0", + "mocha": "^10.2.0", + "nock": "^11.9.1", + "node-mocks-http": "1.2.3", + "sinon": "1.17.6", + "typescript": "4.1.2" + }, + "dependencies": { + "@azure/core-auth": "^1.4.0", + "@azure/core-rest-pipeline": "^1.10.0", + "@microsoft/applicationinsights-web-snippet": "^1.0.1", + "@opentelemetry/api": "^1.0.4", + "@opentelemetry/core": "^1.0.1", + "@opentelemetry/sdk-trace-base": "^1.0.1", + "@opentelemetry/semantic-conventions": "^1.0.1", + "cls-hooked": "^4.2.2", + "continuation-local-storage": "^3.2.1", + "diagnostic-channel": "1.1.0", + "diagnostic-channel-publishers": "1.0.5" + }, + "peerDependencies": { + "applicationinsights-native-metrics": "*" + }, + "peerDependenciesMeta": { + "applicationinsights-native-metrics": { + "optional": true + } + } +} diff --git a/node_modules/applicationinsights/policheck-exclusions.xml b/node_modules/applicationinsights/policheck-exclusions.xml new file mode 100644 index 0000000..0da3e2b --- /dev/null +++ b/node_modules/applicationinsights/policheck-exclusions.xml @@ -0,0 +1,11 @@ + + + + GENERATED + + + + + + + \ No newline at end of file diff --git a/node_modules/applicationinsights/types/@azure_functions-core/index.d.ts b/node_modules/applicationinsights/types/@azure_functions-core/index.d.ts new file mode 100644 index 0000000..5177046 --- /dev/null +++ b/node_modules/applicationinsights/types/@azure_functions-core/index.d.ts @@ -0,0 +1,515 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT License. + +// Copied from https://github.com/Azure/azure-functions-nodejs-worker/blob/v3.x/types-core/index.d.ts + +/** + * This module is shipped as a built-in part of the Azure Functions Node.js worker and is available at runtime + */ +declare module '@azure/functions-core' { + /** + * The version of the Node.js worker + */ + const version: string; + + /** + * The version of the Functions Host + */ + const hostVersion: string; + + /** + * Register a function + * This is a preview feature and requires the feature flag `EnableWorkerIndexing` to be set in the app setting `AzureWebJobsFeatureFlags` + */ + function registerFunction(metadata: FunctionMetadata, callback: FunctionCallback): Disposable; + + /** + * A slimmed down version of `RpcFunctionMetadata` that includes the minimum amount of information needed to register a function + * NOTE: All properties on this object need to be deterministic to support the multiple worker scenario. More info here: https://github.com/Azure/azure-functions-nodejs-worker/issues/638 + */ + interface FunctionMetadata { + /** + * The function name, used for display and tracking purposes + * Must be unique within the app + */ + name: string; + + /** + * The function id, used for tracking purposes + * Must be unique within the app + * If not specified, the function name will be used + */ + functionId?: string; + + /** + * A dictionary of binding name to binding info + */ + bindings: { [name: string]: RpcBindingInfo }; + } + + /** + * Register a hook to interact with the lifecycle of Azure Functions. + * Hooks are executed in the order they were registered and will block execution if they throw an error + */ + function registerHook(hookName: 'preInvocation', callback: PreInvocationCallback): Disposable; + function registerHook(hookName: 'postInvocation', callback: PostInvocationCallback): Disposable; + function registerHook(hookName: 'appStart', callback: AppStartCallback): Disposable; + function registerHook(hookName: 'appTerminate', callback: AppTerminateCallback): Disposable; + function registerHook(hookName: string, callback: HookCallback): Disposable; + + type HookCallback = (context: HookContext) => void | Promise; + type PreInvocationCallback = (context: PreInvocationContext) => void | Promise; + type PostInvocationCallback = (context: PostInvocationContext) => void | Promise; + type AppStartCallback = (context: AppStartContext) => void | Promise; + type AppTerminateCallback = (context: AppTerminateContext) => void | Promise; + + type HookData = { [key: string]: any }; + + /** + * Base interface for all hook context objects + */ + interface HookContext { + /** + * The recommended place to share data between hooks in the same scope (app-level vs invocation-level) + * This object is readonly. You may modify it, but attempting to overwrite it will throw an error + */ + readonly hookData: HookData; + /** + * The recommended place to share data across scopes for all hooks + * This object is readonly. You may modify it, but attempting to overwrite it will throw an error + */ + readonly appHookData: HookData; + } + + /** + * Context on a function that is about to be executed + * This object will be passed to all pre invocation hooks + */ + interface PreInvocationContext extends HookContext { + /** + * The context object passed to the function + * This object is readonly. You may modify it, but attempting to overwrite it will throw an error + */ + readonly invocationContext: unknown; + + /** + * The input values for this specific invocation. Changes to this array _will_ affect the inputs passed to your function + */ + inputs: any[]; + + /** + * The function callback for this specific invocation. Changes to this value _will_ affect the function itself + */ + functionCallback: FunctionCallback; + } + + /** + * Context on a function that has just executed + * This object will be passed to all post invocation hooks + */ + interface PostInvocationContext extends HookContext { + /** + * The context object passed to the function + * This object is readonly. You may modify it, but attempting to overwrite it will throw an error + */ + readonly invocationContext: unknown; + + /** + * The input values for this specific invocation + */ + inputs: any[]; + + /** + * The result of the function, or null if there is no result. Changes to this value _will_ affect the overall result of the function + */ + result: any; + + /** + * The error for the function, or null if there is no error. Changes to this value _will_ affect the overall result of the function + */ + error: any; + } + + /** + * Context on a function app that is about to be started + * This object will be passed to all app start hooks + */ + interface AppStartContext extends HookContext { + /** + * Absolute directory of the function app + */ + functionAppDirectory: string; + } + + type AppTerminateContext = HookContext; + + /** + * Represents a type which can release resources, such as event listening or a timer. + */ + class Disposable { + /** + * Combine many disposable-likes into one. You can use this method when having objects with a dispose function which aren't instances of `Disposable`. + * + * @param disposableLikes Objects that have at least a `dispose`-function member. Note that asynchronous dispose-functions aren't awaited. + * @return Returns a new disposable which, upon dispose, will dispose all provided disposables. + */ + static from(...disposableLikes: { dispose: () => any }[]): Disposable; + + /** + * Creates a new disposable that calls the provided function on dispose. + * *Note* that an asynchronous function is not awaited. + * + * @param callOnDispose Function that disposes something. + */ + constructor(callOnDispose: () => any); + + /** + * Dispose this object. + */ + dispose(): any; + } + + /** + * Registers the main programming model to be used for a Node.js function app + * Only one programming model can be set. The last programming model registered will be used + * If not explicitly set, a default programming model included with the worker will be used + */ + function setProgrammingModel(programmingModel: ProgrammingModel): void; + + /** + * Returns the currently registered programming model + * If not explicitly set, a default programming model included with the worker will be used + */ + function getProgrammingModel(): ProgrammingModel; + + /** + * A set of information and methods that describe the model for handling a Node.js function app + * Currently, this is mainly focused on invocation + */ + interface ProgrammingModel { + /** + * A name for this programming model, generally only used for tracking purposes + */ + name: string; + + /** + * A version for this programming model, generally only used for tracking purposes + */ + version: string; + + /** + * Returns a new instance of the invocation model for each invocation + */ + getInvocationModel(coreContext: CoreInvocationContext): InvocationModel; + } + + /** + * Basic information and helper methods about an invocation provided from the core worker to the programming model + */ + interface CoreInvocationContext { + /** + * A guid unique to this invocation + */ + invocationId: string; + + /** + * The invocation request received by the worker from the host + */ + request: RpcInvocationRequest; + + /** + * Metadata about the function + */ + metadata: RpcFunctionMetadata; + + /** + * Describes the current state of invocation, or undefined if between states + */ + state?: InvocationState; + + /** + * The recommended way to log information + */ + log(level: RpcLogLevel, category: RpcLogCategory, message: string): void; + } + + type InvocationState = 'preInvocationHooks' | 'postInvocationHooks' | 'invocation'; + + /** + * A set of methods that describe the model for invoking a function + */ + interface InvocationModel { + /** + * Returns the context object and inputs to be passed to all following invocation methods + * This is run before preInvocation hooks + */ + getArguments(): Promise; + + /** + * The main method that executes the user's function callback + * This is run between preInvocation and postInvocation hooks + * @param context The context object returned in `getArguments`, potentially modified by preInvocation hooks + * @param inputs The input array returned in `getArguments`, potentially modified by preInvocation hooks + * @param callback The function callback to be executed + */ + invokeFunction(context: unknown, inputs: unknown[], callback: FunctionCallback): Promise; + + /** + * Returns the invocation response to send back to the host + * This is run after postInvocation hooks + * @param context The context object created in `getArguments` + * @param result The result of the function callback, potentially modified by postInvocation hooks + */ + getResponse(context: unknown, result: unknown): Promise; + } + + interface InvocationArguments { + /** + * This is usually the first argument passed to a function callback + */ + context: unknown; + + /** + * The remaining arguments passed to a function callback, generally describing the trigger/input bindings + */ + inputs: unknown[]; + } + + type FunctionCallback = (context: unknown, ...inputs: unknown[]) => unknown; + + // #region rpc types + interface RpcFunctionMetadata { + name?: string | null; + + directory?: string | null; + + scriptFile?: string | null; + + entryPoint?: string | null; + + bindings?: { [k: string]: RpcBindingInfo } | null; + + isProxy?: boolean | null; + + status?: RpcStatusResult | null; + + language?: string | null; + + rawBindings?: string[] | null; + + functionId?: string | null; + + managedDependencyEnabled?: boolean | null; + } + + interface RpcStatusResult { + status?: RpcStatus | null; + + result?: string | null; + + exception?: RpcException | null; + + logs?: RpcLog[] | null; + } + + type RpcStatus = 'failure' | 'success' | 'cancelled'; + + interface RpcLog { + invocationId?: string | null; + + category?: string | null; + + level?: RpcLogLevel | null; + + message?: string | null; + + eventId?: string | null; + + exception?: RpcException | null; + + logCategory?: RpcLogCategory | null; + } + + type RpcLogLevel = 'trace' | 'debug' | 'information' | 'warning' | 'error' | 'critical' | 'none'; + + type RpcLogCategory = 'user' | 'system' | 'customMetric'; + + interface RpcException { + source?: string | null; + + stackTrace?: string | null; + + message?: string | null; + } + + interface RpcBindingInfo { + type?: string | null; + + direction?: RpcBindingDirection | null; + + dataType?: RpcBindingDataType | null; + } + + type RpcBindingDirection = 'in' | 'out' | 'inout'; + + type RpcBindingDataType = 'undefined' | 'string' | 'binary' | 'stream'; + + interface RpcTypedData { + string?: string | null; + + json?: string | null; + + bytes?: Uint8Array | null; + + stream?: Uint8Array | null; + + http?: RpcHttpData | null; + + int?: number | Long | null; + + double?: number | null; + + collectionBytes?: RpcCollectionBytes | null; + + collectionString?: RpcCollectionString | null; + + collectionDouble?: RpcCollectionDouble | null; + + collectionSint64?: RpcCollectionSInt64 | null; + } + + interface RpcCollectionSInt64 { + sint64?: (number | Long)[] | null; + } + + interface RpcCollectionString { + string?: string[] | null; + } + + interface RpcCollectionBytes { + bytes?: Uint8Array[] | null; + } + + interface RpcCollectionDouble { + double?: number[] | null; + } + + interface RpcInvocationRequest { + invocationId?: string | null; + + functionId?: string | null; + + inputData?: RpcParameterBinding[] | null; + + triggerMetadata?: { [k: string]: RpcTypedData } | null; + + traceContext?: RpcTraceContext | null; + + retryContext?: RpcRetryContext | null; + } + + interface RpcTraceContext { + traceParent?: string | null; + + traceState?: string | null; + + attributes?: { [k: string]: string } | null; + } + + interface RpcRetryContext { + retryCount?: number | null; + + maxRetryCount?: number | null; + + exception?: RpcException | null; + } + + interface RpcInvocationResponse { + invocationId?: string | null; + + outputData?: RpcParameterBinding[] | null; + + returnValue?: RpcTypedData | null; + + result?: RpcStatusResult | null; + } + + interface RpcParameterBinding { + name?: string | null; + + data?: RpcTypedData | null; + } + + interface RpcHttpData { + method?: string | null; + + url?: string | null; + + headers?: { [k: string]: string } | null; + + body?: RpcTypedData | null; + + params?: { [k: string]: string } | null; + + statusCode?: string | null; + + query?: { [k: string]: string } | null; + + enableContentNegotiation?: boolean | null; + + rawBody?: RpcTypedData | null; + + cookies?: RpcHttpCookie[] | null; + + nullableHeaders?: { [k: string]: RpcNullableString } | null; + + nullableParams?: { [k: string]: RpcNullableString } | null; + + nullableQuery?: { [k: string]: RpcNullableString } | null; + } + + interface RpcHttpCookie { + name?: string | null; + + value?: string | null; + + domain?: RpcNullableString | null; + + path?: RpcNullableString | null; + + expires?: RpcNullableTimestamp | null; + + secure?: RpcNullableBool | null; + + httpOnly?: RpcNullableBool | null; + + sameSite?: RpcHttpCookieSameSite | null; + + maxAge?: RpcNullableDouble | null; + } + + interface RpcNullableString { + value?: string | null; + } + + interface RpcNullableDouble { + value?: number | null; + } + + interface RpcNullableBool { + value?: boolean | null; + } + + interface RpcNullableTimestamp { + value?: RpcTimestamp | null; + } + + interface RpcTimestamp { + seconds?: number | Long | null; + + nanos?: number | null; + } + + type RpcHttpCookieSameSite = 'none' | 'lax' | 'strict' | 'explicitNone'; + // #endregion rpc types +} \ No newline at end of file diff --git a/node_modules/arr-rotate/index.js b/node_modules/arr-rotate/index.js new file mode 100644 index 0000000..a38f7fc --- /dev/null +++ b/node_modules/arr-rotate/index.js @@ -0,0 +1,11 @@ +'use strict'; +module.exports = (input, n) => { + if (!Array.isArray(input)) { + throw new TypeError(`Expected an array, got ${typeof input}`); + } + + const x = input.slice(); + const num = typeof n === 'number' ? n : 0; + + return x.splice(-num % x.length).concat(x); +}; diff --git a/node_modules/arr-rotate/license b/node_modules/arr-rotate/license new file mode 100644 index 0000000..e02cd4d --- /dev/null +++ b/node_modules/arr-rotate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Martensson (github.com/kevva) + +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. diff --git a/node_modules/arr-rotate/package.json b/node_modules/arr-rotate/package.json new file mode 100644 index 0000000..f1fb2a9 --- /dev/null +++ b/node_modules/arr-rotate/package.json @@ -0,0 +1,32 @@ +{ + "name": "arr-rotate", + "version": "1.0.0", + "description": "Rotate all items in an array", + "license": "MIT", + "repository": "kevva/arr-rotate", + "author": { + "name": "Kevin Martensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "array", + "move", + "rotate", + "shift", + "splice" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/arr-rotate/readme.md b/node_modules/arr-rotate/readme.md new file mode 100644 index 0000000..a9095ba --- /dev/null +++ b/node_modules/arr-rotate/readme.md @@ -0,0 +1,49 @@ +# arr-rotate [![Build Status](https://travis-ci.org/kevva/arr-rotate.svg?branch=master)](https://travis-ci.org/kevva/arr-rotate) + +> Rotate all items in an array + + +## Install + +``` +$ npm install arr-rotate +``` + + +## Usage + +```js +const arrRotate = require('arr-rotate'); + +arrRotate(['foo', 'bar', 'unicorn'], 2); +//=> ['bar', 'unicorn', 'foo'] + +arrRotate(['foo', 'bar', 'unicorn'], 1); +//=> ['unicorn', 'foo', 'bar'] + +arrRotate(['foo', 'bar', 'unicorn'], -1); +//=> ['bar', 'unicorn', 'foo'] +``` + + +## API + +### arrRotate(input, num) + +#### input + +Type: `Array` + +Array to rotate. + +#### num + +Type: `number`
+Default: `0` + +Number of steps to rotate. + + +## License + +MIT © [Kevin Martensson](https://github.com/kevva) diff --git a/node_modules/astral-regex/index.d.ts b/node_modules/astral-regex/index.d.ts new file mode 100644 index 0000000..e81ac31 --- /dev/null +++ b/node_modules/astral-regex/index.d.ts @@ -0,0 +1,28 @@ +declare namespace astralRegex { + interface Options { + /** + Only match an exact string. Useful with `RegExp#test()` to check if a string is a astral symbol. Default: `false` _(Matches any astral symbols in a string)_ + */ + readonly exact?: boolean; + } +} + +/** +Regular expression for matching [astral symbols](https://everything2.com/title/astral+plane). + +@returns A `RegExp` for matching astral symbols. + +@example +``` +import astralRegex = require('astral-regex'); + +astralRegex({exact: true}).test('🦄'); +//=> true + +'foo 🦄 💩 bar'.match(astralRegex()); +//=> ['🦄', '💩'] +``` +*/ +declare function astralRegex(options?: astralRegex.Options): RegExp; + +export = astralRegex; diff --git a/node_modules/astral-regex/index.js b/node_modules/astral-regex/index.js new file mode 100644 index 0000000..651177d --- /dev/null +++ b/node_modules/astral-regex/index.js @@ -0,0 +1,6 @@ +'use strict'; +const regex = '[\uD800-\uDBFF][\uDC00-\uDFFF]'; + +const astralRegex = options => options && options.exact ? new RegExp(`^${regex}$`) : new RegExp(regex, 'g'); + +module.exports = astralRegex; diff --git a/node_modules/astral-regex/license b/node_modules/astral-regex/license new file mode 100644 index 0000000..db6bc32 --- /dev/null +++ b/node_modules/astral-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +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. diff --git a/node_modules/astral-regex/package.json b/node_modules/astral-regex/package.json new file mode 100644 index 0000000..d1ceea7 --- /dev/null +++ b/node_modules/astral-regex/package.json @@ -0,0 +1,33 @@ +{ + "name": "astral-regex", + "version": "2.0.0", + "description": "Regular expression for matching astral symbols", + "license": "MIT", + "repository": "kevva/astral-regex", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "astral", + "emoji", + "regex", + "surrogate" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/astral-regex/readme.md b/node_modules/astral-regex/readme.md new file mode 100644 index 0000000..89d6659 --- /dev/null +++ b/node_modules/astral-regex/readme.md @@ -0,0 +1,46 @@ +# astral-regex [![Build Status](https://travis-ci.org/kevva/astral-regex.svg?branch=master)](https://travis-ci.org/kevva/astral-regex) + +> Regular expression for matching [astral symbols](https://everything2.com/title/astral+plane) + + +## Install + +``` +$ npm install astral-regex +``` + + +## Usage + +```js +const astralRegex = require('astral-regex'); + +astralRegex({exact: true}).test('🦄'); +//=> true + +'foo 🦄 💩 bar'.match(astralRegex()); +//=> ['🦄', '💩'] +``` + + +## API + +### astralRegex([options]) + +Returns a `RegExp` for matching astral symbols. + +#### options + +Type: `Object` + +##### exact + +Type: `boolean`
+Default: `false` *(Matches any astral symbols in a string)* + +Only match an exact string. Useful with `RegExp#test()` to check if a string is a astral symbol. + + +## License + +MIT © [Kevin Mårtensson](https://github.com/kevva) diff --git a/node_modules/async-hook-jl/.eslintrc b/node_modules/async-hook-jl/.eslintrc new file mode 100644 index 0000000..7fe44f0 --- /dev/null +++ b/node_modules/async-hook-jl/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + }, + "rules": { + "indent": [2, 2], + "quotes": [1, "single", "avoid-escape"], + "curly": 0, + "strict": [2, "global"], + "no-shadow": 0, + "no-underscore-dangle": 0, + "no-use-before-define": [1, "nofunc"], + "prefer-spread": 1, + "prefer-const": 1, + "no-console": 0, + "no-var": 1 + } +} diff --git a/node_modules/async-hook-jl/.npmignore b/node_modules/async-hook-jl/.npmignore new file mode 100644 index 0000000..eb79dd5 --- /dev/null +++ b/node_modules/async-hook-jl/.npmignore @@ -0,0 +1,2 @@ +node_modules +.idea diff --git a/node_modules/async-hook-jl/.travis.yml b/node_modules/async-hook-jl/.travis.yml new file mode 100644 index 0000000..3051cf8 --- /dev/null +++ b/node_modules/async-hook-jl/.travis.yml @@ -0,0 +1,11 @@ +script: + - "npm test" + +language: node_js + +node_js: + - "4" + - "6" + - "7" + +sudo: false diff --git a/node_modules/async-hook-jl/LICENSE.md b/node_modules/async-hook-jl/LICENSE.md new file mode 100644 index 0000000..4a0b8be --- /dev/null +++ b/node_modules/async-hook-jl/LICENSE.md @@ -0,0 +1,19 @@ +Copyright (c) 2015 Andreas Madsen + +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. diff --git a/node_modules/async-hook-jl/README.md b/node_modules/async-hook-jl/README.md new file mode 100644 index 0000000..b916095 --- /dev/null +++ b/node_modules/async-hook-jl/README.md @@ -0,0 +1,63 @@ +[![Build Status](https://travis-ci.org/Jeff-Lewis/async-hook-jl.svg?branch=master)](https://travis-ci.org/Jeff-Lewis/async-hook-jl) + +#async-hook-jl + +> Inspect the life of handle objects in node + +## Documentation + +This is high level abstraction of the currently undocumented node API called +AsyncWrap. It patches some issues, makes the API more uniform and allows multiply +hooks to be created. + +I personally hope that most of this will make it into nodecore, but for now +it exists as an userland module. + +For the details of how AsyncWrap works and by extension how this module works, +please see the semi-official AsyncWrap documentation: +https://github.com/nodejs/diagnostics/blob/master/tracing/AsyncWrap/README.md + +```javascript +const asyncHook = require('async-hook-jl'); +``` + +#### Hooks + +The function arguments are: + +```javascript +function init(uid, handle, provider, parentUid, parentHandle) { /* your code */ } +function pre(uid, handle) { /* your code */ } +function post(uid, handle, didThrow) { /* your code */ } +function destroy(uid) { /* your code */ } +``` + +To add hooks: + +```javascript +asyncHook.addHooks({ init, pre, post, destroy }); +``` + +To remove hooks: + +```javascript +asyncHooks.removeHooks({ init, pre, post, destroy }); +``` + +All properties in the hooks object that `addHooks` and `removeHooks` takes are +optional. + +#### Providers + +The providers map is exposed as: +``` +asyncHook.providers[provider]; +``` + +#### Enable and disable + +You can enable and disable all hooks by using `asyncHook.enable()` and +`asyncHook.disable()`. By default it is disabled. + +Be careful about disabling the hooks, this will most likely conflict with other +modules that uses `async-hook-jl`. diff --git a/node_modules/async-hook-jl/async-hook.js b/node_modules/async-hook-jl/async-hook.js new file mode 100644 index 0000000..81c13e2 --- /dev/null +++ b/node_modules/async-hook-jl/async-hook.js @@ -0,0 +1,134 @@ +'use strict'; + +const asyncWrap = process.binding('async_wrap'); +const TIMERWRAP = asyncWrap.Providers.TIMERWRAP; + +const patchs = { + 'nextTick': require('./patches/next-tick.js'), + 'promise': require('./patches/promise.js'), + 'timers': require('./patches/timers.js') +}; + +const ignoreUIDs = new Set(); + +function State() { + this.enabled = false; + this.counter = 0; +} + +function Hooks() { + const initFns = this.initFns = []; + const preFns = this.preFns = []; + const postFns = this.postFns = []; + const destroyFns = this.destroyFns = []; + + this.init = function (uid, provider, parentUid, parentHandle) { + // Ignore TIMERWRAP, since setTimeout etc. is monkey patched + if (provider === TIMERWRAP) { + ignoreUIDs.add(uid); + return; + } + + // call hooks + for (const hook of initFns) { + hook(uid, this, provider, parentUid, parentHandle); + } + }; + + this.pre = function (uid) { + if (ignoreUIDs.has(uid)) return; + + // call hooks + for (const hook of preFns) { + hook(uid, this); + } + }; + + this.post = function (uid, didThrow) { + if (ignoreUIDs.has(uid)) return; + + // call hooks + for (const hook of postFns) { + hook(uid, this, didThrow); + } + }; + + this.destroy = function (uid) { + // Cleanup the ignore list if this uid should be ignored + if (ignoreUIDs.has(uid)) { + ignoreUIDs.delete(uid); + return; + } + + // call hooks + for (const hook of destroyFns) { + hook(uid); + } + }; +} + +Hooks.prototype.add = function (hooks) { + if (hooks.init) this.initFns.push(hooks.init); + if (hooks.pre) this.preFns.push(hooks.pre); + if (hooks.post) this.postFns.push(hooks.post); + if (hooks.destroy) this.destroyFns.push(hooks.destroy); +}; + +function removeElement(array, item) { + const index = array.indexOf(item); + if (index === -1) return; + array.splice(index, 1); +} + +Hooks.prototype.remove = function (hooks) { + if (hooks.init) removeElement(this.initFns, hooks.init); + if (hooks.pre) removeElement(this.preFns, hooks.pre); + if (hooks.post) removeElement(this.postFns, hooks.post); + if (hooks.destroy) removeElement(this.destroyFns, hooks.destroy); +}; + +function AsyncHook() { + this._state = new State(); + this._hooks = new Hooks(); + + // expose version for conflict detection + this.version = require('./package.json').version; + + // expose the Providers map + this.providers = asyncWrap.Providers; + + // apply patches + for (const key of Object.keys(patchs)) { + patchs[key].call(this); + } + + // setup async wrap + if (process.env.hasOwnProperty('NODE_ASYNC_HOOK_WARNING')) { + console.warn('warning: you are using async-hook-jl which is unstable.'); + } + asyncWrap.setupHooks({ + init: this._hooks.init, + pre: this._hooks.pre, + post: this._hooks.post, + destroy: this._hooks.destroy + }); +} +module.exports = AsyncHook; + +AsyncHook.prototype.addHooks = function (hooks) { + this._hooks.add(hooks); +}; + +AsyncHook.prototype.removeHooks = function (hooks) { + this._hooks.remove(hooks); +}; + +AsyncHook.prototype.enable = function () { + this._state.enabled = true; + asyncWrap.enable(); +}; + +AsyncHook.prototype.disable = function () { + this._state.enabled = false; + asyncWrap.disable(); +}; \ No newline at end of file diff --git a/node_modules/async-hook-jl/index.js b/node_modules/async-hook-jl/index.js new file mode 100644 index 0000000..0b5e7d3 --- /dev/null +++ b/node_modules/async-hook-jl/index.js @@ -0,0 +1,31 @@ +'use strict'; + +const AsyncHook = require('./async-hook.js'); + +// If a another copy (same version or not) of stack-chain exists it will result +// in wrong stack traces (most likely dublicate callSites). +if (global._asyncHook) { + // In case the version match, we can simply return the first initialized copy + if (global._asyncHook.version === require('./package.json').version) { + module.exports = global._asyncHook; + } + // The version don't match, this is really bad. Lets just throw + else { + throw new Error('Conflicting version of async-hook-jl found'); + } +} else { + const stackChain = require('stack-chain'); + + // Remove callSites from this module. AsyncWrap doesn't have any callSites + // and the hooks are expected to be completely transparent. + stackChain.filter.attach(function (error, frames) { + return frames.filter(function (callSite) { + const filename = callSite.getFileName(); + // filename is not always a string, for example in case of eval it is + // undefined. So check if the filename is defined. + return !(filename && filename.slice(0, __dirname.length) === __dirname); + }); + }); + + module.exports = global._asyncHook = new AsyncHook(); +} \ No newline at end of file diff --git a/node_modules/async-hook-jl/package.json b/node_modules/async-hook-jl/package.json new file mode 100644 index 0000000..f6230ca --- /dev/null +++ b/node_modules/async-hook-jl/package.json @@ -0,0 +1,33 @@ +{ + "name": "async-hook-jl", + "description": "Inspect the life of handle objects in node", + "version": "1.7.6", + "author": "Andreas Madsen ", + "main": "./index.js", + "scripts": { + "test": "node ./test/runner.js && eslint ." + }, + "repository": { + "type": "git", + "url": "git://github.com/jeff-lewis/async-hook-jl.git" + }, + "keywords": [ + "async", + "async hooks", + "inspect", + "async wrap" + ], + "license": "MIT", + "dependencies": { + "stack-chain": "^1.3.7" + }, + "devDependencies": { + "async": "1.5.x", + "cli-color": "1.1.x", + "eslint": "^3.4.0", + "endpoint": "0.4.x" + }, + "engines": { + "node": "^4.7 || >=6.9 || >=7.3" + } +} diff --git a/node_modules/async-hook-jl/patches/next-tick.js b/node_modules/async-hook-jl/patches/next-tick.js new file mode 100644 index 0000000..525bd7a --- /dev/null +++ b/node_modules/async-hook-jl/patches/next-tick.js @@ -0,0 +1,57 @@ +'use strict'; + +function NextTickWrap() {} + +module.exports = function patch() { + const hooks = this._hooks; + const state = this._state; + + const oldNextTick = process.nextTick; + process.nextTick = function () { + if (!state.enabled) return oldNextTick.apply(process, arguments); + + const args = new Array(arguments.length); + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + const callback = args[0]; + + if (typeof callback !== 'function') { + throw new TypeError('callback is not a function'); + } + + const handle = new NextTickWrap(); + const uid = --state.counter; + + // call the init hook + hooks.init.call(handle, uid, 0, null, null); + + // overwrite callback + args[0] = function () { + // call the pre hook + hooks.pre.call(handle, uid); + + let didThrow = true; + try { + callback.apply(this, arguments); + didThrow = false; + } finally { + // If `callback` threw and there is an uncaughtException handler + // then call the `post` and `destroy` hook after the uncaughtException + // user handlers have been invoked. + if(didThrow && process.listenerCount('uncaughtException') > 0) { + process.once('uncaughtException', function () { + hooks.post.call(handle, uid, true); + hooks.destroy.call(null, uid); + }); + } + } + + // callback done successfully + hooks.post.call(handle, uid, false); + hooks.destroy.call(null, uid); + }; + + return oldNextTick.apply(process, args); + }; +} diff --git a/node_modules/async-hook-jl/patches/promise.js b/node_modules/async-hook-jl/patches/promise.js new file mode 100644 index 0000000..6e81753 --- /dev/null +++ b/node_modules/async-hook-jl/patches/promise.js @@ -0,0 +1,64 @@ +'use strict'; + +function PromiseWrap() {} + +module.exports = function patchPromise() { + const hooks = this._hooks; + const state = this._state; + + const Promise = global.Promise; + + /* As per ECMAScript 2015, .catch must be implemented by calling .then, as + * such we need needn't patch .catch as well. see: + * http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.catch + */ + const oldThen = Promise.prototype.then; + Promise.prototype.then = wrappedThen; + + function makeWrappedHandler(fn, handle, uid, isOnFulfilled) { + if ('function' !== typeof fn) { + return isOnFulfilled + ? makeUnhandledResolutionHandler(uid) + : makeUnhandledRejectionHandler(uid); + } + + return function wrappedHandler() { + hooks.pre.call(handle, uid); + try { + return fn.apply(this, arguments); + } finally { + hooks.post.call(handle, uid, false); + hooks.destroy.call(null, uid); + } + }; + } + + function makeUnhandledResolutionHandler(uid) { + return function unhandledResolutionHandler(val) { + hooks.destroy.call(null, uid); + return val; + }; + } + + function makeUnhandledRejectionHandler(uid) { + return function unhandledRejectedHandler(val) { + hooks.destroy.call(null, uid); + throw val; + }; + } + + function wrappedThen(onFulfilled, onRejected) { + if (!state.enabled) return oldThen.call(this, onFulfilled, onRejected); + + const handle = new PromiseWrap(); + const uid = --state.counter; + + hooks.init.call(handle, uid, 0, null, null); + + return oldThen.call( + this, + makeWrappedHandler(onFulfilled, handle, uid, true), + makeWrappedHandler(onRejected, handle, uid, false) + ); + } +}; diff --git a/node_modules/async-hook-jl/patches/timers.js b/node_modules/async-hook-jl/patches/timers.js new file mode 100644 index 0000000..79e80c9 --- /dev/null +++ b/node_modules/async-hook-jl/patches/timers.js @@ -0,0 +1,117 @@ +'use strict'; + +const timers = require('timers'); + +function TimeoutWrap() {} +function IntervalWrap() {} +function ImmediateWrap() {} + +const timeoutMap = new Map(); +const intervalMap = new Map(); +const ImmediateMap = new Map(); + +let activeCallback = null; +let clearedInCallback = false; + +module.exports = function patch() { + patchTimer(this._hooks, this._state, 'setTimeout', 'clearTimeout', TimeoutWrap, timeoutMap, true); + patchTimer(this._hooks, this._state, 'setInterval', 'clearInterval', IntervalWrap, intervalMap, false); + patchTimer(this._hooks, this._state, 'setImmediate', 'clearImmediate', ImmediateWrap, ImmediateMap, true); + + global.setTimeout = timers.setTimeout; + global.setInterval = timers.setInterval; + global.setImmediate = timers.setImmediate; + + global.clearTimeout = timers.clearTimeout; + global.clearInterval = timers.clearInterval; + global.clearImmediate = timers.clearImmediate; +}; + +function patchTimer(hooks, state, setFn, clearFn, Handle, timerMap, singleCall) { + const oldSetFn = timers[setFn]; + const oldClearFn = timers[clearFn]; + + // overwrite set[Timeout] + timers[setFn] = function () { + if (!state.enabled) return oldSetFn.apply(timers, arguments); + + const args = new Array(arguments.length); + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + const callback = args[0]; + + if (typeof callback !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + + const handle = new Handle(); + const uid = --state.counter; + let timerId = undefined; + + // call the init hook + hooks.init.call(handle, uid, 0, null, null); + + // overwrite callback + args[0] = function () { + // call the pre hook + activeCallback = timerId; + hooks.pre.call(handle, uid); + + let didThrow = true; + try { + callback.apply(this, arguments); + didThrow = false; + } finally { + // If `callback` threw and there is an uncaughtException handler + // then call the `post` and `destroy` hook after the uncaughtException + // user handlers have been invoked. + if (didThrow && process.listenerCount('uncaughtException') > 0) { + process.once('uncaughtException', function () { + // call the post hook + hooks.post.call(handle, uid, true); + // setInterval won't continue + timerMap.delete(timerId); + hooks.destroy.call(null, uid); + }); + } + } + + // callback done successfully + hooks.post.call(handle, uid, false); + activeCallback = null; + + // call the destroy hook if the callback will only be called once + if (singleCall || clearedInCallback) { + clearedInCallback = false; + timerMap.delete(timerId); + hooks.destroy.call(null, uid); + } + }; + + timerId = oldSetFn.apply(timers, args); + // Bind the timerId and uid for later use, in case the clear* function is + // called. + timerMap.set(timerId, uid); + + return timerId; + }; + + // overwrite clear[Timeout] + timers[clearFn] = function (timerId) { + // If clear* was called within the timer callback, then delay the destroy + // event to after the post event has been called. + if (activeCallback === timerId && timerId !== null) { + clearedInCallback = true; + } + // clear should call the destroy hook. Note if timerId doesn't exists + // it is because asyncWrap wasn't enabled at the time. + else if (timerMap.has(timerId)) { + const uid = timerMap.get(timerId); + timerMap.delete(timerId); + hooks.destroy.call(null, uid); + } + + oldClearFn.apply(timers, arguments); + }; +} diff --git a/node_modules/async-hook-jl/test/runner.js b/node_modules/async-hook-jl/test/runner.js new file mode 100644 index 0000000..ed43afe --- /dev/null +++ b/node_modules/async-hook-jl/test/runner.js @@ -0,0 +1,55 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const async = require('async'); +const spawn = require('child_process').spawn; +const clc = require('cli-color'); + +const allFailed = clc.red.bold; +const allPassed = clc.green; + +const failed = clc.yellow; +const passed = (t) => t; + +const files = fs.readdirSync(__dirname).filter(function (filename) { + return filename.slice(0, 5) === 'test-'; +}); + +async.mapSeries(files, runTest, function (err, passed) { + if (err) throw err; + + let failed = 0; + for (const ok of passed) { + if (!ok) failed += 1; + } + + if (failed > 0) { + console.log(allFailed('failed') + ` - ${failed} tests failed`); + } else { + console.log(allPassed('passed') + ` - ${passed.length} tests passed`); + } +}); + +function runTest(filename, done) { + process.stdout.write(` - running ${filename} ...`); + + const p = spawn(process.execPath, [path.resolve(__dirname, filename)], { + stdio: ['ignore', 1, 2], + env: { + 'NODE_ASYNC_HOOK_NO_WARNING': '1' + } + }); + + p.once('close', function (statusCode) { + const ok = (statusCode === 0); + + if (ok) { + console.log(' ' + passed('ok')); + } else { + console.log(' - ' + failed('failed')); + } + + done(null, ok); + }); +} diff --git a/node_modules/async-hook-jl/test/test-conflict-match.js b/node_modules/async-hook-jl/test/test-conflict-match.js new file mode 100644 index 0000000..bb2fc9a --- /dev/null +++ b/node_modules/async-hook-jl/test/test-conflict-match.js @@ -0,0 +1,11 @@ +'use strict'; + +const assert = require('assert'); + +const existing = global._asyncHook = { + version: require('../package.json').version +}; + +const asyncHook = require('../'); + +assert.equal(asyncHook, existing); diff --git a/node_modules/async-hook-jl/test/test-conflict-mismatch.js b/node_modules/async-hook-jl/test/test-conflict-mismatch.js new file mode 100644 index 0000000..d2c805c --- /dev/null +++ b/node_modules/async-hook-jl/test/test-conflict-mismatch.js @@ -0,0 +1,13 @@ +'use strict'; + +const assert = require('assert'); + +global._asyncHook = { + version: '0.0.0' +}; + +try { + require('../'); +} catch (e) { + assert.equal(e.message, 'Conflicting version of async-hook-jl found'); +} \ No newline at end of file diff --git a/node_modules/async-hook-jl/test/test-fsaccess-disabled.js b/node_modules/async-hook-jl/test/test-fsaccess-disabled.js new file mode 100644 index 0000000..38d66fe --- /dev/null +++ b/node_modules/async-hook-jl/test/test-fsaccess-disabled.js @@ -0,0 +1,33 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); +const fs = require('fs'); + +let called = false; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +fs.access(__filename, function () { + called = true; +}); + +process.once('exit', function () { + assert.equal(called, true); +}); diff --git a/node_modules/async-hook-jl/test/test-fsaccess-enabled.js b/node_modules/async-hook-jl/test/test-fsaccess-enabled.js new file mode 100644 index 0000000..f46ad25 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-fsaccess-enabled.js @@ -0,0 +1,75 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); +const fs = require('fs'); + +let called = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; +let postDidThrow = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle, didThrow) { + postUid = uid; + postHandle = handle; + postDidThrow = didThrow; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +fs.access(__filename, function () { + called = true; +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'FSReqWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, asyncHook.providers.FSREQWRAP); + + assert.equal(postDidThrow, false); + + assert.equal(called, true); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-hooks-remove.js b/node_modules/async-hook-jl/test/test-hooks-remove.js new file mode 100644 index 0000000..37e1234 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-hooks-remove.js @@ -0,0 +1,48 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); +const fs = require('fs'); + +let called = false; + +let initCalls = 0; +let preCalls = 0; +let postCalls = 0; +let destroyCalls = 0; + +const hooks = { + init: function () { + initCalls += 1; + }, + pre: function () { + preCalls += 1; + }, + post: function () { + postCalls += 1; + }, + destroy: function () { + destroyCalls += 1; + } +}; + +asyncHook.addHooks(hooks); +asyncHook.addHooks(hooks); +asyncHook.removeHooks(hooks); + +asyncHook.enable(); + +fs.access(__filename, function () { + called = true; +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(called, true); + + assert.equal(initCalls, 1); + assert.equal(preCalls, 1); + assert.equal(postCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-hooks-twice.js b/node_modules/async-hook-jl/test/test-hooks-twice.js new file mode 100644 index 0000000..868afdc --- /dev/null +++ b/node_modules/async-hook-jl/test/test-hooks-twice.js @@ -0,0 +1,47 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); +const fs = require('fs'); + +let called = false; + +let initCalls = 0; +let preCalls = 0; +let postCalls = 0; +let destroyCalls = 0; + +const hooks = { + init: function () { + initCalls += 1; + }, + pre: function () { + preCalls += 1; + }, + post: function () { + postCalls += 1; + }, + destroy: function () { + destroyCalls += 1; + } +}; + +asyncHook.addHooks(hooks); +asyncHook.addHooks(hooks); + +asyncHook.enable(); + +fs.access(__filename, function () { + called = true; +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(called, true); + + assert.equal(initCalls, 2); + assert.equal(preCalls, 2); + assert.equal(postCalls, 2); + assert.equal(destroyCalls, 2); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-clear-in-callback.js b/node_modules/async-hook-jl/test/test-immediate-clear-in-callback.js new file mode 100644 index 0000000..dbe6f34 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-clear-in-callback.js @@ -0,0 +1,38 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const timings = []; + +asyncHook.addHooks({ + init: function (uid, handle) { + timings.push(`init#${uid} - ${handle.constructor.name}`); + }, + pre: function (uid) { + timings.push(`pre#${uid}`); + }, + post: function (uid) { + timings.push(`post#${uid}`); + }, + destroy: function (uid) { + timings.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); +const timerId = setImmediate(() => { + timings.push('callback'); + clearImmediate(timerId); +}, 100); +asyncHook.disable(); + +process.once('exit', function () { + assert.deepEqual(timings, [ + 'init#-1 - ImmediateWrap', + 'pre#-1', + 'callback', + 'post#-1', + 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-clear.js b/node_modules/async-hook-jl/test/test-immediate-clear.js new file mode 100644 index 0000000..4c06f10 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-clear.js @@ -0,0 +1,59 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandleName = ''; +let initParent = {}; +let initProvider = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandleName = handle.constructor.name; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +const timerId = setImmediate(function () { + timerCalled = true; +}); + +clearImmediate(timerId); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, destroyUid); + + assert.equal(initHandleName, 'ImmediateWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(timerCalled, false); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-didthrow.js b/node_modules/async-hook-jl/test/test-immediate-didthrow.js new file mode 100644 index 0000000..16fe524 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-didthrow.js @@ -0,0 +1,46 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const eventOrder = []; + +let throwFlag = null; + +asyncHook.addHooks({ + init: function (uid, handle) { + eventOrder.push(`init#${uid} ${handle.constructor.name}`); + }, + pre: function (uid) { + eventOrder.push(`pre#${uid}`); + }, + post: function (uid, handle, didThrow) { + throwFlag = didThrow; + eventOrder.push(`post#${uid}`); + }, + destroy: function (uid) { + eventOrder.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); + +process.once('uncaughtException', function () { + eventOrder.push('exception'); +}); + +setImmediate(function () { + eventOrder.push('callback'); + throw new Error('error'); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.strictEqual(throwFlag, true); + assert.deepEqual(eventOrder, [ + 'init#-1 ImmediateWrap', 'pre#-1', + 'callback', 'exception', + 'post#-1', 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-disabled.js b/node_modules/async-hook-jl/test/test-immediate-disabled.js new file mode 100644 index 0000000..7d77b48 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-disabled.js @@ -0,0 +1,42 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerACalled = false; +let timerBCalled = false; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +const timerId = setImmediate(function () { + timerACalled = true; +}); + +clearImmediate(timerId); + +setImmediate(function (arg1, arg2) { + timerBCalled = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 'a', 'b'); + +process.once('exit', function () { + assert.equal(timerACalled, false); + assert.equal(timerBCalled, true); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-enabled.js b/node_modules/async-hook-jl/test/test-immediate-enabled.js new file mode 100644 index 0000000..9ae4f41 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-enabled.js @@ -0,0 +1,76 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; +let postDidThrow = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle, didThrow) { + postUid = uid; + postHandle = handle; + postDidThrow = didThrow; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +setImmediate(function (arg1, arg2) { + timerCalled = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 'a', 'b'); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'ImmediateWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(postDidThrow, false); + + assert.equal(timerCalled, true); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-immediate-exception.js b/node_modules/async-hook-jl/test/test-immediate-exception.js new file mode 100644 index 0000000..46489b6 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-exception.js @@ -0,0 +1,32 @@ +'use strict'; + +if (process.env.hasOwnProperty('ASYNC_HOOK_TEST_CHILD')) { + const asyncHook = require('../'); + + asyncHook.enable(); + + setImmediate(function () { + throw new Error('test error'); + }); +} else { + const spawn = require('child_process').spawn; + const endpoint = require('endpoint'); + + const child = spawn(process.execPath, [__filename], { + env: Object.assign({ ASYNC_HOOK_TEST_CHILD: '' }, process.env), + stdio: ['ignore', 1, 'pipe'] + }); + + let stderr = null; + child.stderr.pipe(endpoint(function (err, _stderr) { + if (err) throw err; + stderr = _stderr; + })); + + child.once('close', function (statusCode) { + if (statusCode !== 1 || stderr.toString().indexOf('test error') === -1) { + process.stderr.write(stderr); + process.exit(statusCode); + } + }); +} diff --git a/node_modules/async-hook-jl/test/test-immediate-non-function.js b/node_modules/async-hook-jl/test/test-immediate-non-function.js new file mode 100644 index 0000000..a4ea4fb --- /dev/null +++ b/node_modules/async-hook-jl/test/test-immediate-non-function.js @@ -0,0 +1,21 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +asyncHook.enable(); + +let throws = false; +try { + setImmediate(undefined, 1); +} catch (e) { + assert.equal(e.message, '"callback" argument must be a function'); + assert.equal(e.name, 'TypeError'); + throws = true; +} + +asyncHook.disable(); + +process.once('exit', function () { + assert(throws); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-clear-in-callback.js b/node_modules/async-hook-jl/test/test-interval-clear-in-callback.js new file mode 100644 index 0000000..4a16c75 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-clear-in-callback.js @@ -0,0 +1,38 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const timings = []; + +asyncHook.addHooks({ + init: function (uid, handle) { + timings.push(`init#${uid} - ${handle.constructor.name}`); + }, + pre: function (uid) { + timings.push(`pre#${uid}`); + }, + post: function (uid) { + timings.push(`post#${uid}`); + }, + destroy: function (uid) { + timings.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); +const timerId = setInterval(() => { + timings.push('callback'); + clearInterval(timerId); +}, 100); +asyncHook.disable(); + +process.once('exit', function () { + assert.deepEqual(timings, [ + 'init#-1 - IntervalWrap', + 'pre#-1', + 'callback', + 'post#-1', + 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-clear.js b/node_modules/async-hook-jl/test/test-interval-clear.js new file mode 100644 index 0000000..dc7fccc --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-clear.js @@ -0,0 +1,59 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandleName = ''; +let initParent = {}; +let initProvider = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandleName = handle.constructor.name; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +const timerId = setInterval(function () { + timerCalled = true; +}); + +clearInterval(timerId); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, destroyUid); + + assert.equal(initHandleName, 'IntervalWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(timerCalled, false); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-didthrow.js b/node_modules/async-hook-jl/test/test-interval-didthrow.js new file mode 100644 index 0000000..0a88c21 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-didthrow.js @@ -0,0 +1,46 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const eventOrder = []; + +let throwFlag = null; + +asyncHook.addHooks({ + init: function (uid, handle) { + eventOrder.push(`init#${uid} ${handle.constructor.name}`); + }, + pre: function (uid) { + eventOrder.push(`pre#${uid}`); + }, + post: function (uid, handle, didThrow) { + throwFlag = didThrow; + eventOrder.push(`post#${uid}`); + }, + destroy: function (uid) { + eventOrder.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); + +process.once('uncaughtException', function () { + eventOrder.push('exception'); +}); + +setInterval(function () { + eventOrder.push('callback'); + throw new Error('error'); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.strictEqual(throwFlag, true); + assert.deepEqual(eventOrder, [ + 'init#-1 IntervalWrap', 'pre#-1', + 'callback', 'exception', + 'post#-1', 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-disabled.js b/node_modules/async-hook-jl/test/test-interval-disabled.js new file mode 100644 index 0000000..2491e35 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-disabled.js @@ -0,0 +1,42 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerACalled = false; +let timerBCalled = false; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +const timerAId = setInterval(function () { + timerACalled = true; +}); +clearInterval(timerAId); + +const timerBId = setInterval(function (arg1, arg2) { + timerBCalled = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); + clearInterval(timerBId); +}, 0, 'a', 'b'); + +process.once('exit', function () { + assert.equal(timerACalled, false); + assert.equal(timerBCalled, true); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-enabled.js b/node_modules/async-hook-jl/test/test-interval-enabled.js new file mode 100644 index 0000000..13d11d7 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-enabled.js @@ -0,0 +1,86 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = 0; + +let initCalls = 0; +let preCalls = 0; +let postCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; +let postDidThrow = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + + preCalls += 1; + }, + post: function (uid, handle, didThrow) { + postUid = uid; + postHandle = handle; + postDidThrow = didThrow; + + postCalls += 1; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +const timerId = setInterval(function (arg1, arg2) { + timerCalled += 1; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); + + if (timerCalled === 2) clearInterval(timerId); +}, 0, 'a', 'b'); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'IntervalWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(postDidThrow, false); + + assert.equal(timerCalled, 2); + assert.equal(initCalls, 1); + assert.equal(preCalls, 2); + assert.equal(postCalls, 2); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-interval-exception.js b/node_modules/async-hook-jl/test/test-interval-exception.js new file mode 100644 index 0000000..65f8855 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-exception.js @@ -0,0 +1,32 @@ +'use strict'; + +if (process.env.hasOwnProperty('ASYNC_HOOK_TEST_CHILD')) { + const asyncHook = require('../'); + + asyncHook.enable(); + + setInterval(function () { + throw new Error('test error'); + }); +} else { + const spawn = require('child_process').spawn; + const endpoint = require('endpoint'); + + const child = spawn(process.execPath, [__filename], { + env: Object.assign({ ASYNC_HOOK_TEST_CHILD: '' }, process.env), + stdio: ['ignore', 1, 'pipe'] + }); + + let stderr = null; + child.stderr.pipe(endpoint(function (err, _stderr) { + if (err) throw err; + stderr = _stderr; + })); + + child.once('close', function (statusCode) { + if (statusCode !== 1 || stderr.toString().indexOf('test error') === -1) { + process.stderr.write(stderr); + process.exit(statusCode); + } + }); +} diff --git a/node_modules/async-hook-jl/test/test-interval-non-function.js b/node_modules/async-hook-jl/test/test-interval-non-function.js new file mode 100644 index 0000000..690a707 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-interval-non-function.js @@ -0,0 +1,21 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +asyncHook.enable(); + +let throws = false; +try { + setInterval(undefined, 1); +} catch (e) { + assert.equal(e.message, '"callback" argument must be a function'); + assert.equal(e.name, 'TypeError'); + throws = true; +} + +asyncHook.disable(); + +process.once('exit', function () { + assert(throws); +}); diff --git a/node_modules/async-hook-jl/test/test-nexttick-didthrow.js b/node_modules/async-hook-jl/test/test-nexttick-didthrow.js new file mode 100644 index 0000000..b375b44 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-nexttick-didthrow.js @@ -0,0 +1,46 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const eventOrder = []; + +let throwFlag = null; + +asyncHook.addHooks({ + init: function (uid, handle) { + eventOrder.push(`init#${uid} ${handle.constructor.name}`); + }, + pre: function (uid) { + eventOrder.push(`pre#${uid}`); + }, + post: function (uid, handle, didThrow) { + throwFlag = didThrow; + eventOrder.push(`post#${uid}`); + }, + destroy: function (uid) { + eventOrder.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); + +process.once('uncaughtException', function () { + eventOrder.push('exception'); +}); + +process.nextTick(function () { + eventOrder.push('callback'); + throw new Error('error'); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.strictEqual(throwFlag, true); + assert.deepEqual(eventOrder, [ + 'init#-1 NextTickWrap', 'pre#-1', + 'callback', 'exception', + 'post#-1', 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-nexttick-disabled.js b/node_modules/async-hook-jl/test/test-nexttick-disabled.js new file mode 100644 index 0000000..732893a --- /dev/null +++ b/node_modules/async-hook-jl/test/test-nexttick-disabled.js @@ -0,0 +1,34 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let called = false; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +process.nextTick(function (arg1, arg2) { + called = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 'a', 'b'); + +process.once('exit', function () { + assert.equal(called, true); +}); diff --git a/node_modules/async-hook-jl/test/test-nexttick-enabled.js b/node_modules/async-hook-jl/test/test-nexttick-enabled.js new file mode 100644 index 0000000..83fdf21 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-nexttick-enabled.js @@ -0,0 +1,76 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let called = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; +let postDidThrow = NaN; + +let postHandle = {}; +let postUid = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle, didThrow) { + postUid = uid; + postHandle = handle; + postDidThrow = didThrow; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +process.nextTick(function (arg1, arg2) { + called = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 'a', 'b'); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'NextTickWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(postDidThrow, false); + + assert.equal(called, true); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-nexttick-exception.js b/node_modules/async-hook-jl/test/test-nexttick-exception.js new file mode 100644 index 0000000..5635d91 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-nexttick-exception.js @@ -0,0 +1,32 @@ +'use strict'; + +if (process.env.hasOwnProperty('ASYNC_HOOK_TEST_CHILD')) { + const asyncHook = require('../'); + + asyncHook.enable(); + + process.nextTick(function () { + throw new Error('test error'); + }); +} else { + const spawn = require('child_process').spawn; + const endpoint = require('endpoint'); + + const child = spawn(process.execPath, [__filename], { + env: Object.assign({ ASYNC_HOOK_TEST_CHILD: '' }, process.env), + stdio: ['ignore', 1, 'pipe'] + }); + + let stderr = null; + child.stderr.pipe(endpoint(function (err, _stderr) { + if (err) throw err; + stderr = _stderr; + })); + + child.once('close', function (statusCode) { + if (statusCode !== 1 || stderr.toString().indexOf('test error') === -1) { + process.stderr.write(stderr); + process.exit(statusCode); + } + }); +} diff --git a/node_modules/async-hook-jl/test/test-nexttick-non-function.js b/node_modules/async-hook-jl/test/test-nexttick-non-function.js new file mode 100644 index 0000000..bba245a --- /dev/null +++ b/node_modules/async-hook-jl/test/test-nexttick-non-function.js @@ -0,0 +1,21 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +asyncHook.enable(); + +let throws = false; +try { + process.nextTick(undefined, 1); +} catch (e) { + assert.equal(e.message, 'callback is not a function'); + assert.equal(e.name, 'TypeError'); + throws = true; +} + +asyncHook.disable(); + +process.once('exit', function () { + assert(throws); +}); diff --git a/node_modules/async-hook-jl/test/test-parent.js b/node_modules/async-hook-jl/test/test-parent.js new file mode 100644 index 0000000..68a62b7 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-parent.js @@ -0,0 +1,58 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); +const net = require('net'); + +let called = false; +let firstHook = true; + +let initCalls = 0; + +let serverHandle = {}; +let serverUid = NaN; + +let clientParentHandle = {}; +let clientParentUid = NaN; + + +asyncHook.addHooks({ + init: function (uid, handle, provider, parentUid, parentHandle) { + if (provider != asyncHook.providers.TCPWRAP) return; + + if (firstHook) { + firstHook = false; + + serverUid = uid; + serverHandle = handle; + + assert.equal(parentUid, null); + assert.equal(parentHandle, null); + } else { + clientParentHandle = parentHandle; + clientParentUid = parentUid; + } + + initCalls += 1; + } +}); + +asyncHook.enable(); + +const server = net.createServer(function (socket) { + socket.end(); + server.close(); + called = true; +}).listen(function () { + net.connect(this.address()); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(serverHandle, clientParentHandle); + assert.equal(serverUid, clientParentUid); + + assert.equal(called, true); + assert.equal(initCalls, 2); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-catch-enabled.js b/node_modules/async-hook-jl/test/test-promise-catch-enabled.js new file mode 100644 index 0000000..6aed378 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-catch-enabled.js @@ -0,0 +1,75 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let rejctedCalled = false; +let rejectedArg = null; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle) { + postUid = uid; + postHandle = handle; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +Promise + .reject('a') + .catch(arg => { + rejctedCalled = true; + rejectedArg = arg; + }); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'PromiseWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(rejctedCalled, true); + assert.equal(rejectedArg, 'a'); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-catch-then-chain-fulfilled-enabled.js b/node_modules/async-hook-jl/test/test-promise-catch-then-chain-fulfilled-enabled.js new file mode 100644 index 0000000..97e2bf3 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-catch-then-chain-fulfilled-enabled.js @@ -0,0 +1,80 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let rejectedCalled = false; +let fulfilledCalled = false; +let fulfilledArg = null; + +const initUid = []; +const initHandle = []; +const initProvider = []; +const initParent = []; + +const preUid = []; +const preHandle = []; + +const postUid = []; +const postHandle = []; + +const destroyUid = []; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid.push(uid); + initHandle.push(handle); + initProvider.push(provider); + initParent.push(parent); + }, + pre: function (uid, handle) { + preUid.push(uid); + preHandle.push(handle); + }, + post: function (uid, handle) { + postUid.push(uid); + postHandle.push(handle); + }, + destroy: function (uid) { + destroyUid.push(uid); + } +}); + +asyncHook.enable(); + +Promise + .resolve('a') + .catch(() => { + rejectedCalled = true; + }) + .then(arg => { + fulfilledCalled = true; + fulfilledArg = arg; + }); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid.length, 2, 'both handlers should init'); + assert.equal(preUid.length, 1, 'only the .then should pre'); + assert.equal(postUid.length, 1, 'only the .then should post'); + assert.equal(destroyUid.length, 2, 'both handlers should destroy'); + + assert.equal(initUid[0], destroyUid[0]); + + assert.equal(initUid[1], preUid[0]); + assert.equal(initUid[1], postUid[0]); + assert.equal(initUid[1], destroyUid[1]); + assert.equal(initHandle[1], preHandle[0]); + assert.equal(initHandle[1], postHandle[0]); + + for (let i = 0; i < 2; ++i) { + assert.equal(initHandle[i].constructor.name, 'PromiseWrap'); + assert.equal(initParent[i], null); + assert.equal(initProvider[i], 0); + } + + assert.equal(rejectedCalled, false); + assert.equal(fulfilledCalled, true); + assert.equal(fulfilledArg, 'a'); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-disabled.js b/node_modules/async-hook-jl/test/test-promise-disabled.js new file mode 100644 index 0000000..407b49c --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-disabled.js @@ -0,0 +1,72 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const thenHandlersCalledA = [false, false]; +const thenHandlersCalledB = [false, false]; +let catchHandlerCalledC = false; +let catchHandlerCalledD = false; + +let fulfilledArgA = null; +let rejectedArgB = null; +let rejectedArgC = null; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +Promise + .resolve('a') + .then(arg => { + fulfilledArgA = arg; + thenHandlersCalledA[0] = true; + }, () => { + thenHandlersCalledA[1] = true; + }); + +Promise + .reject('b') + .then(() => { + thenHandlersCalledB[0] = true; + }, arg => { + rejectedArgB = arg; + thenHandlersCalledB[1] = true; + }); + +Promise + .reject('c') + .catch(arg => { + rejectedArgC = arg; + catchHandlerCalledC = true; + }); + +Promise + .resolve('d') + .catch(() => { + catchHandlerCalledD = true; + }); + +process.once('exit', function () { + assert.deepStrictEqual(thenHandlersCalledA, [true, false]); + assert.equal(fulfilledArgA, 'a'); + assert.deepStrictEqual(thenHandlersCalledB, [false, true]); + assert.equal(rejectedArgB, 'b'); + assert.equal(catchHandlerCalledC, true); + assert.equal(rejectedArgC, 'c'); + assert.equal(catchHandlerCalledD, false); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-then-catch-chain-rejected-enabled.js b/node_modules/async-hook-jl/test/test-promise-then-catch-chain-rejected-enabled.js new file mode 100644 index 0000000..16e9ba3 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-then-catch-chain-rejected-enabled.js @@ -0,0 +1,81 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let fulfilledCalled = false; +let rejectedCalled = false; +let rejectedArg = null; + +const initUid = []; +const initHandle = []; +const initProvider = []; +const initParent = []; + +const preUid = []; +const preHandle = []; + +const postUid = []; +const postHandle = []; + +const destroyUid = []; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid.push(uid); + initHandle.push(handle); + initProvider.push(provider); + initParent.push(parent); + }, + pre: function (uid, handle) { + preUid.push(uid); + preHandle.push(handle); + }, + post: function (uid, handle) { + postUid.push(uid); + postHandle.push(handle); + }, + destroy: function (uid) { + destroyUid.push(uid); + } +}); + +asyncHook.enable(); + +Promise + .reject('a') + .then(() => { + fulfilledCalled = true; + }) + .catch(arg => { + rejectedCalled = true; + rejectedArg = arg; + }); + + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid.length, 2, 'both handlers should init'); + assert.equal(preUid.length, 1, 'only the .catch should pre'); + assert.equal(postUid.length, 1, 'only the .catch should post'); + assert.equal(destroyUid.length, 2, 'both handlers should destroy'); + + assert.equal(initUid[0], destroyUid[0]); + + assert.equal(initUid[1], preUid[0]); + assert.equal(initUid[1], postUid[0]); + assert.equal(initUid[1], destroyUid[1]); + assert.equal(initHandle[1], preHandle[0]); + assert.equal(initHandle[1], postHandle[0]); + + for (let i = 0; i < 2; ++i) { + assert.equal(initHandle[i].constructor.name, 'PromiseWrap'); + assert.equal(initParent[i], null); + assert.equal(initProvider[i], 0); + } + + assert.equal(fulfilledCalled, false); + assert.equal(rejectedCalled, true); + assert.equal(rejectedArg, 'a'); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-then-fulfilled-chained-enabled.js b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-chained-enabled.js new file mode 100644 index 0000000..f04db86 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-chained-enabled.js @@ -0,0 +1,80 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let fulfilledCalledA = false; +let fulfilledArgA = null; +let fulfilledCalledB = false; +let fulfilledArgB = null; + +const initUid = []; +const initHandle = []; +const initProvider = []; +const initParent = []; + +const preUid = []; +const preHandle = []; + +const postUid = []; +const postHandle = []; + +const destroyUid = []; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid.push(uid); + initHandle.push(handle); + initProvider.push(provider); + initParent.push(parent); + }, + pre: function (uid, handle) { + preUid.push(uid); + preHandle.push(handle); + }, + post: function (uid, handle) { + postUid.push(uid); + postHandle.push(handle); + }, + destroy: function (uid) { + destroyUid.push(uid); + } +}); + +asyncHook.enable(); + +Promise + .resolve('a') + .then(arg => { + fulfilledCalledA = true; + fulfilledArgA = arg; + return 'b'; + }) + .then(arg => { + fulfilledCalledB = true; + fulfilledArgB = arg; + }); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid.length, 2); + + for (let i = 0; i < 2; ++i) { + assert.equal(initUid[i], preUid[i]); + assert.equal(initUid[i], postUid[i]); + assert.equal(initUid[i], destroyUid[i]); + + assert.equal(initHandle[i], preHandle[i]); + assert.equal(initHandle[i], postHandle[i]); + + assert.equal(initHandle[i].constructor.name, 'PromiseWrap'); + assert.equal(initParent[i], null); + assert.equal(initProvider[i], 0); + } + + assert.equal(fulfilledCalledA, true); + assert.equal(fulfilledArgA, 'a'); + assert.equal(fulfilledCalledB, true); + assert.equal(fulfilledArgB, 'b'); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-then-fulfilled-enabled.js b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-enabled.js new file mode 100644 index 0000000..fa1f652 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-enabled.js @@ -0,0 +1,79 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let fulfilledCalled = false; +let fulfilledArg = null; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; +let postDidThrow = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle, didThrow) { + postUid = uid; + postHandle = handle; + postDidThrow = didThrow; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +Promise + .resolve('a') + .then(arg => { + fulfilledCalled = true; + fulfilledArg = arg; + }); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'PromiseWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(postDidThrow, false); + + assert.equal(fulfilledCalled, true); + assert.equal(fulfilledArg, 'a'); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-then-fulfilled-multiple-enabled.js b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-multiple-enabled.js new file mode 100644 index 0000000..c62e107 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-then-fulfilled-multiple-enabled.js @@ -0,0 +1,75 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const fulfilledCalled = []; +const fulfilledArg = []; + +const initUid = []; +const initHandle = []; +const initProvider = []; +const initParent = []; + +const preUid = []; +const preHandle = []; + +const postUid = []; +const postHandle = []; + +const destroyUid = []; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid.push(uid); + initHandle.push(handle); + initProvider.push(provider); + initParent.push(parent); + }, + pre: function (uid, handle) { + preUid.push(uid); + preHandle.push(handle); + }, + post: function (uid, handle) { + postUid.push(uid); + postHandle.push(handle); + }, + destroy: function (uid) { + destroyUid.push(uid); + } +}); + +asyncHook.enable(); + +const p = Promise.resolve('a'); + +p.then(arg => { + fulfilledCalled.push(true); + fulfilledArg.push(arg); +}); +p.then(arg => { + fulfilledCalled.push(true); + fulfilledArg.push(arg); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid.length, 2); + + for (let i = 0; i < 2; ++i) { + assert.equal(initUid[i], preUid[i]); + assert.equal(initUid[i], postUid[i]); + assert.equal(initUid[i], destroyUid[i]); + + assert.equal(initHandle[i], preHandle[i]); + assert.equal(initHandle[i], postHandle[i]); + + assert.equal(initHandle[i].constructor.name, 'PromiseWrap'); + assert.equal(initParent[i], null); + assert.equal(initProvider[i], 0); + + assert.equal(fulfilledCalled[i], true); + assert.equal(fulfilledArg[i], 'a'); + } +}); diff --git a/node_modules/async-hook-jl/test/test-promise-then-rejected-enabled.js b/node_modules/async-hook-jl/test/test-promise-then-rejected-enabled.js new file mode 100644 index 0000000..88157d0 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-then-rejected-enabled.js @@ -0,0 +1,75 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let rejectedCalled = false; +let rejectedArg = null; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle) { + postUid = uid; + postHandle = handle; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +Promise + .reject('a') + .then(null, arg => { + rejectedCalled = true; + rejectedArg = arg; + }); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'PromiseWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(rejectedCalled, true); + assert.equal(rejectedArg, 'a'); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-promise-timing.js b/node_modules/async-hook-jl/test/test-promise-timing.js new file mode 100644 index 0000000..eaede91 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-promise-timing.js @@ -0,0 +1,75 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const eventOrder = []; + +asyncHook.addHooks({ + init: function (uid, handle) { + eventOrder.push(`init#${uid} ${handle.constructor.name}`); + }, + pre: function (uid) { + eventOrder.push(`pre#${uid}`); + }, + post: function (uid) { + eventOrder.push(`post#${uid}`); + }, + destroy: function (uid) { + eventOrder.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); + +new Promise(function (s) { + setTimeout(s, 100); // 1 +}) +.then(function () { + return new Promise((s) => setTimeout(s, 100)); // 4 +}) +.then(); + +process.once('exit', function () { + const nodeMajor = parseInt(process.versions.node.split('.')[0], 10); + + if (nodeMajor >= 6) { + assert.deepEqual(eventOrder, [ + 'init#-1 TimeoutWrap', + 'init#-2 PromiseWrap', + 'init#-3 PromiseWrap', + 'pre#-1', + 'post#-1', + 'destroy#-1', + 'pre#-2', + 'init#-4 TimeoutWrap', + 'post#-2', + 'destroy#-2', + 'init#-5 PromiseWrap', + 'pre#-4', + 'post#-4', + 'destroy#-4', + 'pre#-5', + 'post#-5', + 'destroy#-5', + 'destroy#-3' + ]); + } else { + assert.deepEqual(eventOrder, [ + 'init#-1 TimeoutWrap', + 'init#-2 PromiseWrap', + 'init#-3 PromiseWrap', + 'pre#-1', + 'post#-1', + 'destroy#-1', + 'pre#-2', + 'init#-4 TimeoutWrap', + 'post#-2', + 'destroy#-2', + 'pre#-4', + 'post#-4', + 'destroy#-4', + 'destroy#-3' + ]); + } +}); diff --git a/node_modules/async-hook-jl/test/test-stackfilter-eval.js b/node_modules/async-hook-jl/test/test-stackfilter-eval.js new file mode 100644 index 0000000..3a05f19 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-stackfilter-eval.js @@ -0,0 +1,9 @@ +'use strict'; +const assert = require('assert'); + +require('../'); + +let e; +eval('(function() { e = new Error(); })()'); + +assert.equal(e.stack.split('\n').length, 10); diff --git a/node_modules/async-hook-jl/test/test-timeout-clear-in-callback.js b/node_modules/async-hook-jl/test/test-timeout-clear-in-callback.js new file mode 100644 index 0000000..efaf0a2 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-clear-in-callback.js @@ -0,0 +1,38 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const timings = []; + +asyncHook.addHooks({ + init: function (uid, handle) { + timings.push(`init#${uid} - ${handle.constructor.name}`); + }, + pre: function (uid) { + timings.push(`pre#${uid}`); + }, + post: function (uid) { + timings.push(`post#${uid}`); + }, + destroy: function (uid) { + timings.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); +const timerId = setTimeout(() => { + timings.push('callback'); + clearTimeout(timerId); +}, 100); +asyncHook.disable(); + +process.once('exit', function () { + assert.deepEqual(timings, [ + 'init#-1 - TimeoutWrap', + 'pre#-1', + 'callback', + 'post#-1', + 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-timeout-clear.js b/node_modules/async-hook-jl/test/test-timeout-clear.js new file mode 100644 index 0000000..ce73a58 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-clear.js @@ -0,0 +1,59 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandleName = ''; +let initParent = {}; +let initProvider = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandleName = handle.constructor.name; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +const timerId = setTimeout(function () { + timerCalled = true; +}); + +clearTimeout(timerId); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, destroyUid); + + assert.equal(initHandleName, 'TimeoutWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(timerCalled, false); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-timeout-didthrow.js b/node_modules/async-hook-jl/test/test-timeout-didthrow.js new file mode 100644 index 0000000..5098ef8 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-didthrow.js @@ -0,0 +1,46 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +const eventOrder = []; + +let throwFlag = null; + +asyncHook.addHooks({ + init: function (uid, handle) { + eventOrder.push(`init#${uid} ${handle.constructor.name}`); + }, + pre: function (uid) { + eventOrder.push(`pre#${uid}`); + }, + post: function (uid, handle, didThrow) { + throwFlag = didThrow; + eventOrder.push(`post#${uid}`); + }, + destroy: function (uid) { + eventOrder.push(`destroy#${uid}`); + } +}); + +asyncHook.enable(); + +process.once('uncaughtException', function () { + eventOrder.push('exception'); +}); + +setTimeout(function () { + eventOrder.push('callback'); + throw new Error('error'); +}); + +asyncHook.disable(); + +process.once('exit', function () { + assert.strictEqual(throwFlag, true); + assert.deepEqual(eventOrder, [ + 'init#-1 TimeoutWrap', 'pre#-1', + 'callback', 'exception', + 'post#-1', 'destroy#-1' + ]); +}); diff --git a/node_modules/async-hook-jl/test/test-timeout-disabled.js b/node_modules/async-hook-jl/test/test-timeout-disabled.js new file mode 100644 index 0000000..84d2e5a --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-disabled.js @@ -0,0 +1,42 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerACalled = false; +let timerBCalled = false; + +asyncHook.addHooks({ + init: function () { + assert(false); + }, + pre: function () { + assert(false); + }, + post: function () { + assert(false); + }, + destroy: function () { + assert(false); + } +}); + +asyncHook.enable(); +asyncHook.disable(); + +const timerId = setTimeout(function () { + timerACalled = true; +}); + +clearTimeout(timerId); + +setTimeout(function (arg1, arg2) { + timerBCalled = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 0, 'a', 'b'); + +process.once('exit', function () { + assert.equal(timerACalled, false); + assert.equal(timerBCalled, true); +}); diff --git a/node_modules/async-hook-jl/test/test-timeout-enabled.js b/node_modules/async-hook-jl/test/test-timeout-enabled.js new file mode 100644 index 0000000..f2be3cf --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-enabled.js @@ -0,0 +1,72 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +let timerCalled = false; + +let initCalls = 0; +let destroyCalls = 0; + +let initUid = NaN; +let initHandle = {}; +let initParent = {}; +let initProvider = NaN; + +let preHandle = {}; +let preUid = NaN; + +let postHandle = {}; +let postUid = NaN; + +let destroyUid = NaN; + +asyncHook.addHooks({ + init: function (uid, handle, provider, parent) { + initUid = uid; + initHandle = handle; + initParent = parent; + initProvider = provider; + + initCalls += 1; + }, + pre: function (uid, handle) { + preUid = uid; + preHandle = handle; + }, + post: function (uid, handle) { + postUid = uid; + postHandle = handle; + }, + destroy: function (uid) { + destroyUid = uid; + destroyCalls += 1; + } +}); + +asyncHook.enable(); + +setTimeout(function (arg1, arg2) { + timerCalled = true; + assert.equal(arg1, 'a'); + assert.equal(arg2, 'b'); +}, 0, 'a', 'b'); + +asyncHook.disable(); + +process.once('exit', function () { + assert.equal(initUid, preUid); + assert.equal(initUid, postUid); + assert.equal(initUid, destroyUid); + + assert.equal(initHandle, preHandle); + assert.equal(initHandle, postHandle); + + assert.equal(initHandle.constructor.name, 'TimeoutWrap'); + assert.equal(initParent, null); + assert.equal(initProvider, 0); + + assert.equal(timerCalled, true); + assert.equal(initCalls, 1); + assert.equal(destroyCalls, 1); +}); diff --git a/node_modules/async-hook-jl/test/test-timeout-exception.js b/node_modules/async-hook-jl/test/test-timeout-exception.js new file mode 100644 index 0000000..b2eb0b3 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-exception.js @@ -0,0 +1,32 @@ +'use strict'; + +if (process.env.hasOwnProperty('ASYNC_HOOK_TEST_CHILD')) { + const asyncHook = require('../'); + + asyncHook.enable(); + + setTimeout(function () { + throw new Error('test error'); + }); +} else { + const spawn = require('child_process').spawn; + const endpoint = require('endpoint'); + + const child = spawn(process.execPath, [__filename], { + env: Object.assign({ ASYNC_HOOK_TEST_CHILD: '' }, process.env), + stdio: ['ignore', 1, 'pipe'] + }); + + let stderr = null; + child.stderr.pipe(endpoint(function (err, _stderr) { + if (err) throw err; + stderr = _stderr; + })); + + child.once('close', function (statusCode) { + if (statusCode !== 1 || stderr.toString().indexOf('test error') === -1) { + process.stderr.write(stderr); + process.exit(statusCode); + } + }); +} diff --git a/node_modules/async-hook-jl/test/test-timeout-non-function.js b/node_modules/async-hook-jl/test/test-timeout-non-function.js new file mode 100644 index 0000000..8696874 --- /dev/null +++ b/node_modules/async-hook-jl/test/test-timeout-non-function.js @@ -0,0 +1,21 @@ +'use strict'; + +const asyncHook = require('../'); +const assert = require('assert'); + +asyncHook.enable(); + +let throws = false; +try { + setTimeout(undefined, 1); +} catch (e) { + assert.equal(e.message, '"callback" argument must be a function'); + assert.equal(e.name, 'TypeError'); + throws = true; +} + +asyncHook.disable(); + +process.once('exit', function () { + assert(throws); +}); diff --git a/node_modules/async-hook-jl/yarn.lock b/node_modules/async-hook-jl/yarn.lock new file mode 100644 index 0000000..39ac691 --- /dev/null +++ b/node_modules/async-hook-jl/yarn.lock @@ -0,0 +1,900 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +acorn-jsx@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-3.0.1.tgz#afdf9488fb1ecefc8348f6fb22f464e32a58b36b" + dependencies: + acorn "^3.0.4" + +acorn@^3.0.4: + version "3.3.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" + +acorn@^5.0.1: + version "5.0.3" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.0.3.tgz#c460df08491463f028ccb82eab3730bf01087b3d" + +ajv-keywords@^1.0.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-1.5.1.tgz#314dd0a4b3368fad3dfcdc54ede6171b886daf3c" + +ajv@^4.7.0: + version "4.11.8" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.11.8.tgz#82ffb02b29e662ae53bdc20af15947706739c536" + dependencies: + co "^4.6.0" + json-stable-stringify "^1.0.1" + +ansi-escapes@^1.1.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" + +ansi-regex@2, ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + +argparse@^1.0.7: + version "1.0.9" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" + dependencies: + sprintf-js "~1.0.2" + +array-union@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" + dependencies: + array-uniq "^1.0.1" + +array-uniq@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" + +arrify@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" + +async@1.5.x: + version "1.5.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" + +babel-code-frame@^6.16.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.22.0.tgz#027620bee567a88c32561574e7fd0801d33118e4" + dependencies: + chalk "^1.1.0" + esutils "^2.0.2" + js-tokens "^3.0.0" + +balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + +brace-expansion@^1.1.7: + version "1.1.8" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292" + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +caller-path@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-0.1.0.tgz#94085ef63581ecd3daa92444a8fe94e82577751f" + dependencies: + callsites "^0.2.0" + +callsites@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" + +chalk@^1.0.0, chalk@^1.1.0, chalk@^1.1.1, chalk@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +circular-json@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.1.tgz#be8b36aefccde8b3ca7aa2d6afc07a37242c0d2d" + +cli-color@1.1.x: + version "1.1.0" + resolved "https://registry.yarnpkg.com/cli-color/-/cli-color-1.1.0.tgz#de188cdc4929d83b67aea04110fbed40fdbf6775" + dependencies: + ansi-regex "2" + d "^0.1.1" + es5-ext "^0.10.8" + es6-iterator "2" + memoizee "^0.3.9" + timers-ext "0.1" + +cli-cursor@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-1.0.2.tgz#64da3f7d56a54412e59794bd62dc35295e8f2987" + dependencies: + restore-cursor "^1.0.1" + +cli-width@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.1.0.tgz#b234ca209b29ef66fc518d9b98d5847b00edf00a" + +co@^4.6.0: + version "4.6.0" + resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" + +code-point-at@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + +concat-stream@^1.5.2: + version "1.6.0" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.0.tgz#0aac662fd52be78964d5532f694784e70110acf7" + dependencies: + inherits "^2.0.3" + readable-stream "^2.2.2" + typedarray "^0.0.6" + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + +d@1: + version "1.0.0" + resolved "https://registry.yarnpkg.com/d/-/d-1.0.0.tgz#754bb5bfe55451da69a58b94d45f4c5b0462d58f" + dependencies: + es5-ext "^0.10.9" + +d@^0.1.1, d@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/d/-/d-0.1.1.tgz#da184c535d18d8ee7ba2aa229b914009fae11309" + dependencies: + es5-ext "~0.10.2" + +debug@^2.1.1: + version "2.6.8" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.8.tgz#e731531ca2ede27d188222427da17821d68ff4fc" + dependencies: + ms "2.0.0" + +deep-is@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" + +del@^2.0.2: + version "2.2.2" + resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" + dependencies: + globby "^5.0.0" + is-path-cwd "^1.0.0" + is-path-in-cwd "^1.0.0" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + rimraf "^2.2.8" + +doctrine@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.0.0.tgz#c73d8d2909d22291e1a007a395804da8b665fe63" + dependencies: + esutils "^2.0.2" + isarray "^1.0.0" + +endpoint@0.4.x: + version "0.4.5" + resolved "https://registry.yarnpkg.com/endpoint/-/endpoint-0.4.5.tgz#8a32db66ad94c3161d279ed1ab4ffb6c4101b79a" + dependencies: + inherits "^2.0.1" + +es5-ext@^0.10.14, es5-ext@^0.10.8, es5-ext@^0.10.9, es5-ext@~0.10.11, es5-ext@~0.10.14, es5-ext@~0.10.2, es5-ext@~0.10.5, es5-ext@~0.10.6: + version "0.10.23" + resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.23.tgz#7578b51be974207a5487821b56538c224e4e7b38" + dependencies: + es6-iterator "2" + es6-symbol "~3.1" + +es6-iterator@2, es6-iterator@^2.0.1, es6-iterator@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.1.tgz#8e319c9f0453bf575d374940a655920e59ca5512" + dependencies: + d "1" + es5-ext "^0.10.14" + es6-symbol "^3.1" + +es6-iterator@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-0.1.3.tgz#d6f58b8c4fc413c249b4baa19768f8e4d7c8944e" + dependencies: + d "~0.1.1" + es5-ext "~0.10.5" + es6-symbol "~2.0.1" + +es6-map@^0.1.3: + version "0.1.5" + resolved "https://registry.yarnpkg.com/es6-map/-/es6-map-0.1.5.tgz#9136e0503dcc06a301690f0bb14ff4e364e949f0" + dependencies: + d "1" + es5-ext "~0.10.14" + es6-iterator "~2.0.1" + es6-set "~0.1.5" + es6-symbol "~3.1.1" + event-emitter "~0.3.5" + +es6-set@~0.1.5: + version "0.1.5" + resolved "https://registry.yarnpkg.com/es6-set/-/es6-set-0.1.5.tgz#d2b3ec5d4d800ced818db538d28974db0a73ccb1" + dependencies: + d "1" + es5-ext "~0.10.14" + es6-iterator "~2.0.1" + es6-symbol "3.1.1" + event-emitter "~0.3.5" + +es6-symbol@3.1.1, es6-symbol@^3.1, es6-symbol@^3.1.1, es6-symbol@~3.1, es6-symbol@~3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.1.tgz#bf00ef4fdab6ba1b46ecb7b629b4c7ed5715cc77" + dependencies: + d "1" + es5-ext "~0.10.14" + +es6-symbol@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-2.0.1.tgz#761b5c67cfd4f1d18afb234f691d678682cb3bf3" + dependencies: + d "~0.1.1" + es5-ext "~0.10.5" + +es6-weak-map@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.2.tgz#5e3ab32251ffd1538a1f8e5ffa1357772f92d96f" + dependencies: + d "1" + es5-ext "^0.10.14" + es6-iterator "^2.0.1" + es6-symbol "^3.1.1" + +es6-weak-map@~0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-0.1.4.tgz#706cef9e99aa236ba7766c239c8b9e286ea7d228" + dependencies: + d "~0.1.1" + es5-ext "~0.10.6" + es6-iterator "~0.1.3" + es6-symbol "~2.0.1" + +escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + +escope@^3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/escope/-/escope-3.6.0.tgz#e01975e812781a163a6dadfdd80398dc64c889c3" + dependencies: + es6-map "^0.1.3" + es6-weak-map "^2.0.1" + esrecurse "^4.1.0" + estraverse "^4.1.1" + +eslint@^3.4.0: + version "3.19.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-3.19.0.tgz#c8fc6201c7f40dd08941b87c085767386a679acc" + dependencies: + babel-code-frame "^6.16.0" + chalk "^1.1.3" + concat-stream "^1.5.2" + debug "^2.1.1" + doctrine "^2.0.0" + escope "^3.6.0" + espree "^3.4.0" + esquery "^1.0.0" + estraverse "^4.2.0" + esutils "^2.0.2" + file-entry-cache "^2.0.0" + glob "^7.0.3" + globals "^9.14.0" + ignore "^3.2.0" + imurmurhash "^0.1.4" + inquirer "^0.12.0" + is-my-json-valid "^2.10.0" + is-resolvable "^1.0.0" + js-yaml "^3.5.1" + json-stable-stringify "^1.0.0" + levn "^0.3.0" + lodash "^4.0.0" + mkdirp "^0.5.0" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.1" + pluralize "^1.2.1" + progress "^1.1.8" + require-uncached "^1.0.2" + shelljs "^0.7.5" + strip-bom "^3.0.0" + strip-json-comments "~2.0.1" + table "^3.7.8" + text-table "~0.2.0" + user-home "^2.0.0" + +espree@^3.4.0: + version "3.4.3" + resolved "https://registry.yarnpkg.com/espree/-/espree-3.4.3.tgz#2910b5ccd49ce893c2ffffaab4fd8b3a31b82374" + dependencies: + acorn "^5.0.1" + acorn-jsx "^3.0.0" + +esprima@^3.1.1: + version "3.1.3" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633" + +esquery@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.0.tgz#cfba8b57d7fba93f17298a8a006a04cda13d80fa" + dependencies: + estraverse "^4.0.0" + +esrecurse@^4.1.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.0.tgz#fa9568d98d3823f9a41d91e902dcab9ea6e5b163" + dependencies: + estraverse "^4.1.0" + object-assign "^4.0.1" + +estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1, estraverse@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" + +esutils@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" + +event-emitter@~0.3.4, event-emitter@~0.3.5: + version "0.3.5" + resolved "https://registry.yarnpkg.com/event-emitter/-/event-emitter-0.3.5.tgz#df8c69eef1647923c7157b9ce83840610b02cc39" + dependencies: + d "1" + es5-ext "~0.10.14" + +exit-hook@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8" + +fast-levenshtein@~2.0.4: + version "2.0.6" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" + +figures@^1.3.5: + version "1.7.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" + dependencies: + escape-string-regexp "^1.0.5" + object-assign "^4.1.0" + +file-entry-cache@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-2.0.0.tgz#c392990c3e684783d838b8c84a45d8a048458361" + dependencies: + flat-cache "^1.2.1" + object-assign "^4.0.1" + +flat-cache@^1.2.1: + version "1.2.2" + resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.2.2.tgz#fa86714e72c21db88601761ecf2f555d1abc6b96" + dependencies: + circular-json "^0.3.1" + del "^2.0.2" + graceful-fs "^4.1.2" + write "^0.2.1" + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + +generate-function@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/generate-function/-/generate-function-2.0.0.tgz#6858fe7c0969b7d4e9093337647ac79f60dfbe74" + +generate-object-property@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/generate-object-property/-/generate-object-property-1.2.0.tgz#9c0e1c40308ce804f4783618b937fa88f99d50d0" + dependencies: + is-property "^1.0.0" + +glob@^7.0.0, glob@^7.0.3, glob@^7.0.5: + version "7.1.2" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^9.14.0: + version "9.18.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" + +globby@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" + dependencies: + array-union "^1.0.1" + arrify "^1.0.0" + glob "^7.0.3" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + +graceful-fs@^4.1.2: + version "4.1.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + dependencies: + ansi-regex "^2.0.0" + +ignore@^3.2.0: + version "3.3.3" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.3.tgz#432352e57accd87ab3110e82d3fea0e47812156d" + +imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" + +inquirer@^0.12.0: + version "0.12.0" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-0.12.0.tgz#1ef2bfd63504df0bc75785fff8c2c41df12f077e" + dependencies: + ansi-escapes "^1.1.0" + ansi-regex "^2.0.0" + chalk "^1.0.0" + cli-cursor "^1.0.1" + cli-width "^2.0.0" + figures "^1.3.5" + lodash "^4.3.0" + readline2 "^1.0.1" + run-async "^0.1.0" + rx-lite "^3.1.2" + string-width "^1.0.1" + strip-ansi "^3.0.0" + through "^2.3.6" + +interpret@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.0.3.tgz#cbc35c62eeee73f19ab7b10a801511401afc0f90" + +is-fullwidth-code-point@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" + dependencies: + number-is-nan "^1.0.0" + +is-fullwidth-code-point@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" + +is-my-json-valid@^2.10.0: + version "2.16.0" + resolved "https://registry.yarnpkg.com/is-my-json-valid/-/is-my-json-valid-2.16.0.tgz#f079dd9bfdae65ee2038aae8acbc86ab109e3693" + dependencies: + generate-function "^2.0.0" + generate-object-property "^1.1.0" + jsonpointer "^4.0.0" + xtend "^4.0.0" + +is-path-cwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" + +is-path-in-cwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.0.tgz#6477582b8214d602346094567003be8a9eac04dc" + dependencies: + is-path-inside "^1.0.0" + +is-path-inside@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.0.tgz#fc06e5a1683fbda13de667aff717bbc10a48f37f" + dependencies: + path-is-inside "^1.0.1" + +is-property@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-property/-/is-property-1.0.2.tgz#57fe1c4e48474edd65b09911f26b1cd4095dda84" + +is-resolvable@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.0.0.tgz#8df57c61ea2e3c501408d100fb013cf8d6e0cc62" + dependencies: + tryit "^1.0.1" + +isarray@^1.0.0, isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + +js-tokens@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.1.tgz#08e9f132484a2c45a30907e9dc4d5567b7f114d7" + +js-yaml@^3.5.1: + version "3.8.4" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.8.4.tgz#520b4564f86573ba96662af85a8cafa7b4b5a6f6" + dependencies: + argparse "^1.0.7" + esprima "^3.1.1" + +json-stable-stringify@^1.0.0, json-stable-stringify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" + dependencies: + jsonify "~0.0.0" + +jsonify@~0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" + +jsonpointer@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9" + +levn@^0.3.0, levn@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" + dependencies: + prelude-ls "~1.1.2" + type-check "~0.3.2" + +lodash@^4.0.0, lodash@^4.3.0: + version "4.17.4" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" + +lru-queue@0.1: + version "0.1.0" + resolved "https://registry.yarnpkg.com/lru-queue/-/lru-queue-0.1.0.tgz#2738bd9f0d3cf4f84490c5736c48699ac632cda3" + dependencies: + es5-ext "~0.10.2" + +memoizee@^0.3.9: + version "0.3.10" + resolved "https://registry.yarnpkg.com/memoizee/-/memoizee-0.3.10.tgz#4eca0d8aed39ec9d017f4c5c2f2f6432f42e5c8f" + dependencies: + d "~0.1.1" + es5-ext "~0.10.11" + es6-weak-map "~0.1.4" + event-emitter "~0.3.4" + lru-queue "0.1" + next-tick "~0.2.2" + timers-ext "0.1" + +minimatch@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + dependencies: + brace-expansion "^1.1.7" + +minimist@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" + +mkdirp@^0.5.0, mkdirp@^0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" + dependencies: + minimist "0.0.8" + +ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + +mute-stream@0.0.5: + version "0.0.5" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.5.tgz#8fbfabb0a98a253d3184331f9e8deb7372fac6c0" + +natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" + +next-tick@1: + version "1.0.0" + resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz#ca86d1fe8828169b0120208e3dc8424b9db8342c" + +next-tick@~0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-0.2.2.tgz#75da4a927ee5887e39065880065b7336413b310d" + +number-is-nan@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + +object-assign@^4.0.1, object-assign@^4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + dependencies: + wrappy "1" + +onetime@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-1.1.0.tgz#a1f7838f8314c516f05ecefcbc4ccfe04b4ed789" + +optionator@^0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" + dependencies: + deep-is "~0.1.3" + fast-levenshtein "~2.0.4" + levn "~0.3.0" + prelude-ls "~1.1.2" + type-check "~0.3.2" + wordwrap "~1.0.0" + +os-homedir@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + +path-is-inside@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" + +path-parse@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" + +pify@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + +pinkie-promise@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + dependencies: + pinkie "^2.0.0" + +pinkie@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + +pluralize@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-1.2.1.tgz#d1a21483fd22bb41e58a12fa3421823140897c45" + +prelude-ls@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" + +process-nextick-args@~1.0.6: + version "1.0.7" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3" + +progress@^1.1.8: + version "1.1.8" + resolved "https://registry.yarnpkg.com/progress/-/progress-1.1.8.tgz#e260c78f6161cdd9b0e56cc3e0a85de17c7a57be" + +readable-stream@^2.2.2: + version "2.3.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.2.tgz#5a04df05e4f57fe3f0dc68fdd11dc5c97c7e6f4d" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~1.0.6" + safe-buffer "~5.1.0" + string_decoder "~1.0.0" + util-deprecate "~1.0.1" + +readline2@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/readline2/-/readline2-1.0.1.tgz#41059608ffc154757b715d9989d199ffbf372e35" + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + mute-stream "0.0.5" + +rechoir@^0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" + dependencies: + resolve "^1.1.6" + +require-uncached@^1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" + dependencies: + caller-path "^0.1.0" + resolve-from "^1.0.0" + +resolve-from@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226" + +resolve@^1.1.6: + version "1.3.3" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.3.3.tgz#655907c3469a8680dc2de3a275a8fdd69691f0e5" + dependencies: + path-parse "^1.0.5" + +restore-cursor@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-1.0.1.tgz#34661f46886327fed2991479152252df92daa541" + dependencies: + exit-hook "^1.0.0" + onetime "^1.0.0" + +rimraf@^2.2.8: + version "2.6.1" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.1.tgz#c2338ec643df7a1b7fe5c54fa86f57428a55f33d" + dependencies: + glob "^7.0.5" + +run-async@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/run-async/-/run-async-0.1.0.tgz#c8ad4a5e110661e402a7d21b530e009f25f8e389" + dependencies: + once "^1.3.0" + +rx-lite@^3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-3.1.2.tgz#19ce502ca572665f3b647b10939f97fd1615f102" + +safe-buffer@~5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853" + +shelljs@^0.7.5: + version "0.7.8" + resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.8.tgz#decbcf874b0d1e5fb72e14b164a9683048e9acb3" + dependencies: + glob "^7.0.0" + interpret "^1.0.0" + rechoir "^0.6.2" + +slice-ansi@0.0.4: + version "0.0.4" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-0.0.4.tgz#edbf8903f66f7ce2f8eafd6ceed65e264c831b35" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + +stack-chain@^1.3.7: + version "1.3.7" + resolved "https://registry.yarnpkg.com/stack-chain/-/stack-chain-1.3.7.tgz#d192c9ff4ea6a22c94c4dd459171e3f00cea1285" + +string-width@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + strip-ansi "^3.0.0" + +string-width@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.0.0.tgz#635c5436cc72a6e0c387ceca278d4e2eec52687e" + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^3.0.0" + +string_decoder@~1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab" + dependencies: + safe-buffer "~5.1.0" + +strip-ansi@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + dependencies: + ansi-regex "^2.0.0" + +strip-bom@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" + +strip-json-comments@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + +table@^3.7.8: + version "3.8.3" + resolved "https://registry.yarnpkg.com/table/-/table-3.8.3.tgz#2bbc542f0fda9861a755d3947fefd8b3f513855f" + dependencies: + ajv "^4.7.0" + ajv-keywords "^1.0.0" + chalk "^1.1.1" + lodash "^4.0.0" + slice-ansi "0.0.4" + string-width "^2.0.0" + +text-table@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" + +through@^2.3.6: + version "2.3.8" + resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" + +timers-ext@0.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/timers-ext/-/timers-ext-0.1.2.tgz#61cc47a76c1abd3195f14527f978d58ae94c5204" + dependencies: + es5-ext "~0.10.14" + next-tick "1" + +tryit@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/tryit/-/tryit-1.0.3.tgz#393be730a9446fd1ead6da59a014308f36c289cb" + +type-check@~0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" + dependencies: + prelude-ls "~1.1.2" + +typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + +user-home@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/user-home/-/user-home-2.0.0.tgz#9c70bfd8169bc1dcbf48604e0f04b8b49cde9e9f" + dependencies: + os-homedir "^1.0.0" + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + +wordwrap@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + +write@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757" + dependencies: + mkdirp "^0.5.1" + +xtend@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af" diff --git a/node_modules/async-listener/.travis.yml b/node_modules/async-listener/.travis.yml new file mode 100644 index 0000000..136c607 --- /dev/null +++ b/node_modules/async-listener/.travis.yml @@ -0,0 +1,23 @@ +language: node_js + +cache: + directories: + - node_modules + +node_js: + - "9" + - "8" + - "7" + - "7.9.0" + - "6" + - "5" + - "4" + - "3" + - "0.12" + - "0.10" + +matrix: + allow_failures: + - node_js: '7' + +sudo: false diff --git a/node_modules/async-listener/LICENSE b/node_modules/async-listener/LICENSE new file mode 100644 index 0000000..46a677b --- /dev/null +++ b/node_modules/async-listener/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2013-2017, Forrest L Norvell +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/async-listener/README.md b/node_modules/async-listener/README.md new file mode 100644 index 0000000..21a5a00 --- /dev/null +++ b/node_modules/async-listener/README.md @@ -0,0 +1,55 @@ +[![NPM](https://nodei.co/npm/async-listener.png?downloads=true&stars=true)](https://nodei.co/npm/async-listener/) + +[![Build status](https://travis-ci.org/othiym23/async-listener.svg?branch=master)](https://travis-ci.org/othiym23/async-listener) + +# process.addAsyncListener polyfill + +This is an implementation of Trevor Norris's +process.{addAsyncListener,removeAsyncListener} API for adding behavior to async +calls. You can see his implementation (currently a work in progress) on +[Node.js core pull request #6011](https://github.com/joyent/node/pull/6011). +This polyfill / shim is intended for use in versions of Node prior to whatever +version of Node in which Trevor's changes finally land (anticipated at the time +of this writing as 0.11.7). + +Here's his documentation of the intended API, which will probably get cleaned up +here later: + +## createAsyncListener(callbacks[, initialStorage]) + +* `callbacks` {Object} +* `initialStorage` {Value} + +Returns a constructed `AsyncListener` object. Which can then be passed to +`process.addAsyncListener()` and `process.removeAsyncListener()`. Each +function parameter is as follows: + +1. `callbacks`: An `Object` which may contain four optional fields: + * `create`: A `function (storage)` that is called when an asynchronous event + is queued. Recives the `storage` attached to the listener. `storage` can be + created by passing an `initialStorage` argument during construction, or by + returning a `Value` from `create` which will be attached to the listener + and overwrite the `initialStorage`. + * `before`: A `function (context, storage)` that is called immediately + before the asynchronous callback is about to run. It will be passed both + the `context` (i.e. `this`) of the calling function and the `storage`. + * `after`: A `function (context, storage)` called immediately after the + asynchronous event's callback is run. Note that if the event's callback + throws during execution this will not be called. + * `error`: A `function (storage, error)` called if the event's callback + threw. If `error` returns `true` then Node will assume the error has been + properly handled and resume execution normally. +1. `initialStorage`: A `Value` (i.e. anything) that will be, by default, + attached to all new event instances. This will be overwritten if a `Value` + is returned by `create()`. + + +## addAsyncListener(callbacks[, initialStorage]) +## addAsyncListener(asyncListener) + +Returns a constructed `AsyncListener` object and immediately adds it to the +listening queue. + +## removeAsyncListener(asyncListener) + +Removes the `asyncListener` from the listening queue. diff --git a/node_modules/async-listener/es6-wrapped-promise.js b/node_modules/async-listener/es6-wrapped-promise.js new file mode 100644 index 0000000..577b33d --- /dev/null +++ b/node_modules/async-listener/es6-wrapped-promise.js @@ -0,0 +1,37 @@ +'use strict'; + +module.exports = (Promise, ensureAslWrapper) => { + // Updates to this class should also be applied to the the ES3 version + // in index.js. + return class WrappedPromise extends Promise { + constructor(executor) { + var context, args; + super(wrappedExecutor); + var promise = this; + + try { + executor.apply(context, args); + } catch (err) { + args[1](err); + } + + return promise; + function wrappedExecutor(resolve, reject) { + context = this; + args = [wrappedResolve, wrappedReject]; + + // These wrappers create a function that can be passed a function and an argument to + // call as a continuation from the resolve or reject. + function wrappedResolve(val) { + ensureAslWrapper(promise, false); + return resolve(val); + } + + function wrappedReject(val) { + ensureAslWrapper(promise, false); + return reject(val); + } + } + } + } +}; diff --git a/node_modules/async-listener/glue.js b/node_modules/async-listener/glue.js new file mode 100644 index 0000000..152e513 --- /dev/null +++ b/node_modules/async-listener/glue.js @@ -0,0 +1,488 @@ +var wrap = require('shimmer').wrap; + +/* + * + * CONSTANTS + * + */ +var HAS_CREATE_AL = 1 << 0; +var HAS_BEFORE_AL = 1 << 1; +var HAS_AFTER_AL = 1 << 2; +var HAS_ERROR_AL = 1 << 3; + +/** + * There is one list of currently active listeners that is mutated in place by + * addAsyncListener and removeAsyncListener. This complicates error-handling, + * for reasons that are discussed below. + */ +var listeners = []; + +/** + * There can be multiple listeners with the same properties, so disambiguate + * them by assigning them an ID at creation time. + */ +var uid = 0; + +/** + * Ensure that errors coming from within listeners are handed off to domains, + * process._fatalException, or uncaughtException without being treated like + * user errors. + */ +var inAsyncTick = false; + +/** + * Because asynchronous contexts can be nested, and errors can come from anywhere + * in the stack, a little extra work is required to keep track of where in the + * nesting we are. Because JS arrays are frequently mutated in place + */ +var listenerStack = []; + +/** + * The error handler on a listener can capture errors thrown during synchronous + * execution immediately after the listener is added. To capture both + * synchronous and asynchronous errors, the error handler just uses the + * "global" list of active listeners, and the rest of the code ensures that the + * listener list is correct by using a stack of listener lists during + * asynchronous execution. + */ +var asyncCatcher; + +/** + * The guts of the system -- called each time an asynchronous event happens + * while one or more listeners are active. + */ +var asyncWrap; + +/** + * Simple helper function that's probably faster than using Array + * filter methods and can be inlined. + */ +function union(dest, added) { + var destLength = dest.length; + var addedLength = added.length; + var returned = []; + + if (destLength === 0 && addedLength === 0) return returned; + + for (var j = 0; j < destLength; j++) returned[j] = dest[j]; + + if (addedLength === 0) return returned; + + for (var i = 0; i < addedLength; i++) { + var missing = true; + for (j = 0; j < destLength; j++) { + if (dest[j].uid === added[i].uid) { + missing = false; + break; + } + } + if (missing) returned.push(added[i]); + } + + return returned; +} + +/* + * For performance, split error-handlers and asyncCatcher up into two separate + * code paths. + */ + +// 0.9+ +if (process._fatalException) { + /** + * Error handlers on listeners can throw, the catcher needs to be able to + * discriminate between exceptions thrown by user code, and exceptions coming + * from within the catcher itself. Use a global to keep track of which state + * the catcher is currently in. + */ + var inErrorTick = false; + + /** + * Throwing always happens synchronously. If the current array of values for + * the current list of asyncListeners is put in a module-scoped variable right + * before a call that can throw, it will always be correct when the error + * handlers are run. + */ + var errorValues; + + asyncCatcher = function asyncCatcher(er) { + var length = listeners.length; + if (inErrorTick || length === 0) return false; + + var handled = false; + + /* + * error handlers + */ + inErrorTick = true; + for (var i = 0; i < length; ++i) { + var listener = listeners[i]; + if ((listener.flags & HAS_ERROR_AL) === 0) continue; + + var value = errorValues && errorValues[listener.uid]; + handled = listener.error(value, er) || handled; + } + inErrorTick = false; + + /* Test whether there are any listener arrays on the stack. In the case of + * synchronous throws when the listener is active, there may have been + * none pushed yet. + */ + if (listenerStack.length > 0) listeners = listenerStack.pop(); + errorValues = undefined; + + return handled && !inAsyncTick; + }; + + asyncWrap = function asyncWrap(original, list, length) { + var values = []; + + /* + * listeners + */ + inAsyncTick = true; + for (var i = 0; i < length; ++i) { + var listener = list[i]; + values[listener.uid] = listener.data; + + if ((listener.flags & HAS_CREATE_AL) === 0) continue; + + var value = listener.create(listener.data); + if (value !== undefined) values[listener.uid] = value; + } + inAsyncTick = false; + + /* One of the main differences between this polyfill and the core + * asyncListener support is that core avoids creating closures by putting a + * lot of the state managemnt on the C++ side of Node (and of course also it + * bakes support for async listeners into the Node C++ API through the + * AsyncWrap class, which means that it doesn't monkeypatch basically every + * async method like this does). + */ + return function () { + // put the current values where the catcher can see them + errorValues = values; + + /* More than one listener can end up inside these closures, so save the + * current listeners on a stack. + */ + listenerStack.push(listeners); + + /* Activate both the listeners that were active when the closure was + * created and the listeners that were previously active. + */ + listeners = union(list, listeners); + + /* + * before handlers + */ + inAsyncTick = true; + for (var i = 0; i < length; ++i) { + if ((list[i].flags & HAS_BEFORE_AL) > 0) { + list[i].before(this, values[list[i].uid]); + } + } + inAsyncTick = false; + + // save the return value to pass to the after callbacks + var returned = original.apply(this, arguments); + + /* + * after handlers (not run if original throws) + */ + inAsyncTick = true; + for (i = 0; i < length; ++i) { + if ((list[i].flags & HAS_AFTER_AL) > 0) { + list[i].after(this, values[list[i].uid]); + } + } + inAsyncTick = false; + + // back to the previous listener list on the stack + listeners = listenerStack.pop(); + errorValues = undefined; + + return returned; + }; + }; + + wrap(process, '_fatalException', function (_fatalException) { + return function _asyncFatalException(er) { + return asyncCatcher(er) || _fatalException(er); + }; + }); +} +// 0.8 and below +else { + /** + * If an error handler in asyncWrap throws, the process must die. Under 0.8 + * and earlier the only way to put a bullet through the head of the process + * is to rethrow from inside the exception handler, so rethrow and set + * errorThrew to tell the uncaughtHandler what to do. + */ + var errorThrew = false; + + /** + * Under Node 0.8, this handler *only* handles synchronously thrown errors. + * This simplifies it, which almost but not quite makes up for the hit taken + * by putting everything in a try-catch. + */ + asyncCatcher = function uncaughtCatcher(er) { + // going down hard + if (errorThrew) throw er; + + var handled = false; + + /* + * error handlers + */ + var length = listeners.length; + for (var i = 0; i < length; ++i) { + var listener = listeners[i]; + if ((listener.flags & HAS_ERROR_AL) === 0) continue; + handled = listener.error(null, er) || handled; + } + + /* Rethrow if one of the before / after handlers fire, which will bring the + * process down immediately. + */ + if (!handled && inAsyncTick) throw er; + }; + + asyncWrap = function asyncWrap(original, list, length) { + var values = []; + + /* + * listeners + */ + inAsyncTick = true; + for (var i = 0; i < length; ++i) { + var listener = list[i]; + values[listener.uid] = listener.data; + + if ((listener.flags & HAS_CREATE_AL) === 0) continue; + + var value = listener.create(listener.data); + if (value !== undefined) values[listener.uid] = value; + } + inAsyncTick = false; + + /* One of the main differences between this polyfill and the core + * asyncListener support is that core avoids creating closures by putting a + * lot of the state managemnt on the C++ side of Node (and of course also it + * bakes support for async listeners into the Node C++ API through the + * AsyncWrap class, which means that it doesn't monkeypatch basically every + * async method like this does). + */ + return function () { + /*jshint maxdepth:4*/ + + // after() handlers don't run if threw + var threw = false; + + // ...unless the error is handled + var handled = false; + + /* More than one listener can end up inside these closures, so save the + * current listeners on a stack. + */ + listenerStack.push(listeners); + + /* Activate both the listeners that were active when the closure was + * created and the listeners that were previously active. + */ + listeners = union(list, listeners); + + /* + * before handlers + */ + inAsyncTick = true; + for (var i = 0; i < length; ++i) { + if ((list[i].flags & HAS_BEFORE_AL) > 0) { + list[i].before(this, values[list[i].uid]); + } + } + inAsyncTick = false; + + // save the return value to pass to the after callbacks + var returned; + try { + returned = original.apply(this, arguments); + } + catch (er) { + threw = true; + for (var i = 0; i < length; ++i) { + if ((listeners[i].flags & HAS_ERROR_AL) == 0) continue; + try { + handled = listeners[i].error(values[list[i].uid], er) || handled; + } + catch (x) { + errorThrew = true; + throw x; + } + } + + if (!handled) { + // having an uncaughtException handler here alters crash semantics + process.removeListener('uncaughtException', asyncCatcher); + process._originalNextTick(function () { + process.addListener('uncaughtException', asyncCatcher); + }); + + throw er; + } + } + finally { + /* + * after handlers (not run if original throws) + */ + if (!threw || handled) { + inAsyncTick = true; + for (i = 0; i < length; ++i) { + if ((list[i].flags & HAS_AFTER_AL) > 0) { + list[i].after(this, values[list[i].uid]); + } + } + inAsyncTick = false; + } + + // back to the previous listener list on the stack + listeners = listenerStack.pop(); + } + + + return returned; + }; + }; + + // will be the first to fire if async-listener is the first module loaded + process.addListener('uncaughtException', asyncCatcher); +} + +// for performance in the case where there are no handlers, just the listener +function simpleWrap(original, list, length) { + inAsyncTick = true; + for (var i = 0; i < length; ++i) { + var listener = list[i]; + if (listener.create) listener.create(listener.data); + } + inAsyncTick = false; + + // still need to make sure nested async calls are made in the context + // of the listeners active at their creation + return function () { + listenerStack.push(listeners); + listeners = union(list, listeners); + + var returned = original.apply(this, arguments); + + listeners = listenerStack.pop(); + + return returned; + }; +} + +/** + * Called each time an asynchronous function that's been monkeypatched in + * index.js is called. If there are no listeners, return the function + * unwrapped. If there are any asyncListeners and any of them have callbacks, + * pass them off to asyncWrap for later use, otherwise just call the listener. + */ +function wrapCallback(original) { + var length = listeners.length; + + // no context to capture, so avoid closure creation + if (length === 0) return original; + + // capture the active listeners as of when the wrapped function was called + var list = listeners.slice(); + + for (var i = 0; i < length; ++i) { + if (list[i].flags > 0) return asyncWrap(original, list, length); + } + + return simpleWrap(original, list, length); +} + +function AsyncListener(callbacks, data) { + if (typeof callbacks.create === 'function') { + this.create = callbacks.create; + this.flags |= HAS_CREATE_AL; + } + + if (typeof callbacks.before === 'function') { + this.before = callbacks.before; + this.flags |= HAS_BEFORE_AL; + } + + if (typeof callbacks.after === 'function') { + this.after = callbacks.after; + this.flags |= HAS_AFTER_AL; + } + + if (typeof callbacks.error === 'function') { + this.error = callbacks.error; + this.flags |= HAS_ERROR_AL; + } + + this.uid = ++uid; + this.data = data === undefined ? null : data; +} +AsyncListener.prototype.create = undefined; +AsyncListener.prototype.before = undefined; +AsyncListener.prototype.after = undefined; +AsyncListener.prototype.error = undefined; +AsyncListener.prototype.data = undefined; +AsyncListener.prototype.uid = 0; +AsyncListener.prototype.flags = 0; + +function createAsyncListener(callbacks, data) { + if (typeof callbacks !== 'object' || !callbacks) { + throw new TypeError('callbacks argument must be an object'); + } + + if (callbacks instanceof AsyncListener) { + return callbacks; + } + else { + return new AsyncListener(callbacks, data); + } +} + +function addAsyncListener(callbacks, data) { + var listener; + if (!(callbacks instanceof AsyncListener)) { + listener = createAsyncListener(callbacks, data); + } + else { + listener = callbacks; + } + + // Make sure the listener isn't already in the list. + var registered = false; + for (var i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + registered = true; + break; + } + } + + if (!registered) listeners.push(listener); + + return listener; +} + +function removeAsyncListener(listener) { + for (var i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + break; + } + } +} + +process.createAsyncListener = createAsyncListener; +process.addAsyncListener = addAsyncListener; +process.removeAsyncListener = removeAsyncListener; + +module.exports = wrapCallback; diff --git a/node_modules/async-listener/index.js b/node_modules/async-listener/index.js new file mode 100644 index 0000000..f12e3dd --- /dev/null +++ b/node_modules/async-listener/index.js @@ -0,0 +1,674 @@ +'use strict'; + +if (process.addAsyncListener) throw new Error("Don't require polyfill unless needed"); + +var shimmer = require('shimmer') + , semver = require('semver') + , wrap = shimmer.wrap + , massWrap = shimmer.massWrap + , wrapCallback = require('./glue.js') + , util = require('util') + ; + +var v6plus = semver.gte(process.version, '6.0.0'); +var v7plus = semver.gte(process.version, '7.0.0'); +var v8plus = semver.gte(process.version, '8.0.0'); +var v11plus = semver.gte(process.version, '11.0.0'); + +var net = require('net'); + +// From Node.js v7.0.0, net._normalizeConnectArgs have been renamed net._normalizeArgs +if (v7plus && !net._normalizeArgs) { + // a polyfill in our polyfill etc so forth -- taken from node master on 2017/03/09 + net._normalizeArgs = function (args) { + if (args.length === 0) { + return [{}, null]; + } + + var arg0 = args[0]; + var options = {}; + if (typeof arg0 === 'object' && arg0 !== null) { + // (options[...][, cb]) + options = arg0; + } else if (isPipeName(arg0)) { + // (path[...][, cb]) + options.path = arg0; + } else { + // ([port][, host][...][, cb]) + options.port = arg0; + if (args.length > 1 && typeof args[1] === 'string') { + options.host = args[1]; + } + } + + var cb = args[args.length - 1]; + if (typeof cb !== 'function') + return [options, null]; + else + return [options, cb]; + } +} else if (!v7plus && !net._normalizeConnectArgs) { + // a polyfill in our polyfill etc so forth -- taken from node master on 2013/10/30 + net._normalizeConnectArgs = function (args) { + var options = {}; + + function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; } + + if (typeof args[0] === 'object' && args[0] !== null) { + // connect(options, [cb]) + options = args[0]; + } + else if (typeof args[0] === 'string' && toNumber(args[0]) === false) { + // connect(path, [cb]); + options.path = args[0]; + } + else { + // connect(port, [host], [cb]) + options.port = args[0]; + if (typeof args[1] === 'string') { + options.host = args[1]; + } + } + + var cb = args[args.length - 1]; + return typeof cb === 'function' ? [options, cb] : [options]; + }; +} + +// In https://github.com/nodejs/node/pull/11796 `_listen2` was renamed +// `_setUpListenHandle`. It's still aliased as `_listen2`, and currently the +// Node internals still call the alias - but who knows for how long. So better +// make sure we use the new name instead if available. +if ('_setUpListenHandle' in net.Server.prototype) { + wrap(net.Server.prototype, '_setUpListenHandle', wrapSetUpListenHandle); +} else { + wrap(net.Server.prototype, '_listen2', wrapSetUpListenHandle); +} + +function wrapSetUpListenHandle(original) { + return function () { + this.on('connection', function (socket) { + if (socket._handle) { + socket._handle.onread = wrapCallback(socket._handle.onread); + } + }); + + try { + return original.apply(this, arguments); + } + finally { + // the handle will only not be set in cases where there has been an error + if (this._handle && this._handle.onconnection) { + this._handle.onconnection = wrapCallback(this._handle.onconnection); + } + } + }; +} + +function patchOnRead(ctx) { + if (ctx && ctx._handle) { + var handle = ctx._handle; + if (!handle._originalOnread) { + handle._originalOnread = handle.onread; + } + handle.onread = wrapCallback(handle._originalOnread); + } +} + +wrap(net.Socket.prototype, 'connect', function (original) { + return function () { + var args; + // Node core uses an internal Symbol here to guard against the edge-case + // where the user accidentally passes in an array. As we don't have access + // to this Symbol we resort to this hack where we just detect if there is a + // symbol or not. Checking for the number of Symbols is by no means a fool + // proof solution, but it catches the most basic cases. + if (v8plus && + Array.isArray(arguments[0]) && + Object.getOwnPropertySymbols(arguments[0]).length > 0) { + // already normalized + args = arguments[0]; + } else { + // From Node.js v7.0.0, net._normalizeConnectArgs have been renamed net._normalizeArgs + args = v7plus + ? net._normalizeArgs(arguments) + : net._normalizeConnectArgs(arguments); + } + if (args[1]) args[1] = wrapCallback(args[1]); + var result = original.apply(this, args); + patchOnRead(this); + return result; + }; +}); + +var http = require('http'); + +// NOTE: A rewrite occurred in 0.11 that changed the addRequest signature +// from (req, host, port, localAddress) to (req, options) +// Here, I use the longer signature to maintain 0.10 support, even though +// the rest of the arguments aren't actually used +wrap(http.Agent.prototype, 'addRequest', function (original) { + return function (req) { + var onSocket = req.onSocket; + req.onSocket = wrapCallback(function (socket) { + patchOnRead(socket); + return onSocket.apply(this, arguments); + }); + return original.apply(this, arguments); + }; +}); + +var childProcess = require('child_process'); + +function wrapChildProcess(child) { + if (Array.isArray(child.stdio)) { + child.stdio.forEach(function (socket) { + if (socket && socket._handle) { + socket._handle.onread = wrapCallback(socket._handle.onread); + wrap(socket._handle, 'close', activatorFirst); + } + }); + } + + if (child._handle) { + child._handle.onexit = wrapCallback(child._handle.onexit); + } +} + +// iojs v2.0.0+ +if (childProcess.ChildProcess) { + wrap(childProcess.ChildProcess.prototype, 'spawn', function (original) { + return function () { + var result = original.apply(this, arguments); + wrapChildProcess(this); + return result; + }; + }); +} else { + massWrap(childProcess, [ + 'execFile', // exec is implemented in terms of execFile + 'fork', + 'spawn' + ], function (original) { + return function () { + var result = original.apply(this, arguments); + wrapChildProcess(result); + return result; + }; + }); +} + +// need unwrapped nextTick for use within < 0.9 async error handling +if (!process._fatalException) { + process._originalNextTick = process.nextTick; +} + +var processors = []; +if (process._nextDomainTick) processors.push('_nextDomainTick'); +if (process._tickDomainCallback) processors.push('_tickDomainCallback'); + +massWrap( + process, + processors, + activator +); +wrap(process, 'nextTick', activatorFirst); + +var asynchronizers = [ + 'setTimeout', + 'setInterval' +]; +if (global.setImmediate) asynchronizers.push('setImmediate'); + +var timers = require('timers'); +var patchGlobalTimers = global.setTimeout === timers.setTimeout; + +massWrap( + timers, + asynchronizers, + activatorFirst +); + +if (patchGlobalTimers) { + massWrap( + global, + asynchronizers, + activatorFirst + ); +} + +var dns = require('dns'); +massWrap( + dns, + [ + 'lookup', + 'resolve', + 'resolve4', + 'resolve6', + 'resolveCname', + 'resolveMx', + 'resolveNs', + 'resolveTxt', + 'resolveSrv', + 'reverse' + ], + activator +); + +if (dns.resolveNaptr) wrap(dns, 'resolveNaptr', activator); + +var fs = require('fs'); +massWrap( + fs, + [ + 'watch', + 'rename', + 'truncate', + 'chown', + 'fchown', + 'chmod', + 'fchmod', + 'stat', + 'lstat', + 'fstat', + 'link', + 'symlink', + 'readlink', + 'realpath', + 'unlink', + 'rmdir', + 'mkdir', + 'readdir', + 'close', + 'open', + 'utimes', + 'futimes', + 'fsync', + 'write', + 'read', + 'readFile', + 'writeFile', + 'appendFile', + 'watchFile', + 'unwatchFile', + "exists", + ], + activator +); + +// only wrap lchown and lchmod on systems that have them. +if (fs.lchown) wrap(fs, 'lchown', activator); +if (fs.lchmod) wrap(fs, 'lchmod', activator); + +// only wrap ftruncate in versions of node that have it +if (fs.ftruncate) wrap(fs, 'ftruncate', activator); + +// Wrap zlib streams +var zlib; +try { zlib = require('zlib'); } catch (err) { } +if (zlib && zlib.Deflate && zlib.Deflate.prototype) { + var proto = Object.getPrototypeOf(zlib.Deflate.prototype); + if (proto._transform) { + // streams2 + wrap(proto, "_transform", activator); + } + else if (proto.write && proto.flush && proto.end) { + // plain ol' streams + massWrap( + proto, + [ + 'write', + 'flush', + 'end' + ], + activator + ); + } +} + +// Wrap Crypto +var crypto; +try { crypto = require('crypto'); } catch (err) { } +if (crypto) { + + var toWrap = [ + 'pbkdf2', + 'randomBytes', + ]; + if (!v11plus) { + toWrap.push('pseudoRandomBytes'); + } + + massWrap(crypto, toWrap, activator); +} + +// It is unlikely that any userspace promise implementations have a native +// implementation of both Promise and Promise.toString. +var instrumentPromise = !!global.Promise && + Promise.toString() === 'function Promise() { [native code] }' && + Promise.toString.toString() === 'function toString() { [native code] }'; + +// Check that global Promise is native +if (instrumentPromise) { + // shoult not use any methods that have already been wrapped + var promiseListener = process.addAsyncListener({ + create: function create() { + instrumentPromise = false; + } + }); + + // should not resolve synchronously + global.Promise.resolve(true).then(function notSync() { + instrumentPromise = false; + }); + + process.removeAsyncListener(promiseListener); +} + +/* + * Native promises use the microtask queue to make all callbacks run + * asynchronously to avoid Zalgo issues. Since the microtask queue is not + * exposed externally, promises need to be modified in a fairly invasive and + * complex way. + * + * The async boundary in promises that must be patched is between the + * fulfillment of the promise and the execution of any callback that is waiting + * for that fulfillment to happen. This means that we need to trigger a create + * when resolve or reject is called and trigger before, after and error handlers + * around the callback execution. There may be multiple callbacks for each + * fulfilled promise, so handlers will behave similar to setInterval where + * there may be multiple before after and error calls for each create call. + * + * async-listener monkeypatching has one basic entry point: `wrapCallback`. + * `wrapCallback` should be called when create should be triggered and be + * passed a function to wrap, which will execute the body of the async work. + * The resolve and reject calls can be modified fairly easily to call + * `wrapCallback`, but at the time of resolve and reject all the work to be done + * on fulfillment may not be defined, since a call to then, chain or fetch can + * be made even after the promise has been fulfilled. To get around this, we + * create a placeholder function which will call a function passed into it, + * since the call to the main work is being made from within the wrapped + * function, async-listener will work correctly. + * + * There is another complication with monkeypatching Promises. Calls to then, + * chain and catch each create new Promises that are fulfilled internally in + * different ways depending on the return value of the callback. When the + * callback return a Promise, the new Promise is resolved asynchronously after + * the returned Promise has been also been resolved. When something other than + * a promise is resolved the resolve call for the new Promise is put in the + * microtask queue and asynchronously resolved. + * + * Then must be wrapped so that its returned promise has a wrapper that can be + * used to invoke further continuations. This wrapper cannot be created until + * after the callback has run, since the callback may return either a promise + * or another value. Fortunately we already have a wrapper function around the + * callback we can use (the wrapper created by resolve or reject). + * + * By adding an additional argument to this wrapper, we can pass in the + * returned promise so it can have its own wrapper appended. the wrapper + * function can the call the callback, and take action based on the return + * value. If a promise is returned, the new Promise can proxy the returned + * Promise's wrapper (this wrapper may not exist yet, but will by the time the + * wrapper needs to be invoked). Otherwise, a new wrapper can be create the + * same way as in resolve and reject. Since this wrapper is created + * synchronously within another wrapper, it will properly appear as a + * continuation from within the callback. + */ + +if (instrumentPromise) { + wrapPromise(); +} + +function wrapPromise() { + var Promise = global.Promise; + + // Updates to this class should also be applied to the the ES6 version + // in es6-wrapped-promise.js. + function wrappedPromise(executor) { + if (!(this instanceof wrappedPromise)) { + return Promise(executor); + } + + if (typeof executor !== 'function') { + return new Promise(executor); + } + + var context, args; + var promise = new Promise(wrappedExecutor); + promise.__proto__ = wrappedPromise.prototype; + + try { + executor.apply(context, args); + } catch (err) { + args[1](err); + } + + return promise; + + function wrappedExecutor(resolve, reject) { + context = this; + args = [wrappedResolve, wrappedReject]; + + // These wrappers create a function that can be passed a function and an argument to + // call as a continuation from the resolve or reject. + function wrappedResolve(val) { + ensureAslWrapper(promise, false); + return resolve(val); + } + + function wrappedReject(val) { + ensureAslWrapper(promise, false); + return reject(val); + } + } + } + + util.inherits(wrappedPromise, Promise); + + wrap(Promise.prototype, 'then', wrapThen); + // Node.js = 0 ? x : false; +} + +// taken from node master on 2017/03/09 +function isPipeName(s) { + return typeof s === 'string' && toNumber(s) === false; +} diff --git a/node_modules/async-listener/package.json b/node_modules/async-listener/package.json new file mode 100644 index 0000000..c7d2ae1 --- /dev/null +++ b/node_modules/async-listener/package.json @@ -0,0 +1,39 @@ +{ + "name": "async-listener", + "version": "0.6.10", + "description": "Polyfill exporting trevnorris's 0.11+ asyncListener API.", + "author": "Forrest L Norvell ", + "contributors": [ + "Tim Caswell ", + "Forrest L Norvell " + ], + "main": "index.js", + "scripts": { + "test": "tap test/*.tap.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/othiym23/async-listener.git" + }, + "keywords": [ + "polyfill", + "shim", + "zesty", + "crazed", + "experimental" + ], + "license": "BSD-2-Clause", + "bugs": { + "url": "https://github.com/othiym23/async-listener/issues" + }, + "engines": { + "node": "<=0.11.8 || >0.11.10" + }, + "dependencies": { + "semver": "^5.3.0", + "shimmer": "^1.1.0" + }, + "devDependencies": { + "tap": "^0.7.1" + } +} diff --git a/node_modules/async-listener/test/add-remove.tap.js b/node_modules/async-listener/test/add-remove.tap.js new file mode 100644 index 0000000..7e5efa6 --- /dev/null +++ b/node_modules/async-listener/test/add-remove.tap.js @@ -0,0 +1,39 @@ +'use strict'; + +var test = require('tap').test; + +test("async listener lifecycle", function (t) { + t.plan(8); + + if (!process.addAsyncListener) require('../index.js'); + + t.ok(process.createAsyncListener, "can create async listeners"); + var counted = 0; + var listener = process.createAsyncListener( + { + create : function () { counted++; }, + before : function () {}, + after : function () {}, + error : function () {} + }, + Object.create(null) + ); + + t.ok(process.addAsyncListener, "can add async listeners"); + t.doesNotThrow(function () { + listener = process.addAsyncListener(listener); + }, "adding does not throw"); + + t.ok(listener, "have a listener we can later remove"); + + t.ok(process.removeAsyncListener, "can remove async listeners"); + t.doesNotThrow(function () { + process.removeAsyncListener(listener); + }, "removing does not throw"); + + t.doesNotThrow(function () { + process.removeAsyncListener(listener); + }, "failing remove does not throw"); + + t.equal(counted, 0, "didn't hit any async functions"); +}); diff --git a/node_modules/async-listener/test/connection-handler-disconnects.tap.js b/node_modules/async-listener/test/connection-handler-disconnects.tap.js new file mode 100644 index 0000000..4eb94ef --- /dev/null +++ b/node_modules/async-listener/test/connection-handler-disconnects.tap.js @@ -0,0 +1,74 @@ +'use strict'; + +var net = require('net'); +var test = require('tap').test; +if (!process.addAsyncListener) require('../index.js'); + +var PORT = 12346; + +test("another connection handler disconnects server", function (t) { + t.plan(7); + + var client; + + // This tests that we don't crash when another connection listener + // destroys the socket handle before we try to wrap + // socket._handle.onread . + // In this case, the connection handler declared below will run first, + // because the wrapping event handler doesn't get added until + // the server listens below. + + var server = net.createServer(function() {}); + server.on( + 'connection', + function (socket) { + t.ok(true, 'Reached second connection event'); + socket.destroy(); + t.ok(! socket._handle, 'Destroy removed the socket handle'); + } + ); + + server.on('error', function (err) { + t.fail(true, 'It should not produce errors'); + }); + + server.on( + 'listening', + function () { + t.ok(true, 'Server listened ok'); + + // This will run both 'connection' handlers, with the one above + // running first. + // This should succeed even though the socket is destroyed. + client = net.connect(PORT); + client.on( + 'connect', + function () { + t.ok(true, 'connected ok'); + } + ); + + client.on( + 'close', + function () { + t.ok(true, 'disconnected ok'); + t.ok( + !client._handle, + 'close removed the client handle' + ); + + server.close(function () { + t.ok( + !server._handle, + 'Destroy removed the server handle' + ); + }); + } + ) + } + ); + + // Another 'connection' handler is registered during this call. + server.listen(PORT); + +}); diff --git a/node_modules/async-listener/test/core-asynclistener-error-multiple-handled.simple.js b/node_modules/async-listener/test/core-asynclistener-error-multiple-handled.simple.js new file mode 100644 index 0000000..50493da --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-multiple-handled.simple.js @@ -0,0 +1,78 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +var active = null; +var cntr = 0; + +function onAsync0() { + return 0; +} + +function onAsync1() { + return 1; +} + +function onError(stor) { + results.push(stor); + return true; +} + +var results = []; +var asyncNoHandleError0 = { + create: onAsync0, + error: onError +}; +var asyncNoHandleError1 = { + create: onAsync1, + error: onError +}; + +var listeners = [ + process.addAsyncListener(asyncNoHandleError0), + process.addAsyncListener(asyncNoHandleError1) +]; + +process.nextTick(function() { + throw new Error(); +}); + +process.removeAsyncListener(listeners[0]); +process.removeAsyncListener(listeners[1]); + +process.on('exit', function(code) { + // If the exit code isn't ok then return early to throw the stack that + // caused the bad return code. + if (code !== 0) + return; + + // Handling of errors should propagate to all listeners. + assert.equal(results[0], 0); + assert.equal(results[1], 1); + assert.equal(results.length, 2); + + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-error-multiple-mix.simple.js b/node_modules/async-listener/test/core-asynclistener-error-multiple-mix.simple.js new file mode 100644 index 0000000..da37601 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-multiple-mix.simple.js @@ -0,0 +1,67 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +var results = []; +var asyncNoHandleError = { + error: function(stor) { + results.push(1); + } +}; + +var asyncHandleError = { + error: function(stor) { + results.push(0); + return true; + } +}; + +var listeners = [ + process.addAsyncListener(asyncHandleError), + process.addAsyncListener(asyncNoHandleError) +]; + +// Even if an error handler returns true, both should fire. +process.nextTick(function() { + throw new Error(); +}); + +process.removeAsyncListener(listeners[0]); +process.removeAsyncListener(listeners[1]); + +process.on('exit', function(code) { + // If the exit code isn't ok then return early to throw the stack that + // caused the bad return code. + if (code !== 0) + return; + + // Mixed handling of errors should propagate to all listeners. + assert.equal(results[0], 0); + assert.equal(results[1], 1); + assert.equal(results.length, 2); + + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-error-multiple-unhandled.simple.js b/node_modules/async-listener/test/core-asynclistener-error-multiple-unhandled.simple.js new file mode 100644 index 0000000..950b6f7 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-multiple-unhandled.simple.js @@ -0,0 +1,80 @@ +// 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 (!process.addAsyncListener) require('../index.js'); + +var assert = require('assert'); + +function onAsync0() { + return 0; +} + +function onAsync1() { + return 1; +} + +function onError(stor) { + results.push(stor); +} + +var results = []; +var asyncNoHandleError0 = { + create: onAsync0, + error: onError +}; +var asyncNoHandleError1 = { + create: onAsync1, + error: onError +}; + +var listeners = [ + process.addAsyncListener(asyncNoHandleError0), + process.addAsyncListener(asyncNoHandleError1) +]; + +var uncaughtFired = false; +process.on('uncaughtException', function() { + uncaughtFired = true; + + // Unhandled errors should propagate to all listeners. + assert.equal(results[0], 0); + assert.equal(results[1], 1); + assert.equal(results.length, 2); +}); + +process.nextTick(function() { + throw new Error(); +}); + +process.on('exit', function(code) { + // If the exit code isn't ok then return early to throw the stack that + // caused the bad return code. + if (code !== 0) + return; + + // Need to remove the async listeners or tests will always pass + for (var i = 0; i < listeners.length; i++) + process.removeAsyncListener(listeners[i]); + + assert.ok(uncaughtFired); + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-error-net.simple.js b/node_modules/async-listener/test/core-asynclistener-error-net.simple.js new file mode 100644 index 0000000..21fddc3 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-net.simple.js @@ -0,0 +1,110 @@ +// 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 PORT = 12346; + +if (!process.addAsyncListener) require('../index.js'); + +var assert = require('assert'); +var dns = require('dns'); +var fs = require('fs'); +var net = require('net'); + +var errorMsgs = []; +var caught = 0; +var expectCaught = 0; + +var callbacksObj = { + error: function(value, er) { + var idx = errorMsgs.indexOf(er.message); + caught++; + + // process._rawDebug('Handling error: ' + er.message); + + if (-1 < idx) + errorMsgs.splice(idx, 1); + else + throw new Error('Message not found: ' + er.message); + + return true; + } +}; + +var listener = process.addAsyncListener(callbacksObj); + +process.on('exit', function(code) { + process.removeAsyncListener(listener); + + if (code > 0) + return; + + if (errorMsgs.length > 0) + throw new Error('Errors not fired: ' + errorMsgs); + + assert.equal(caught, expectCaught); + console.log('ok'); +}); + + +// Net +var iter = 3; +for (var i = 0; i < iter; i++) { + errorMsgs.push('net - error: server connection'); + errorMsgs.push('net - error: client data'); + errorMsgs.push('net - error: server data'); +} +errorMsgs.push('net - error: server closed'); + +var server = net.createServer(function(c) { + c.on('data', function() { + if (0 === --iter) { + server.close(function() { + console.log('net - server closing'); + throw new Error('net - error: server closed'); + }); + expectCaught++; + } + console.log('net - connection received data'); + throw new Error('net - error: server data'); + }); + expectCaught++; + + c.end('bye'); + console.log('net - connection received'); + throw new Error('net - error: server connection'); +}); +expectCaught += iter; + +server.listen(PORT, function() { + for (var i = 0; i < iter; i++) + clientConnect(); +}); + +function clientConnect() { + var client = net.connect(PORT, function() { }); + + client.on('data', function() { + client.end('see ya'); + console.log('net - client received data'); + throw new Error('net - error: client data'); + }); + expectCaught++; +} diff --git a/node_modules/async-listener/test/core-asynclistener-error-throw-in-after.simple.js b/node_modules/async-listener/test/core-asynclistener-error-throw-in-after.simple.js new file mode 100644 index 0000000..03a89fc --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-throw-in-after.simple.js @@ -0,0 +1,56 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +var once = 0; +function onAsync0() {} + +var handlers = { + after: function () { + throw new Error('erk'); + }, + error: function () { + // error handler must be called exactly *once* + once++; + + return true; + } +}; + +var key = process.addAsyncListener(onAsync0, handlers); + +process.on('uncaughtException', function () { + // process should propagate error regardless of + // error handlers return value + assert.equal(once, 1); + console.log('ok'); +}); + +setImmediate(function () { + return 1; +}); + +process.removeAsyncListener(key); diff --git a/node_modules/async-listener/test/core-asynclistener-error-throw-in-before-multiple.simple.js b/node_modules/async-listener/test/core-asynclistener-error-throw-in-before-multiple.simple.js new file mode 100644 index 0000000..622a4d9 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-throw-in-before-multiple.simple.js @@ -0,0 +1,79 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +var once = 0; +function onAsync0() {} +function onAsync1() {} + +var handlers = { + before : function () { + throw 1; + }, + error : function (stor, err) { + // must catch error thrown in before + assert.equal(err, 1); + + once++; + + return true; + } +}; + +var handlers1 = { + before : function () { + throw 2; + }, + error : function (stor, err) { + // must catch *other* handler's throw error + assert.equal(err, 1); + + once++; + + return true; + } +}; + +var keys = [ + process.addAsyncListener(onAsync0, handlers), + process.addAsyncListener(onAsync1, handlers1) +]; + +process.on('uncaughtException', function () { + // both error handlers must fire + assert.equal(once, 2); + + console.log('ok'); +}); + +setImmediate(function () { + return 1; +}); + +keys.forEach(function (key) { + process.removeAsyncListener(key); +}); + diff --git a/node_modules/async-listener/test/core-asynclistener-error-throw-in-before.simple.js b/node_modules/async-listener/test/core-asynclistener-error-throw-in-before.simple.js new file mode 100644 index 0000000..f6a3c65 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-throw-in-before.simple.js @@ -0,0 +1,56 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +var once = 0; +function onAsync0() {} + +var handlers = { + before : function () { + throw 1; + }, + error : function () { + // error handler must be called exactly *once* + once++; + + return true; + } +}; + +var key = process.addAsyncListener(onAsync0, handlers); + +process.on('uncaughtException', function () { + // process should propagate error regardless of + // error handlers return value + assert.equal(once, 1); + console.log('ok'); +}); + +setImmediate(function () { + return 1; +}); + +process.removeAsyncListener(key); diff --git a/node_modules/async-listener/test/core-asynclistener-error-throw-in-error.simple.js b/node_modules/async-listener/test/core-asynclistener-error-throw-in-error.simple.js new file mode 100644 index 0000000..cec06a3 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error-throw-in-error.simple.js @@ -0,0 +1,72 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); +var cluster = require('cluster'); + +function onAsync0() {} + +if (cluster.isMaster) { + cluster.setupMaster({ + silent : true + }); + cluster.fork(); + cluster.on('exit', function (worker, code) { + if (process._fatalException) { + // verify child exited because of throw from 'error' + assert.equal(code, 7); + } + else { + // node < 0.9.x doesn't have error exit codes + assert.equal(code, 1); + } + + console.log('ok'); + }); +} else { + var once = 0; + + var handlers = { + error : function () { + // the error handler should not be called again + if (once++ !== 0) process.exit(5); + + throw new Error('error handler'); + } + }; + + var key = process.addAsyncListener(onAsync0, handlers); + + process.on('unhandledException', function () { + // throwing in 'error' should bypass unhandledException + process.exit(1); + }); + + setImmediate(function () { + throw new Error('setImmediate'); + }); + + process.removeAsyncListener(key); +} diff --git a/node_modules/async-listener/test/core-asynclistener-error.simple.js b/node_modules/async-listener/test/core-asynclistener-error.simple.js new file mode 100644 index 0000000..97d3b58 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-error.simple.js @@ -0,0 +1,229 @@ +// 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 PORT = 12346; + +if (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); +var dns = require('dns'); +var fs = require('fs'); +var net = require('net'); +var addListener = process.addAsyncListener; +var removeListener = process.removeAsyncListener; + +var caught = 0; +var expectCaught = 0; + +function asyncL() { } + +var callbacksObj = { + error: function(domain, er) { + caught++; + + switch (er.message) { + case 'sync throw': + case 'setTimeout - simple': + case 'setImmediate - simple': + case 'setInterval - simple': + case 'process.nextTick - simple': + case 'setTimeout - nested': + case 'process.nextTick - nested': + case 'setImmediate - nested': + case 'setTimeout2 - nested': + case 'setInterval - nested': + case 'fs - file does not exist': + case 'fs - nested file does not exist': + case 'fs - exists': + case 'fs - realpath': + case 'net - connection listener': + case 'net - server listening': + case 'net - client connect': + case 'dns - lookup': + return true; + + default: + return false; + } + } +}; + +process.on('exit', function() { + console.log('caught:', caught); + console.log('expected:', expectCaught); + assert.equal(caught, expectCaught, 'caught all expected errors'); + console.log('ok'); +}); + +var listener = process.createAsyncListener(asyncL, callbacksObj); + + +// Catch synchronous throws +process.nextTick(function() { + addListener(listener); + + expectCaught++; + throw new Error('sync throw'); + + removeListener(listener); +}); + + +// Simple cases +process.nextTick(function() { + addListener(listener); + + setTimeout(function() { + throw new Error('setTimeout - simple'); + }); + expectCaught++; + + setImmediate(function() { + throw new Error('setImmediate - simple'); + }); + expectCaught++; + + var b = setInterval(function() { + clearInterval(b); + throw new Error('setInterval - simple'); + }); + expectCaught++; + + process.nextTick(function() { + throw new Error('process.nextTick - simple'); + }); + expectCaught++; + + removeListener(listener); +}); + + +// Deeply nested +process.nextTick(function() { + addListener(listener); + + setTimeout(function() { + process.nextTick(function() { + setImmediate(function() { + var b = setInterval(function() { + clearInterval(b); + throw new Error('setInterval - nested'); + }); + expectCaught++; + throw new Error('setImmediate - nested'); + }); + expectCaught++; + throw new Error('process.nextTick - nested'); + }); + expectCaught++; + setTimeout(function() { + throw new Error('setTimeout2 - nested'); + }); + expectCaught++; + throw new Error('setTimeout - nested'); + }); + expectCaught++; + + removeListener(listener); +}); + + +// FS +process.nextTick(function() { + addListener(listener); + + fs.stat('does not exist', function() { + throw new Error('fs - file does not exist'); + }); + expectCaught++; + + fs.exists('hi all', function() { + throw new Error('fs - exists'); + }); + expectCaught++; + + fs.realpath('/some/path', function() { + throw new Error('fs - realpath'); + }); + expectCaught++; + + removeListener(listener); +}); + + +// Nested FS +process.nextTick(function() { + addListener(listener); + + setTimeout(function() { + setImmediate(function() { + var b = setInterval(function() { + clearInterval(b); + process.nextTick(function() { + fs.stat('does not exist', function() { + throw new Error('fs - nested file does not exist'); + }); + expectCaught++; + }); + }); + }); + }); + + removeListener(listener); +}); + + +// Net +process.nextTick(function() { + addListener(listener); + + var server = net.createServer(function() { + server.close(); + throw new Error('net - connection listener'); + }); + expectCaught++; + + server.listen(PORT, function() { + var client = net.connect(PORT, function() { + client.end(); + throw new Error('net - client connect'); + }); + expectCaught++; + throw new Error('net - server listening'); + }); + expectCaught++; + + removeListener(listener); +}); + + +// DNS +process.nextTick(function() { + addListener(listener); + + dns.lookup('localhost', function() { + throw new Error('dns - lookup'); + }); + expectCaught++; + + removeListener(listener); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-nexttick-remove.simple.js b/node_modules/async-listener/test/core-asynclistener-nexttick-remove.simple.js new file mode 100644 index 0000000..07f080d --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-nexttick-remove.simple.js @@ -0,0 +1,137 @@ +// 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 (!process.addAsyncListener) require('../index.js'); + +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); + +var actualAsync = 0; +var expectAsync = 0; + + +process.on('exit', function() { + console.log('expected', expectAsync); + console.log('actual ', actualAsync); + assert.equal(expectAsync, actualAsync); + console.log('ok'); +}); + + +// --- Begin Testing --- // + +function onAsync() { + actualAsync++; +} + + +var id; +process.nextTick(function() { + process.removeAsyncListener(id); +}); +id = process.addAsyncListener(onAsync); + + +// Test listeners side-by-side +var b = setInterval(function() { + clearInterval(b); +}); +expectAsync++; + +var c = setInterval(function() { + clearInterval(c); +}); +expectAsync++; + +setTimeout(function() { }); +expectAsync++; + +setTimeout(function() { }); +expectAsync++; + +process.nextTick(function() { }); +expectAsync++; + +process.nextTick(function() { }); +expectAsync++; + +setImmediate(function() { }); +expectAsync++; + +setImmediate(function() { }); +expectAsync++; + +setTimeout(function() { }, 100); +expectAsync++; + +setTimeout(function() { }, 100); +expectAsync++; + + +// Async listeners should propagate with nested callbacks +var interval = 3; + +process.nextTick(function() { + setTimeout(function() { + setImmediate(function() { + var i = setInterval(function() { + if (--interval <= 0) + clearInterval(i); + }); + expectAsync++; + }); + expectAsync++; + process.nextTick(function() { + setImmediate(function() { + setTimeout(function() { }, 200); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; +}); +expectAsync++; + + +// Test callbacks from fs I/O +fs.stat('something random', function() { }); +expectAsync++; + +setImmediate(function() { + fs.stat('random again', function() { }); + expectAsync++; +}); +expectAsync++; + + +// Test net I/O +var server = net.createServer(function() { }); +expectAsync++; + +server.listen(8080, function() { + server.close(); + expectAsync++; +}); +expectAsync++; diff --git a/node_modules/async-listener/test/core-asynclistener-only-add.simple.js b/node_modules/async-listener/test/core-asynclistener-only-add.simple.js new file mode 100644 index 0000000..daa1531 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-only-add.simple.js @@ -0,0 +1,133 @@ +// 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 (!process.addAsyncListener) require('../index.js'); + +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); + +var actualAsync = 0; +var expectAsync = 0; + + +process.on('exit', function() { + console.log('expected', expectAsync); + console.log('actual ', actualAsync); + assert.equal(expectAsync, actualAsync); + console.log('ok'); +}); + + +// --- Begin Testing --- // + +function onAsync() { + actualAsync++; +} + + +process.addAsyncListener(onAsync); + + +// Test listeners side-by-side +var b = setInterval(function() { + clearInterval(b); +}); +expectAsync++; + +var c = setInterval(function() { + clearInterval(c); +}); +expectAsync++; + +setTimeout(function() { }); +expectAsync++; + +setTimeout(function() { }); +expectAsync++; + +process.nextTick(function() { }); +expectAsync++; + +process.nextTick(function() { }); +expectAsync++; + +setImmediate(function() { }); +expectAsync++; + +setImmediate(function() { }); +expectAsync++; + +setTimeout(function() { }, 100); +expectAsync++; + +setTimeout(function() { }, 100); +expectAsync++; + + +// Async listeners should propagate with nested callbacks +var interval = 3; + +process.nextTick(function() { + setTimeout(function() { + setImmediate(function() { + var i = setInterval(function() { + if (--interval <= 0) + clearInterval(i); + }); + expectAsync++; + }); + expectAsync++; + process.nextTick(function() { + setImmediate(function() { + setTimeout(function() { }, 200); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; +}); +expectAsync++; + + +// Test callbacks from fs I/O +fs.stat('something random', function() { }); +expectAsync++; + +setImmediate(function() { + fs.stat('random again', function() { }); + expectAsync++; +}); +expectAsync++; + + +// Test net I/O +var server = net.createServer(function() { }); +expectAsync++; + +server.listen(8080, function() { + server.close(); + expectAsync++; +}); +expectAsync++; diff --git a/node_modules/async-listener/test/core-asynclistener-remove-before.simple.js b/node_modules/async-listener/test/core-asynclistener-remove-before.simple.js new file mode 100644 index 0000000..e7aa095 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-remove-before.simple.js @@ -0,0 +1,55 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +function onAsync0() { + return 0; +} + +var set = 0; +var asyncNoHandleError = { + before : function () { + set ++; + }, + after : function () { + set ++; + } +}; + +var key = process.addAsyncListener(onAsync0, asyncNoHandleError); + +process.removeAsyncListener(key); + +setImmediate(function () { + return 1; +}); + +process.on('exit', function () { + // the async handler should never be called + assert.equal(set, 0); + + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-remove-inflight-error.simple.js b/node_modules/async-listener/test/core-asynclistener-remove-inflight-error.simple.js new file mode 100644 index 0000000..5703069 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-remove-inflight-error.simple.js @@ -0,0 +1,50 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +function onAsync0() {} + +var set = 0; +var asyncNoHandleError = { + error : function () { + set ++; + } +}; + +var key = process.addAsyncListener(onAsync0, asyncNoHandleError); + +setImmediate(function () { + throw 1; +}); + +process.removeAsyncListener(key); +process.on('uncaughtException', function () { + // throwing should call the error handler once, + // then propagate to the uncaughtException + assert.equal(set, 1); + + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener-remove-inflight.simple.js b/node_modules/async-listener/test/core-asynclistener-remove-inflight.simple.js new file mode 100644 index 0000000..3402aad --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener-remove-inflight.simple.js @@ -0,0 +1,53 @@ +// 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 (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); + +function onAsync0() {} + +var set = 0; +var asyncNoHandleError = { + before : function () { + set++; + }, + after : function () { + set++; + } +}; + +var key = process.addAsyncListener(onAsync0, asyncNoHandleError); + +setImmediate(function () { + return 1; +}); + +process.removeAsyncListener(key); +process.on('exit', function () { + // calling removeAsyncListener *after* a callback is scheduled + // should not affect the handler from responding to the callback + assert.equal(set, 2); + + console.log('ok'); +}); diff --git a/node_modules/async-listener/test/core-asynclistener.simple.js b/node_modules/async-listener/test/core-asynclistener.simple.js new file mode 100644 index 0000000..3002bb1 --- /dev/null +++ b/node_modules/async-listener/test/core-asynclistener.simple.js @@ -0,0 +1,191 @@ +// 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 PORT = 12346; + +if (!process.addAsyncListener) require('../index.js'); +if (!global.setImmediate) global.setImmediate = setTimeout; + +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); +var dgram = require('dgram'); + +var addListener = process.addAsyncListener; +var removeListener = process.removeAsyncListener; +var actualAsync = 0; +var expectAsync = 0; + +var callbacks = { + create: function onAsync() { + actualAsync++; + } +}; + +var listener = process.createAsyncListener(callbacks); + +process.on('exit', function() { + console.log('expected', expectAsync); + console.log('actual ', actualAsync); + // TODO(trevnorris): Not a great test. If one was missed, but others + // overflowed then the test would still pass. + assert.ok(actualAsync >= expectAsync); +}); + + +// Test listeners side-by-side +process.nextTick(function() { + addListener(listener); + + var b = setInterval(function() { + clearInterval(b); + }); + expectAsync++; + + var c = setInterval(function() { + clearInterval(c); + }); + expectAsync++; + + setTimeout(function() { }); + expectAsync++; + + setTimeout(function() { }); + expectAsync++; + + process.nextTick(function() { }); + expectAsync++; + + process.nextTick(function() { }); + expectAsync++; + + setImmediate(function() { }); + expectAsync++; + + setImmediate(function() { }); + expectAsync++; + + setTimeout(function() { }, 10); + expectAsync++; + + setTimeout(function() { }, 10); + expectAsync++; + + removeListener(listener); +}); + + +// Async listeners should propagate with nested callbacks +process.nextTick(function() { + addListener(listener); + var interval = 3; + + process.nextTick(function() { + setTimeout(function() { + setImmediate(function() { + var i = setInterval(function() { + if (--interval <= 0) + clearInterval(i); + }); + expectAsync++; + }); + expectAsync++; + process.nextTick(function() { + setImmediate(function() { + setTimeout(function() { }, 20); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; + }); + expectAsync++; + + removeListener(listener); +}); + + +// Test triggers with two async listeners +process.nextTick(function() { + addListener(listener); + addListener(listener); + + setTimeout(function() { + process.nextTick(function() { }); + expectAsync += 2; + }); + expectAsync += 2; + + removeListener(listener); + removeListener(listener); +}); + + +// Test callbacks from fs I/O +process.nextTick(function() { + addListener(listener); + + fs.stat('something random', function(err, stat) { }); + expectAsync++; + + setImmediate(function() { + fs.stat('random again', function(err, stat) { }); + expectAsync++; + }); + expectAsync++; + + removeListener(listener); +}); + + +// Test net I/O +process.nextTick(function() { + addListener(listener); + + var server = net.createServer(function(c) { }); + expectAsync++; + + server.listen(PORT, function() { + server.close(); + expectAsync++; + }); + expectAsync++; + + removeListener(listener); +}); + + +// Test UDP +process.nextTick(function() { + addListener(listener); + + var server = dgram.createSocket('udp4'); + expectAsync++; + + server.bind(PORT); + + server.close(); + expectAsync++; + + removeListener(listener); +}); diff --git a/node_modules/async-listener/test/core/core-asynclistener-add-inflight.js b/node_modules/async-listener/test/core/core-asynclistener-add-inflight.js new file mode 100644 index 0000000..0052a7e --- /dev/null +++ b/node_modules/async-listener/test/core/core-asynclistener-add-inflight.js @@ -0,0 +1,58 @@ +// 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 (!process.addAsyncListener) require('../../index.js'); + +var assert = require('assert'); + +function onAsync0() {} +function onAsync1() {} + +var once = 0; +var handlers0 = { + before: function (stor, err) { + // should catch the error *once* + once++; + } +} + +var handlers1 = { + before: function (stor, err) { + // handler was added in flight, and should not be called + throw "Should Never Be Called"; + } +} + +var key0 = process.addAsyncListener(onAsync0, handlers0); + +process.on('exit', function (err) { + // handlers0 before handler must be called once only + assert.equal(once, 1); + console.log('ok'); +}); + +setImmediate(function () { + 1; +}); + +process.addAsyncListener(onAsync1, handlers1); +process.removeAsyncListener(key0); diff --git a/node_modules/async-listener/test/core/core-asynclistener-error-throw-in-before-inflight.js b/node_modules/async-listener/test/core/core-asynclistener-error-throw-in-before-inflight.js new file mode 100644 index 0000000..d6a502e --- /dev/null +++ b/node_modules/async-listener/test/core/core-asynclistener-error-throw-in-before-inflight.js @@ -0,0 +1,59 @@ +// 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 (!process.addAsyncListener) require('../../index.js'); + +var assert = require('assert'); + +function onAsync0() {} +function onAsync1() {} + +var once = 0; +var handlers0 = { + error: function (stor, err) { + // should catch the error *once* + once++; + } +} + +var handlers1 = { + error: function (stor, err) { + // this error handler is bound *after* the async callback + // and it should not handle the error + throw "Should Never Be Called"; + } +} + +var key0 = process.addAsyncListener(onAsync0, handlers0); + +process.on('uncaughtException', function (err) { + // handlers0 error handler must be called once only + assert.equal(once, 1); + console.log('ok'); +}); + +setImmediate(function () { + throw 1; +}); + +process.addAsyncListener(onAsync1, handlers1); +process.removeAsyncListener(key0); diff --git a/node_modules/async-listener/test/errors-this-tick.tap.js b/node_modules/async-listener/test/errors-this-tick.tap.js new file mode 100644 index 0000000..c8a2474 --- /dev/null +++ b/node_modules/async-listener/test/errors-this-tick.tap.js @@ -0,0 +1,70 @@ +'use strict'; + +var assert = require('assert'); + +if (!process.addAsyncListener) require('../index.js'); + +function MiniCLS() { + this.active = Object.create(null); + this._stack = []; +} + +MiniCLS.prototype.enter = function (context) { + assert.ok(context, "context must be provided for entering"); + + this._stack.push(this.active); + this.active = context; +}; + +MiniCLS.prototype.exit = function (context) { + assert.ok(context, "context must be provided for exiting"); + + if (this.active === context) { + assert.ok(this._stack.length, "can't remove top context"); + this.active = this._stack.pop(); + return; + } + + var index = this._stack.lastIndexOf(context); + + assert.ok(index >= 0, "context not currently entered; can't exit"); + assert.ok(index, "can't remove top context"); + + this.active = this._stack[index - 1]; + this._stack.length = index - 1; +}; + +MiniCLS.prototype.run = function (fn) { + var context = Object.create(this.active); + this.enter(context); + try { + fn(context); + return context; + } + finally { + this.exit(context); + } +}; + +var cls = new MiniCLS(); +process.addAsyncListener( + { + create : function () { return cls.active; }, + before : function (context, domain) { cls.enter(domain); }, + after : function (context, domain) { cls.exit(domain); }, + error : function (domain) { if (domain) cls.exit(domain); } + } +); + +process.on('uncaughtException', function (err) { + if (err.message === 'oops') { + console.log('ok got expected error: %s', err.message); + } + else { + console.log('not ok got expected error: %s', err.stack); + } +}); + +cls.run(function () { + throw new Error('oops'); +}); diff --git a/node_modules/async-listener/test/fork-listen2-problem.tap.js b/node_modules/async-listener/test/fork-listen2-problem.tap.js new file mode 100644 index 0000000..590871a --- /dev/null +++ b/node_modules/async-listener/test/fork-listen2-problem.tap.js @@ -0,0 +1,33 @@ +'use strict'; + +var fork = require('child_process').fork; +var test = require('tap').test; + +var server + +test("parent listener", function (t) { + server = require('net').createServer(); + + server.listen(8585, function () { + t.ok(server, "parent listening on port 8585"); + + var listener = fork(__dirname + '/fork-listener.js'); + t.ok(listener, "child process started"); + + listener.on('message', function (message) { + if (message === 'shutdown') { + t.ok(message, "child handled error properly"); + listener.send('shutdown'); + } + else { + t.fail("parent got unexpected message " + message); + } + t.end(); + }); + }); +}); + +test("tearDown", function (t) { + server.close(); + t.end(); +}) diff --git a/node_modules/async-listener/test/fork-listener.js b/node_modules/async-listener/test/fork-listener.js new file mode 100644 index 0000000..4859003 --- /dev/null +++ b/node_modules/async-listener/test/fork-listener.js @@ -0,0 +1,31 @@ +'use strict'; + +var domain = require('domain'); + +if (!process.addAsyncListener) require('../index.js'); + +var d = domain.create(); +d.on('error', function (error) { + process.send(error.message); +}); + +process.on('message', function (message) { + if (message === 'shutdown') { + process.exit(); + } + else { + process.send("child got unexpected message " + message); + } +}); + +d.run(function () { + var server = require('net').createServer(); + + server.on('error', function () { + process.send('shutdown'); + }); + + server.listen(8585, function () { + process.send("child shouldn't be able to listen on port 8585"); + }); +}); diff --git a/node_modules/async-listener/test/function-length-preserved.tap.js b/node_modules/async-listener/test/function-length-preserved.tap.js new file mode 100644 index 0000000..cafd9fb --- /dev/null +++ b/node_modules/async-listener/test/function-length-preserved.tap.js @@ -0,0 +1,24 @@ +var test = require('tap').test; + +test("asyncListener preserves function length", function (t) { + t.plan(2); + + var fsLengthsPre = computeValueLengths(require('fs')); + var httpLengthsPre = computeValueLengths(require('http')); + + if (!process.addAsyncListener) require('../index.js'); + + var fsLengthsPost = computeValueLengths(require('fs')); + var httpLengthsPost = computeValueLengths(require('http')); + + t.same(fsLengthsPre, fsLengthsPost); + t.same(httpLengthsPre, httpLengthsPost); +}); + +function computeValueLengths(o) { + var lengths = []; + for (var k in o) { + lengths.push(o[k].length); + } + return lengths; +} diff --git a/node_modules/async-listener/test/handle.tap.js b/node_modules/async-listener/test/handle.tap.js new file mode 100644 index 0000000..e480293 --- /dev/null +++ b/node_modules/async-listener/test/handle.tap.js @@ -0,0 +1,34 @@ +if (!process.addAsyncListener) require('../index.js'); + +var test = require('tap').test; +var net = require('net'); + +test('synchronous errors during connect return a null _handle', function(t){ + t.plan(3); + + // listening server + var server = net.createServer().listen(8000); + + // client + var client = net.connect({port: 8000}); + + client.on('connect', function(){ + t.ok(true, 'connect'); + // kill connection + client.end(); + }); + + client.on('error', function(){ + server.close(); + t.ok(true, 'done test'); + }); + + client.on('end', function() { + setTimeout(function(){ + // try to reconnect, but this has an error + // rather than throw the right error, we're going to get an async-listener error + t.ok(true, 'end'); + client.connect(8001); + }, 100); + }); +}); diff --git a/node_modules/async-listener/test/http-request.tap.js b/node_modules/async-listener/test/http-request.tap.js new file mode 100644 index 0000000..b379993 --- /dev/null +++ b/node_modules/async-listener/test/http-request.tap.js @@ -0,0 +1,307 @@ +if (!process.addAsyncListener) require('../index.js'); + +var extend = require('util')._extend; +var test = require('tap').test; +var http = require('http'); + +// Convert semver string to number set +// TODO: This is *very* naive structure to check versions with, +// but it works well enough for now... +var nodeVersion = process.version.slice(1).split('.').map(Number) + +test('http.Agent socket reuse works', function(t){ + function main (done) { + var listener = addListner(); + var times = 2; + + var agent = new http.Agent({ + keepAlive: true, + maxFreeSockets: 1, + maxSockets: 1 + }); + + function after(rand, i) { + if (--times === 0) { + t.deepEqual( + listener.root, + expected, + 'should have equal state structures' + ); + if (agent.destroy) { + agent.destroy(); + } + done(); + } + } + + function ping(i) { + listener.currentName = 'ping #' + i + ' request'; + var addr = server.address(); + var req = http.request({ + agent: agent, + port: addr.port, + host: addr.host, + path: '/sub' + }, function (res) { + // The second request is a logical continuation of + // the first request, due to the http.Agent pooling + if (i === 0) { + t.equal( + listener.current.name, + 'ping #' + i + ' request', + 'should be ping #' + i + ' request' + ); + } else { + t.equal( + listener.current.name, + 'setImmediate to after #' + (i - 1), + 'should be setImmediate to after #' + (i - 1) + ); + } + + listener.currentName = 'res.resume ping #' + i; + const bufs = []; + res.on('data', function (chunk) { + bufs.push(chunk); + }); + res.on('end', function () { + const body = Buffer.concat(bufs).toString(); + t.equal('hello', body, 'should have body of "hello"') + t.equal( + listener.current.name, + 'res.resume ping #' + i, + 'should be res.resume ping #' + i + ); + listener.currentName = 'setImmediate to after #' + i; + setImmediate(after, i); + }); + }); + listener.currentName = 'req.end ping #' + i; + req.end(); + } + + for (var i = 0; i < times; i++) { + listener.currentName = 'setImmediate #' + i; + setImmediate(ping, i); + } + + process.removeAsyncListener(listener.listener); + + // + // NOTE: This expected structure building stuff is really complicated + // because the interactions in node internals changed so much from 0.10 + // until now. It could be a lot simpler if we only cared about testing + // the current stable, but this really needs to be tested back to 0.10. + // + // I'm sorry. :'( + // + function make (name, override) { + return extend({ + name: name, + children: [], + before: 1, + after: 1, + error: 0 + }, override || {}) + } + + // + // First ping branch + // + var innerResumeChildren = []; + if (nodeVersion[0] < 8) { + innerResumeChildren.push(make('res.resume ping #0')); + } + innerResumeChildren.push(make('setImmediate to after #0')); + + var innerResumeChildrenWrapped = [ + make('res.resume ping #0', { + children: innerResumeChildren + }), + make('res.resume ping #0'), + make('res.resume ping #0') + ]; + var innerPingChildren = []; + if (nodeVersion[0] == 0 && nodeVersion[1] < 12) { + innerPingChildren.push(make('res.resume ping #0')); + } + innerPingChildren.push(make('res.resume ping #0', { + children: nodeVersion[0] == 0 && nodeVersion[1] < 12 + ? innerResumeChildren + : innerResumeChildrenWrapped + })); + if (nodeVersion[0] > 0 || nodeVersion[1] > 10) { + if (nodeVersion[0] < 6 && nodeVersion[0] !== 4) { + innerPingChildren.push(make('res.resume ping #0')); + } + innerPingChildren.push( + make('res.resume ping #0', { + children: [make('res.resume ping #0')] + }), + make('res.resume ping #0') + ); + } + + var firstImmediateChildren = [ + make('ping #0 request', { + children: [ + make('ping #0 request', { + children: innerPingChildren + }), + make('ping #0 request', { + children: nodeVersion[0] > 0 || nodeVersion[1] > 10 + ? [make('req.end ping #1')] + : [] + }) + ] + }) + ]; + + if (nodeVersion[0] > 4) { + firstImmediateChildren.push(make('ping #0 request')); + }; + + firstImmediateChildren.push( + make('ping #0 request'), + make('ping #0 request', { + before: 0, + after: 0 + }) + ); + + var firstImmediate = make('setImmediate #0', { + children: firstImmediateChildren + }); + + // + // Second ping branch + // + var innerPingChildren = []; + if (nodeVersion[0] < 8) { + innerPingChildren.push(make('res.resume ping #1')); + } + + innerPingChildren.push(make('setImmediate to after #1', { + after: 0 + })); + + var innerPingChildrenWrapped = [ + make('res.resume ping #1', { + children: innerPingChildren + }), + make('res.resume ping #1'), + make('res.resume ping #1') + ]; + var innerImmediateChildren = []; + if (nodeVersion[0] == 0 && nodeVersion[1] < 12) { + innerImmediateChildren.push(make('res.resume ping #1')); + } + innerImmediateChildren.push(make('res.resume ping #1', { + children: nodeVersion[0] == 0 && nodeVersion[1] < 12 + ? innerPingChildren + : innerPingChildrenWrapped + })); + if (nodeVersion[0] > 0 || nodeVersion[1] > 10) { + if (nodeVersion[0] < 6 && nodeVersion[0] !== 4) { + innerImmediateChildren.push(make('res.resume ping #1')); + } + innerImmediateChildren.push( + make('res.resume ping #1', { + children: [make('res.resume ping #1')] + }), + make('res.resume ping #1') + ); + } + + var secondImmediate = make('setImmediate #1', { + children: [ + make('ping #1 request', { + children: [ + make('setImmediate to after #0', { + children: innerImmediateChildren + }), + make('setImmediate to after #0', { + children: [make('setImmediate to after #0')] + }) + ] + }) + ] + }); + + // + // Make expected object + // + var expected = make('root', { + children: [ + firstImmediate, + secondImmediate + ], + before: 0, + after: 0 + }); + } + + var server = http.createServer(function (req, res) { + res.end('hello'); + }); + + // + // Test client + // + server.listen(function () { + main(function () { + server.close(); + server.on('close', function () { + t.end(); + }); + }); + }); +}); + +function addListner() { + var listener = process.addAsyncListener({ + create: create, + before: before, + after: after, + error: error + }); + + var state = { + listener: listener, + currentName: 'root' + }; + + state.root = create(); + state.current = state.root; + + return state; + + function create () { + var node = { + name: state.currentName, + children: [], + before: 0, + after: 0, + error: 0 + }; + + if(state.current) state.current.children.push(node); + return node; + } + + function before(ctx, node) { + state.current = node; + state.current.before++; + } + + function after(ctx, node) { + node.after++; + state.current = null; + } + + function error(ctx, node) { + node.error++; + state.current = null; + return false; + } +} diff --git a/node_modules/async-listener/test/native-promises.tap.js b/node_modules/async-listener/test/native-promises.tap.js new file mode 100644 index 0000000..b893741 --- /dev/null +++ b/node_modules/async-listener/test/native-promises.tap.js @@ -0,0 +1,2236 @@ +if (!global.Promise) return; + +var test = require('tap').test; + +var unwrappedPromise = global.Promise; +var resolvedBeforeWrap = unwrappedPromise.resolve(123) + +require('../index.js'); + +// Convert semver string to number set +// TODO: This is *very* naive structure to check versions with, +// but it works well enough for now... +var nodeVersion = process.version.slice(1).split('.').map(Number) + +test('then', function(t) { + var listener = addListner(); + + var promise = new Promise(function(accept, reject) { + listener.currentName = 'accept'; + accept(10); + }); + + promise.then(function(val) { + listener.currentName = 'nextTick in first then'; + process.nextTick(function() { + t.strictEqual(val, 10); + }); + listener.currentName = 'first then continuation'; + }); + + listener.currentName = 'setImmediate in root'; + setImmediate(function() { + promise.then(function(val) { + t.strictEqual(val, 10); + t.strictEqual(this, global); + listener.currentName = 'setTimeout in 2nd then'; + setTimeout(function() { + t.deepEqual(listener.root, expected); + t.end(); + }); + listener.currentName = '2nd then continuation'; + }); + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [ + { + name: 'accept', + children: [ + { + name: 'nextTick in first then', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'first then continuation', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'setTimeout in 2nd then', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 2, + after: 2, + error: 0 + }, + { + name: 'accept', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'setImmediate in root', + children: [ + { + name: 'first then continuation', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } +}); + +test('catch', function(t) { + var listener = addListner(); + + var promise = new Promise(function(accept, reject) { + listener.currentName = 'reject'; + reject(15); + }); + + listener.currentName = 'catch'; + promise.catch(function(val) { + listener.currentName = 'nextTick in catch'; + process.nextTick(function() { + t.strictEqual(val, 15); + }); + listener.currentName = 'catch continuation'; + }); + + listener.currentName = 'setImmediate in root'; + setImmediate(function() { + promise.then( + function fullfilled() { + throw new Error('should not be called on reject'); + }, + function rejected(val) { + t.strictEqual(val, 15); + t.strictEqual(this, global); + listener.currentName = 'setTimeout in then'; + setTimeout(function() { + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 3) { + expected.children.splice(-1, 0, { + name: 'catch', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + t.deepEqual(listener.root, expected); + t.end(); + }); + listener.currentName = 'then continuation'; + } + ) + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [ + { + name: 'reject', + children: [ + { + name: 'nextTick in catch', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'setTimeout in then', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 2, + after: 2, + error: 0 + }, + { + name: 'setImmediate in root', + children: [ + { + name: 'catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'catch continuation', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + }; +}); + +test('Promise.resolve', function resolveTest(t) { + var listener = addListner(); + + listener.currentName = 'resolve'; + var p = Promise.resolve(123); + + p.then(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + t.equal(value, 123); + t.deepEqual(listener.root, { + name: 'root', + children: [{ + name: 'resolve', + children: [{ + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }], + before: 1, + after: 1, + error: 0 + }, + { + name: 'resolve', + children: [], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + }); + t.end(); + }); + process.removeAsyncListener(listener.listener); + }); +}); + +test('Promise.reject', function rejectTest(t) { + var listener = addListner(); + + listener.currentName = 'reject'; + var p = Promise.reject(123); + + listener.currentName = 'catch'; + p.catch(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + t.equal(value, 123); + + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 2) { + expected.children.push({ + name: 'catch', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = 'catch continuation'; + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [{ + name: 'reject', + children: [ + { + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + } +}); + +test('Promise.all', function allTest(t) { + var listener = addListner(); + + listener.currentName = 'resolve 1'; + var a = Promise.resolve(123); + listener.currentName = 'resolve 2'; + var b = Promise.resolve(456); + listener.currentName = 'all'; + var p = Promise.all([a, b]); + + p.then(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + process.removeAsyncListener(listener.listener); + t.deepEqual(value, [123, 456]); + t.deepEqual(listener.root, { + name: 'root', + children: [{ + name: 'resolve 1', + children: [{ + // Internal continuation of a used for making the race future. + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }], + before: 1, + after: 1, + error: 0 + }, { + name: 'resolve 2', + children: [ + { + name: 'all', + children: [ + { + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + // Internal continuation of b used for making the race future. + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + }); + t.end(); + }); + + listener.currentName = 'then continuation'; + }); +}); + +test('Promise.all reject', function allTest(t) { + var listener = addListner(); + + listener.currentName = 'resolve'; + var a = Promise.resolve(123); + listener.currentName = 'reject'; + var b = Promise.reject(456); + listener.currentName = 'all'; + var p = Promise.all([a, b]); + + p.catch(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 3) { + expected.children.push({ + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + process.removeAsyncListener(listener.listener); + t.equal(value, 456); + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = 'catch continuation'; + }); + + var expected = { + name: 'root', + children: [{ + name: 'resolve', + children: [{ + // Internal continuation of a used for making the race future. + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }], + before: 1, + after: 1, + error: 0 + }, { + name: 'reject', + children: [ + { + name: 'all', + children: [ + { + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + // Internal continuation of b used for making the race future. + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'all', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'all', + children: [], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + } +}); + +test('Promise.race', function raceTest(t) { + var listener = addListner(); + + listener.currentName = 'resolve 1'; + var a = Promise.resolve(123); + listener.currentName = 'resolve 2'; + var b = Promise.resolve(456); + listener.currentName = 'race'; + var p = Promise.race([a, b]); + + p.then(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + process.removeAsyncListener(listener.listener); + t.equal(value, 123); + t.deepEqual(listener.root, { + name: 'root', + children: [{ + name: 'resolve 1', + children: [ + { + name: 'race', + children: [ + { + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + // Internal continuation of a used for making the race future. + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, { + name: 'resolve 2', + children: [{ + // Internal continuation of b used for making the race future. + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + }); + t.end(); + }); + + listener.currentName = 'then continuation'; + }); +}); + +test('Promise.race - reject', function raceTest(t) { + var listener = addListner(); + + listener.currentName = 'reject'; + var a = Promise.reject(123); + listener.currentName = 'resolve'; + var b = Promise.resolve(456); + listener.currentName = 'race'; + var p = Promise.race([a, b]); + + p.catch(function then(value) { + listener.currentName = 'nextTick'; + process.nextTick(function next() { + process.removeAsyncListener(listener.listener); + t.equal(value, 123); + + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 3) { + expected.children.push({ + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = 'catch continuation'; + }); + + var expected = { + name: 'root', + children: [{ + name: 'reject', + children: [ + { + name: 'race', + children: [ + { + name: 'nextTick', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + // Internal continuation of a used for making the race future. + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, { + name: 'resolve', + children: [{ + // Internal continuation of b used for making the race future. + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'race', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'race', + children: [], + before: 1, + after: 1, + error: 0 + }], + before: 0, + after: 0, + error: 0 + } +}); + +test('instanceof', function diferTest(t) { + var p = Promise.resolve(10); + + t.ok(p instanceof Promise, 'instanceof should work on wrapped Promise'); + t.ok(p instanceof unwrappedPromise, 'instanceof should work on unwrapped Promise'); + t.end() +}); + +test('then chain with promise', function(t) { + var listener = addListner(); + + listener.currentName = 'accept'; + var promise = Promise.resolve(10); + + promise + .then(function(val) { + return new Promise(function wait(accept) { + listener.currentName = 'nextTick in nested promise'; + process.nextTick(function() { + listener.currentName = 'accept from nextTick'; + accept(val); + }); + }); + }) + .then(function validate(val) { + t.strictEqual(val, 10); + t.strictEqual(this, global); + + listener.currentName = 'setTimeout in 2nd then'; + setTimeout(function() { + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = '2nd then continuation'; + }); + + process.removeAsyncListener(listener.listener); + + // Promise resolution changed slightly in node v6, + // now resolve/reject wraps again on completion. + var children = [] + if (nodeVersion[0] >= 6) { + children.push({ + name: 'accept from nextTick', + children: [], + before: 0, + after: 0, + error: 0 + }) + } + children.push( + { + name: 'setTimeout in 2nd then', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ) + + var expected = { + name: 'root', + children: [ + { + name: 'accept', + children: [ + { + name: 'nextTick in nested promise', + children: [ + { + name: 'accept from nextTick', + children: children, + before: children.length - 1, + after: children.length - 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'accept', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'accept', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } +}); + +test('then chain with rejected promise', function(t) { + var listener = addListner(); + + listener.currentName = 'reject'; + var promise = Promise.reject(10); + + promise + .then(fail, function(val) { + return new Promise(function wait(accept, reject) { + listener.currentName = 'nextTick in nested promise'; + process.nextTick(function() { + listener.currentName = 'reject from nextTick'; + reject(val); + }); + }); + }) + .then(fail, function validate(val) { + t.strictEqual(val, 10); + t.strictEqual(this, global); + + listener.currentName = 'setTimeout in 2nd then'; + setTimeout(function() { + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 2) { + expected.children.splice(1, 0, { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = '2nd then continuation'; + }); + + function fail() { + t.fail('should not be called'); + t.end(); + } + + process.removeAsyncListener(listener.listener); + + // Promise resolution changed slightly in node v6, + // now resolve/reject wraps again on completion. + var children = [] + if (nodeVersion[0] >= 6) { + children.push({ + name: 'reject from nextTick', + children: [], + before: 0, + after: 0, + error: 0 + }) + } + children.push( + { + name: 'setTimeout in 2nd then', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ) + + var expected = { + name: 'root', + children: [ + { + name: 'reject', + children: [ + { + name: 'nextTick in nested promise', + children: [ + { + name: 'reject from nextTick', + children: children, + before: children.length - 1, + after: children.length - 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } +}); + +test('multi catch with promise', function(t) { + var listener = addListner(); + + listener.currentName = 'reject'; + var promise = Promise.reject(10); + + promise + .catch(function(val) { + return new Promise(function wait(accept, reject) { + listener.currentName = 'nextTick in nested promise'; + process.nextTick(function() { + listener.currentName = 'reject from nextTick'; + reject(val); + }); + }); + }) + .catch(function validate(val) { + t.strictEqual(val, 10); + t.strictEqual(this, global); + + listener.currentName = 'setTimeout in 2nd catch'; + setTimeout(function() { + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 2) { + expected.children.splice(1, 0, { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = '2nd catch continuation'; + }); + + process.removeAsyncListener(listener.listener); + + // Promise resolution changed slightly in node v6, + // now resolve/reject wraps again on completion. + var children = [] + if (nodeVersion[0] >= 6) { + children.push({ + name: 'reject from nextTick', + children: [], + before: 0, + after: 0, + error: 0 + }) + } + children.push( + { + name: 'setTimeout in 2nd catch', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd catch continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ) + + var expected = { + name: 'root', + children: [ + { + name: 'reject', + children: [ + { + name: 'nextTick in nested promise', + children: [ + { + name: 'reject from nextTick', + children: children, + before: children.length - 1, + after: children.length - 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } +}); + +test('throw in executor', function(t) { + var listener = addListner(); + + var promise = new Promise(function unsafe() { + listener.currentName = 'throw'; + throw 10; + }); + + promise.catch(function(val) { + t.equal(val, 10, 'should match thrown value') + if (listener.root.children.length === 2) { + expected.children.splice(1, 0, { + name: 'throw', + children: [], + before: 1, + after: 0, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [ + { + name: 'throw', + children: [ + ], + before: 1, + after: 0, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } +}); + +test('Promise.resolve().catch().then()', function (t) { + var listenerState = addListner(); + + t.plan(1); + listenerState.currentName = 'resolve' + var p = Promise.resolve(1) + + listenerState.currentName = 'return of 1st catch that didnt get run' + p = p.catch(function () {}) + + p = p.then(function () { + listenerState.currentName = 'returned by 1st then' + throw new Error() + }) + + p = p.catch(function () { + listenerState.currentName = 'returned by 2nd catch' + throw new Error + }); + + p = p.then(function () {}, function () { + listenerState.currentName = 'returned by 2nd then' + throw new Error() + }); + + p = p.catch(function () { + t.deepEqual(listenerState.root, expected); + }); + + var expected = { + name: 'root', + children: [ + { + name: 'resolve', + children: [ + { + name: 'return of 1st catch that didnt get run', + children: [ + { + name: 'returned by 1st then', + children: [ + { + name: 'returned by 2nd catch', + children: [ + { + name: 'returned by 2nd then', + children: [], + before: 1, + after: 0, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: 'return of 1st catch that didnt get run', + children: [], + before: 1, + after: 0, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } + + process.removeAsyncListener(listenerState.listener); +}); + +test('continue from unwrapped promise', function(t) { + var listener = addListner(); + + listener.currentName = 'resolve'; + resolvedBeforeWrap.then(function(val) { + t.equal(val, 123, 'should match resolved value'); + listener.currentName = '2nd resolve'; + return 456; + }).then(function (val) { + t.equal(val, 456, 'should match resolved value'); + t.deepEqual(listener.root, expected); + t.end(); + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [{ + name : 'resolve', + children : [{ + name : '2nd resolve', + children : [], + before : 1, + after : 0, + error : 0 + }], + before : 1, + after : 1, + error : 0 + }, + { + name : 'resolve', + children : [], + before : 1, + after : 0, + error : 0 + }], + before: 0, + after: 0, + error: 0 + }; +}); + +test('return unwrapped promise', function(t) { + var listener = addListner(); + + listener.currentName = 'resolve'; + Promise.resolve(890).then(function (val) { + t.equal(val, 890, 'should match resolved value'); + return resolvedBeforeWrap; + }).then(function(val) { + t.equal(val, 123, 'should match resolved value'); + return 456; + }).then(function (val) { + t.equal(val, 456, 'should match resolved value'); + t.deepEqual(listener.root, expected); + t.end(); + }); + + process.removeAsyncListener(listener.listener); + + var expected = { + name: 'root', + children: [{ + name : 'resolve', + children : [], + before : 1, + after : 1, + error : 0 + }, + { + name : 'resolve', + children : [], + before : 1, + after : 1, + error : 0 + }, + { + name : 'resolve', + children : [{ + name : 'resolve', + children : [], + before : 1, + after : 0, + error : 0 + }], + before : 1, + after : 1, + error : 0 + }, + { + name : 'resolve', + children : [], + before : 1, + after : 0, + error : 0 + }], + before: 0, + after: 0, + error: 0 + }; +}); + +test('resume context after unwrapped promise', function(t) { + var listener = addListner(); + + listener.currentName = 'resolve'; + var wrapped = Promise.resolve(456); + + listener.currentName = 'unwrapped resolve'; + resolvedBeforeWrap.then(function(val) { + t.equal(val, 123, 'should match resolved value'); + listener.currentName = 'maybe internal resolve'; + return wrapped + }).then(function (val) { + t.equal(val, 456, 'should match resolved value'); + listener.currentName = 'return after continuing from wrapped promise'; + return 89 + }).then(function (val) { + t.equal(val, 89, 'should match resolved value'); + t.deepEqual(listener.root, expected); + t.end(); + }); + + process.removeAsyncListener(listener.listener); + + // Promise resolution changed slightly in node v6, + // now resolve/reject wraps again on completion. + var children = [] + if (nodeVersion[0] >= 6) { + children.push({ + name : 'maybe internal resolve', + children : [], + before : 0, + after : 0, + error : 0 + }) + } + children.push({ + name : 'return after continuing from wrapped promise', + children : [], + before : 1, + after : 0, + error : 0 + }) + + var expected = { + name: 'root', + children: [{ + name : 'resolve', + children : children, + before : children.length, + after : children.length, + error : 0 + }, + { + name : 'unwrapped resolve', + children : [], + before : 1, + after : 1, + error : 0 + }, + { + name : 'unwrapped resolve', + children : [], + before : 1, + after : 1, + error : 0 + }, + { + name : 'unwrapped resolve', + children : [], + before : 1, + after : 0, + error : 0 + }], + before: 0, + after: 0, + error: 0 + }; +}); + +function addListner() { + var listener = process.addAsyncListener({ + create: create, + before: before, + after: after, + error: error + }); + + + var state = { + listener: listener, + currentName: 'root' + }; + + state.root = create(); + state.current = state.root; + + return state; + + function create () { + var node = { + name: state.currentName, + children: [], + before: 0, + after: 0, + error: 0 + }; + + if(state.current) state.current.children.push(node); + return node; + } + + function before(ctx, node) { + state.current = node; + state.current.before++; + } + + function after(ctx, node) { + node.after++; + state.current = null; + } + + function error(ctx, node) { + node.error++; + state.current = null; + return false; + } +} + +// for the following, +// +// https://github.com/v8/v8/commits/master/src/js/promise-extra.js +// +// is helpful context -- none of these are part of ES2015 promises, and were +// set up to be removed. + +// Node.js = 6) { + children.push({ + name: 'accept from nextTick', + children: [], + before: 0, + after: 0, + error: 0 + }) + } + children.push( + { + name: 'setTimeout in 2nd chain', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd then continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ) + + var expected = { + name: 'root', + children: [ + { + name: 'accept', + children: [ + { + name: 'nextTick in nested promise', + children: [ + { + name: 'accept from nextTick', + children: children, + before: children.length - 1, + after: children.length - 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'accept', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'accept', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } + }); + + test('multi chain with rejected promise', function(t) { + var listener = addListner(); + + listener.currentName = 'reject'; + var promise = Promise.reject(10); + + promise + .chain(fail, function(val) { + return new Promise(function wait(accept, reject) { + listener.currentName = 'nextTick in nested promise'; + process.nextTick(function() { + listener.currentName = 'reject from nextTick'; + reject(val); + }); + }); + }) + .chain(fail, function validate(val) { + t.strictEqual(val, 10); + t.strictEqual(this, global); + + listener.currentName = 'setTimeout in 2nd chain'; + setTimeout(function() { + // some version of iojs use nextTick for some parts of its async + if (listener.root.children.length === 2) { + expected.children.splice(1, 0, { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + t.deepEqual(listener.root, expected); + t.end(); + }); + + listener.currentName = '2nd chain continuation'; + }); + + function fail() { + t.fail('should not be called'); + t.end(); + } + + process.removeAsyncListener(listener.listener); + + // Promise resolution changed slightly in node v6, + // now resolve/reject wraps again on completion. + var children = [] + if (nodeVersion[0] >= 6) { + children.push({ + name: 'reject from nextTick', + children: [], + before: 0, + after: 0, + error: 0 + }) + } + children.push( + { + name: 'setTimeout in 2nd chain', + children: [], + before: 1, + after: 0, + error: 0 + }, + { + name: '2nd chain continuation', + children: [], + before: 0, + after: 0, + error: 0 + } + ) + + var expected = { + name: 'root', + children: [ + { + name: 'reject', + children: [ + { + name: 'nextTick in nested promise', + children: [ + { + name: 'reject from nextTick', + children: children, + before: children.length - 1, + after: children.length - 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + }, + { + name: 'reject', + children: [], + before: 0, + after: 0, + error: 0 + }, + { + name: 'reject', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + } + }); +} + +test('es6 subclasses', function(t) { + if (nodeVersion[0] < 6) { + t.pass('class syntax is not supported before node 6'); + t.end(); + return; + } + + // Promise subclasses do 2 asserts per promise. + t.plan(13); + + var SubclassedPromise = require('./promise-subclass.js'); + var StandardSubclassedPromise = SubclassedPromise(t, false); + var SubclassedPromiseCustomSpecies = SubclassedPromise(t, true); + + var s = StandardSubclassedPromise.resolve(42).then(function(val) { + t.strictEqual(val, 42); + t.end(); + }); + + var p1 = + new StandardSubclassedPromise(function(resolve) { resolve(123); }) + .then(function() {}); + t.ok(p1 instanceof StandardSubclassedPromise, + 'should be StandardSubclassedPromise instance'); + t.ok(p1 instanceof unwrappedPromise, 'should be unwrappedPromise instance'); + t.ok(p1 instanceof Promise, 'should be base Promise instance'); + + var p2 = + new SubclassedPromiseCustomSpecies(function(resolve) { resolve(123); }) + .then(function() {}); + t.notOk(p2 instanceof SubclassedPromiseCustomSpecies, + 'should not be SubclassedPromiseCustomSpecies instance'); + t.ok(p2 instanceof unwrappedPromise, 'should be unwrappedPromise instance'); + t.ok(p2 instanceof Promise, 'should be base Promise instance'); +}); diff --git a/node_modules/async-listener/test/no-after-following-error.tap.js b/node_modules/async-listener/test/no-after-following-error.tap.js new file mode 100644 index 0000000..107f9a8 --- /dev/null +++ b/node_modules/async-listener/test/no-after-following-error.tap.js @@ -0,0 +1,31 @@ +var test = require('tap').test; + +if (!global.setImmediate) global.setImmediate = setTimeout; + +test("after handler not run on throw", function (t) { + t.plan(2); + + if (!process.addAsyncListener) require('../index.js'); + + var key = process.createAsyncListener( + { + create : function () { return {}; }, + after : function asyncAfter() { t.fail("after was called"); }, + error : function asyncError(domain) { t.ok(domain, "got error"); } + } + ); + + process.addAsyncListener(key); + + setImmediate(function () { + throw new Error('whoops'); + }); + + function handler(err) { + process.removeAsyncListener(key); + process.removeListener('uncaughtException', handler); + t.ok(err, "error was propagated"); + } + + process.on('uncaughtException', handler); +}); diff --git a/node_modules/async-listener/test/overlapping-nexttick.tap.js b/node_modules/async-listener/test/overlapping-nexttick.tap.js new file mode 100644 index 0000000..2409500 --- /dev/null +++ b/node_modules/async-listener/test/overlapping-nexttick.tap.js @@ -0,0 +1,192 @@ +var test = require('tap').test + , assert = require('assert') + ; + +if (!global.setImmediate) global.setImmediate = setTimeout; + +/** + * + * + * + * + * SETUP AND BOILERPLATE + * + * + * + */ +if (!process.addAsyncListener) require('../index.js'); + +/* + * CLS code + */ +function Namespace () { + this.active = Object.create(null); + this._stack = []; + this.id = null; +} + +Namespace.prototype.set = function (key, value) { + this.active[key] = value; + return value; +}; + +Namespace.prototype.get = function (key) { + return this.active[key]; +}; + +Namespace.prototype.enter = function (context) { + assert.ok(context, "context must be provided for entering"); + + this._stack.push(this.active); + this.active = context; +}; + +Namespace.prototype.exit = function (context) { + assert.ok(context, "context must be provided for exiting"); + + if (this.active === context) { + assert.ok(this._stack.length, "can't remove top context"); + this.active = this._stack.pop(); + return; + } + + var index = this._stack.lastIndexOf(context); + + assert.ok(index >= 0, "context not currently entered; can't exit"); + assert.ok(index, "can't remove top context"); + + this.active = this._stack[index - 1]; + this._stack.length = index - 1; +}; + +Namespace.prototype.createContext = function () { + return Object.create(this.active); +}; + +Namespace.prototype.run = function (fn) { + var context = this.createContext(); + this.enter(context); + try { + fn(context); + return context; + } + finally { + this.exit(context); + } +}; + +Namespace.prototype.bind = function (fn, context) { + if (!context) context = this.active; + var self = this; + return function () { + self.enter(context); + try { + return fn.apply(this, arguments); + } + finally { + self.exit(context); + } + }; +}; + +function create(name) { + assert.ok(name, "namespace must be given a name!"); + + var namespace = new Namespace(name); + namespace.id = process.addAsyncListener( + { + create : function () { return namespace.active; }, + before : function (context, domain) { namespace.enter(domain); }, + after : function (context, domain) { namespace.exit(domain); } + } + ); + + return namespace; +} + +/* + * Transaction code + */ +var id = 1337; +function Transaction() { this.id = id++; } + +/* + * Tracer code + */ +var namespace = create("__NR_tracer"); +function getTransaction() { + var state = namespace.get('state'); + if (state) return state.transaction; +} + +function transactionProxy(handler) { + return function wrapTransactionInvocation() { + var state = {transaction : new Transaction()}; + + var context = namespace.createContext(); + context.state = state; + + return namespace.bind(handler, context).apply(this, arguments); + }; +} + + +/** + * + * + * + * + * TESTS + * + * + * + */ + +test("overlapping requests", function (t) { + t.plan(2); + + t.test("simple overlap", function (t) { + t.plan(3); + + setImmediate(function () { console.log('!'); }); + + var n = create("test2"); + t.ok(!n.get('state'), "state should not yet be visible"); + + n.run(function () { + n.set('state', true); + t.ok(n.get('state'), "state should be visible"); + + setImmediate(function () { t.ok(n.get('state'), "state should be visible"); }); + }); + }); + + t.test("two process.nextTicks", function (t) { + t.plan(6); + + function handler(id) { + var transaction = getTransaction(); + t.ok(transaction, "transaction should be visible"); + t.equal((transaction || {}).id, id, "transaction matches"); + } + + t.ok(!getTransaction(), "transaction should not yet be visible"); + + var first; + var proxied = transactionProxy(function () { + t.ok(getTransaction(), "transaction should be visible"); + + first = getTransaction().id; + process.nextTick(function () { handler(first); }, 42); + }); + proxied(); + + process.nextTick(transactionProxy(function () { + t.ok(getTransaction(), "transaction should be visible"); + + var second = getTransaction().id; + t.notEqual(first, second, "different transaction IDs"); + process.nextTick(function () { handler(second); }, 42); + }), 42); + }); +}); diff --git a/node_modules/async-listener/test/promise-subclass.js b/node_modules/async-listener/test/promise-subclass.js new file mode 100644 index 0000000..2fb3eb4 --- /dev/null +++ b/node_modules/async-listener/test/promise-subclass.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = (tap, customSpecies) => { + if (customSpecies) { + return class SubclassedPromise extends Promise { + static get [Symbol.species]() { return Promise; } + then(onSuccess, onReject) { + tap.type(onSuccess, 'function'); + tap.type(onReject, 'undefined'); + return super.then(onSuccess, onReject); + } + }; + } else { + return class SubclassedPromise extends Promise { + then(onSuccess, onReject) { + tap.type(onSuccess, 'function'); + tap.type(onReject, 'undefined'); + return super.then(onSuccess, onReject); + } + }; + } +}; diff --git a/node_modules/async-listener/test/simple-counter-with-io.tap.js b/node_modules/async-listener/test/simple-counter-with-io.tap.js new file mode 100644 index 0000000..39b5cb2 --- /dev/null +++ b/node_modules/async-listener/test/simple-counter-with-io.tap.js @@ -0,0 +1,28 @@ +var test = require('tap').test; + +if (!global.setImmediate) global.setImmediate = setTimeout; + +test("asyncListeners work as expected with process.nextTick", function (t) { + t.plan(1); + + if (!process.addAsyncListener) require('../index.js'); + + console.log('+'); + // comment out this line to get the expected result: + setImmediate(function () { console.log('!'); }); + + var counter = 1; + var current; + process.addAsyncListener( + { + create : function listener() { return counter++; }, + before : function (_, domain) { current = domain; }, + after : function () { current = null; } + } + ); + + setImmediate(function () { t.equal(current, 1); }); + // uncomment this line to get the expected result: + // process.removeAsyncListener(id); +}); + diff --git a/node_modules/async-listener/test/simple-counter.tap.js b/node_modules/async-listener/test/simple-counter.tap.js new file mode 100644 index 0000000..a611132 --- /dev/null +++ b/node_modules/async-listener/test/simple-counter.tap.js @@ -0,0 +1,29 @@ +var test = require('tap').test; + +test("asyncListeners work as expected with process.nextTick", function (t) { + t.plan(4); + + if (!process.addAsyncListener) require('../index.js'); + + var active + , cntr = 0 + ; + + process.addAsyncListener( + { + create : function () { return { val : ++cntr }; }, + before : function (context, data) { active = data.val; }, + after : function () { active = null; } + } + ); + + process.nextTick(function () { + t.equal(active, 1); + process.nextTick(function () { t.equal(active, 3); }); + }); + + process.nextTick(function () { + t.equal(active, 2); + process.nextTick(function () { t.equal(active, 4); }); + }); +}); diff --git a/node_modules/async-listener/test/simplified-error.simple.js b/node_modules/async-listener/test/simplified-error.simple.js new file mode 100644 index 0000000..a885aa2 --- /dev/null +++ b/node_modules/async-listener/test/simplified-error.simple.js @@ -0,0 +1,67 @@ +// 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 (!process.addAsyncListener) require('../index.js'); + +var assert = require('assert'); +var fs = require('fs'); +var addListener = process.addAsyncListener; +var removeListener = process.removeAsyncListener; + +var caught = 0; +var expectCaught = 0; + +var callbacksObj = { + error: function(domain, er) { + caught++; + + switch (er.message) { + case 'fs - nested file does not exist': + return true; + + default: + return false; + } + } +}; + +process.on('exit', function() { + console.log('caught:', caught); + console.log('expected:', expectCaught); + assert.equal(caught, expectCaught, 'caught all expected errors'); + console.log('ok'); +}); + +var listener = process.createAsyncListener(callbacksObj); + +// Nested FS +process.nextTick(function() { + addListener(listener); + + setTimeout(function() { + fs.stat('does not exist', function() { + throw new Error('fs - nested file does not exist'); + }); + expectCaught++; + }); + + removeListener(listener); +}); diff --git a/node_modules/async-listener/test/spawn.tap.js b/node_modules/async-listener/test/spawn.tap.js new file mode 100644 index 0000000..1f78845 --- /dev/null +++ b/node_modules/async-listener/test/spawn.tap.js @@ -0,0 +1,100 @@ +var test = require('tap').test + , assert = require('assert') + ; + +if (!global.setImmediate) global.setImmediate = setTimeout; + +if (!process.addAsyncListener) require('../index.js'); + +var childProcess = require('child_process') + , exec = childProcess.exec + , execFile = childProcess.execFile + , spawn = childProcess.spawn + ; + +test('ChildProcess', function (t) { + t.plan(3); + + t.test('exec', function (t) { + t.plan(3); + + var active + , cntr = 0 + ; + + process.addAsyncListener( + { + create : function () { return { val : ++cntr }; }, + before : function (context, data) { active = data.val; }, + after : function () { active = null; } + } + ); + + t.equal(active, undefined, + 'starts in initial context'); + process.nextTick(function () { + t.equal(active, 1, + 'after tick: 1st context'); + var child = exec('node --version'); + child.on('exit', function (code) { + t.ok(active >= 2, + 'after exec#exit: entered additional contexts'); + }) + }); + }); + + t.test('execFile', function (t) { + t.plan(3); + + var active + , cntr = 0 + ; + + process.addAsyncListener( + { + create : function () { return { val : ++cntr }; }, + before : function (context, data) { active = data.val; }, + after : function () { active = null; } + } + ); + + t.equal(active, undefined, + 'starts in initial context'); + process.nextTick(function () { + t.equal(active, 1, + 'after nextTick: 1st context'); + execFile('node', ['--version'], function (err, code) { + t.ok(active >= 2, + 'after execFile: entered additional contexts'); + }); + }); + }); + + t.test('spawn', function (t) { + t.plan(3); + + var active + , cntr = 0 + ; + + process.addAsyncListener( + { + create : function () { return { val : ++cntr }; }, + before : function (context, data) { active = data.val; }, + after : function () { active = null; } + } + ); + + t.equal(active, undefined, + 'starts in initial context'); + process.nextTick(function () { + t.equal(active, 1, + 'after tick: 1st context'); + var child = spawn('node', ['--version']); + child.on('exit', function (code) { + t.ok(active >= 2, + 'after spawn#exit: entered additional contexts'); + }) + }); + }); +}); diff --git a/node_modules/async-listener/test/timers.tap.js b/node_modules/async-listener/test/timers.tap.js new file mode 100644 index 0000000..aeeade4 --- /dev/null +++ b/node_modules/async-listener/test/timers.tap.js @@ -0,0 +1,159 @@ +if (!process.addAsyncListener) require('../index.js'); + +var test = require('tap').test; +var net = require('net'); + +test('test process.nextTick', function (t) { + test_helper(t, function (listener, done) { + listener.currentName = 'process.nextTick'; + process.nextTick(done); + }, { + name: 'root', + children: [ + { + name: 'process.nextTick', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + }); +}); + +test('test setTimeout', function (t) { + test_helper(t, function (listener, done) { + listener.currentName = 'setTimeout'; + setTimeout(done, 1); + }, { + name: 'root', + children: [ + { + name: 'setTimeout', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + }); +}); + +test('test setImmediate', function (t) { + test_helper(t, function (listener, done) { + listener.currentName = 'setImmediate'; + setImmediate(done); + }, { + name: 'root', + children: [ + { + name: 'setImmediate', + children: [], + before: 1, + after: 1, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + }); +}); + +test('test setInterval', function (t) { + test_helper(t, function (listener, done) { + listener.currentName = 'setInterval'; + var count = 0; + var interval = setInterval(function () { + if (++count === 2) { + clearInterval(interval); + done(); + } + }); + }, { + name: 'root', + children: [ + { + name: 'setInterval', + children: [], + before: 2, + after: 2, + error: 0 + } + ], + before: 0, + after: 0, + error: 0 + }); +}); + +function test_helper (t, run, expect) { + // Trigger callback out-of-band from async listener + var done; + var interval = setInterval(function () { + if (done) { + clearInterval(interval); + t.deepEqual(listener.root, expect); + t.end(); + } + }, 5); + + var listener = addListner(); + run(listener, function () { done = true; }); + process.removeAsyncListener(listener.listener); +} + +function addListner() { + var listener = process.addAsyncListener({ + create: create, + before: before, + after: after, + error: error + }); + + + var state = { + listener: listener, + currentName: 'root' + }; + + state.root = create(); + state.current = state.root; + + return state; + + function create () { + var node = { + name: state.currentName, + children: [], + before: 0, + after: 0, + error: 0 + }; + + if(state.current) state.current.children.push(node); + return node; + } + + function before(ctx, node) { + state.current = node; + state.current.before++; + } + + function after(ctx, node) { + node.after++; + state.current = null; + } + + function error(ctx, node) { + node.error++; + state.current = null; + return false; + } +} diff --git a/node_modules/async-listener/test/zlib.tap.js b/node_modules/async-listener/test/zlib.tap.js new file mode 100644 index 0000000..55938e3 --- /dev/null +++ b/node_modules/async-listener/test/zlib.tap.js @@ -0,0 +1,214 @@ +if (!process.addAsyncListener) require('../index.js'); + +var test = require('tap').test; +var zlib = require('zlib'); + +// Convert semver string to number set +// TODO: This is *very* naive structure to check versions with, +// but it works well enough for now... +var nodeVersion = process.version.slice(1).split('.').map(Number) + +var compressors = ['deflate', 'deflateRaw', 'gzip']; +var decompressors = ['inflate', 'inflateRaw', 'gunzip']; + +compressors.forEach(function (method) { + var name = 'zlib.' + method; + var el = { + name: name, + children: [], + before: 1, + after: 1, + error: 0 + }; + var list = [ el ]; + if (nodeVersion[0] >= 6) { + list.push(el); + } + + var children = [ + { + name: name, + // Compressors use streams internally, + // so there's a bunch of nested stuff. + children: [ + { + name: name, + children: [ + { + name: name, + children: list, + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ] + if (nodeVersion[0] >= 9) { + children.unshift({ + name: name, + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + test('test ' + name, function (t) { + test_helper(t, function (listener, done) { + listener.currentName = name; + zlib[method](new Buffer('Goodbye World'), done); + }, { + name: 'root', + children: children, + before: 0, + after: 0, + error: 0 + }); + }); +}); + +decompressors.forEach(function (method, i) { + var preMethod = compressors[i]; + var name = 'zlib.' + method; + var el = { + name: name, + children: [], + before: 1, + after: 1, + error: 0 + }; + var list = [ el ]; + if (nodeVersion[0] >= 6) { + list.push(el); + } + + var children = [ + { + name: name, + // Compressors use streams internally, + // so there's a bunch of nested stuff. + children: [ + { + name: name, + children: [ + { + name: name, + children: list, + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ], + before: 1, + after: 1, + error: 0 + } + ] + if (nodeVersion[0] >= 9) { + children.unshift({ + name: name, + children: [], + before: 1, + after: 1, + error: 0 + }) + } + + test('test ' + name, function (t) { + zlib[preMethod](new Buffer('Goodbye World'), function (err, buf) { + t.ok(!err, 'should not have errored in preparation') + test_helper(t, function (listener, done) { + listener.currentName = name; + zlib[method](buf, done); + }, { + name: 'root', + children: children, + before: 0, + after: 0, + error: 0 + }); + }); + }); +}); + +function test_helper (t, run, expect) { + // Trigger callback out-of-band from async listener + var args; + var interval = setInterval(function () { + if (args) { + clearInterval(interval); + t.ok(!args[0], 'should not have errored'); + t.deepEqual(listener.root, expect); + t.end(); + } + }, 5); + + var listener = addListner(); + run(listener, function () { + args = Array.prototype.slice.call(arguments); + }); + process.removeAsyncListener(listener.listener); +} + +function addListner() { + var listener = process.addAsyncListener({ + create: create, + before: before, + after: after, + error: error + }); + + + var state = { + listener: listener, + currentName: 'root' + }; + + state.root = create(); + state.current = state.root; + + return state; + + function create () { + var node = { + name: state.currentName, + children: [], + before: 0, + after: 0, + error: 0 + }; + + if(state.current) state.current.children.push(node); + return node; + } + + function before(ctx, node) { + state.current = node; + state.current.before++; + } + + function after(ctx, node) { + node.after++; + state.current = null; + } + + function error(ctx, node) { + node.error++; + state.current = null; + return false; + } +} diff --git a/node_modules/asynckit/LICENSE b/node_modules/asynckit/LICENSE new file mode 100644 index 0000000..c9eca5d --- /dev/null +++ b/node_modules/asynckit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +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. diff --git a/node_modules/asynckit/README.md b/node_modules/asynckit/README.md new file mode 100644 index 0000000..ddcc7e6 --- /dev/null +++ b/node_modules/asynckit/README.md @@ -0,0 +1,233 @@ +# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) + +Minimal async jobs utility library, with streams support. + +[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) + +[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) +[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) +[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) + + + +AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. +Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. + +It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. + +| compression | size | +| :----------------- | -------: | +| asynckit.js | 12.34 kB | +| asynckit.min.js | 4.11 kB | +| asynckit.min.js.gz | 1.47 kB | + + +## Install + +```sh +$ npm install --save asynckit +``` + +## Examples + +### Parallel Jobs + +Runs iterator over provided array in parallel. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will terminate rest of the active jobs (if abort function is provided) +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var parallel = require('asynckit').parallel + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , target = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// async job accepts one element from the array +// and a callback function +function asyncJob(item, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var parallel = require('asynckit/parallel') + , assert = require('assert') + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] + , target = [] + , keys = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); + assert.deepEqual(keys, expectedKeys); +}); + +// supports full value, key, callback (shortcut) interface +function asyncJob(item, key, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + keys.push(key); + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). + +### Serial Jobs + +Runs iterator over provided array sequentially. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will not proceed to the rest of the items in the list +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var serial = require('asynckit/serial') + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// extended interface (item, key, callback) +// also supported for arrays +function asyncJob(item, key, cb) +{ + target.push(key); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var serial = require('asynckit').serial + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , target = [] + ; + + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// shortcut interface (item, callback) +// works for object as well as for the arrays +function asyncJob(item, cb) +{ + target.push(item); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). + +_Note: Since _object_ is an _unordered_ collection of properties, +it may produce unexpected results with sequential iterations. +Whenever order of the jobs' execution is important please use `serialOrdered` method._ + +### Ordered Serial Iterations + +TBD + +For example [compare-property](compare-property) package. + +### Streaming interface + +TBD + +## Want to Know More? + +More examples can be found in [test folder](test/). + +Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. + +## License + +AsyncKit is licensed under the MIT license. diff --git a/node_modules/asynckit/bench.js b/node_modules/asynckit/bench.js new file mode 100644 index 0000000..c612f1a --- /dev/null +++ b/node_modules/asynckit/bench.js @@ -0,0 +1,76 @@ +/* eslint no-console: "off" */ + +var asynckit = require('./') + , async = require('async') + , assert = require('assert') + , expected = 0 + ; + +var Benchmark = require('benchmark'); +var suite = new Benchmark.Suite; + +var source = []; +for (var z = 1; z < 100; z++) +{ + source.push(z); + expected += z; +} + +suite +// add tests + +.add('async.map', function(deferred) +{ + var total = 0; + + async.map(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +.add('asynckit.parallel', function(deferred) +{ + var total = 0; + + asynckit.parallel(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +// add listeners +.on('cycle', function(ev) +{ + console.log(String(ev.target)); +}) +.on('complete', function() +{ + console.log('Fastest is ' + this.filter('fastest').map('name')); +}) +// run async +.run({ 'async': true }); diff --git a/node_modules/asynckit/index.js b/node_modules/asynckit/index.js new file mode 100644 index 0000000..455f945 --- /dev/null +++ b/node_modules/asynckit/index.js @@ -0,0 +1,6 @@ +module.exports = +{ + parallel : require('./parallel.js'), + serial : require('./serial.js'), + serialOrdered : require('./serialOrdered.js') +}; diff --git a/node_modules/asynckit/package.json b/node_modules/asynckit/package.json new file mode 100644 index 0000000..51147d6 --- /dev/null +++ b/node_modules/asynckit/package.json @@ -0,0 +1,63 @@ +{ + "name": "asynckit", + "version": "0.4.0", + "description": "Minimal async jobs utility library, with streams support", + "main": "index.js", + "scripts": { + "clean": "rimraf coverage", + "lint": "eslint *.js lib/*.js test/*.js", + "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", + "win-test": "tape test/test-*.js", + "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", + "report": "istanbul report", + "size": "browserify index.js | size-table asynckit", + "debug": "tape test/test-*.js" + }, + "pre-commit": [ + "clean", + "lint", + "test", + "browser", + "report", + "size" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/alexindigo/asynckit.git" + }, + "keywords": [ + "async", + "jobs", + "parallel", + "serial", + "iterator", + "array", + "object", + "stream", + "destroy", + "terminate", + "abort" + ], + "author": "Alex Indigo ", + "license": "MIT", + "bugs": { + "url": "https://github.com/alexindigo/asynckit/issues" + }, + "homepage": "https://github.com/alexindigo/asynckit#readme", + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^2.11.9", + "eslint": "^2.9.0", + "istanbul": "^0.4.3", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.7", + "pre-commit": "^1.1.3", + "reamde": "^1.1.0", + "rimraf": "^2.5.2", + "size-table": "^0.2.0", + "tap-spec": "^4.1.1", + "tape": "^4.5.1" + }, + "dependencies": {} +} diff --git a/node_modules/asynckit/parallel.js b/node_modules/asynckit/parallel.js new file mode 100644 index 0000000..3c50344 --- /dev/null +++ b/node_modules/asynckit/parallel.js @@ -0,0 +1,43 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} diff --git a/node_modules/asynckit/serial.js b/node_modules/asynckit/serial.js new file mode 100644 index 0000000..6cd949a --- /dev/null +++ b/node_modules/asynckit/serial.js @@ -0,0 +1,17 @@ +var serialOrdered = require('./serialOrdered.js'); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} diff --git a/node_modules/asynckit/serialOrdered.js b/node_modules/asynckit/serialOrdered.js new file mode 100644 index 0000000..607eafe --- /dev/null +++ b/node_modules/asynckit/serialOrdered.js @@ -0,0 +1,75 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} diff --git a/node_modules/asynckit/stream.js b/node_modules/asynckit/stream.js new file mode 100644 index 0000000..d43465f --- /dev/null +++ b/node_modules/asynckit/stream.js @@ -0,0 +1,21 @@ +var inherits = require('util').inherits + , Readable = require('stream').Readable + , ReadableAsyncKit = require('./lib/readable_asynckit.js') + , ReadableParallel = require('./lib/readable_parallel.js') + , ReadableSerial = require('./lib/readable_serial.js') + , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') + ; + +// API +module.exports = +{ + parallel : ReadableParallel, + serial : ReadableSerial, + serialOrdered : ReadableSerialOrdered, +}; + +inherits(ReadableAsyncKit, Readable); + +inherits(ReadableParallel, ReadableAsyncKit); +inherits(ReadableSerial, ReadableAsyncKit); +inherits(ReadableSerialOrdered, ReadableAsyncKit); diff --git a/node_modules/auto-bind/index.d.ts b/node_modules/auto-bind/index.d.ts new file mode 100644 index 0000000..0c6764b --- /dev/null +++ b/node_modules/auto-bind/index.d.ts @@ -0,0 +1,54 @@ +declare namespace autoBind { + interface Options { + /** + Bind only the given methods. + */ + readonly include?: ReadonlyArray; + + /** + Bind methods except for the given methods. + */ + readonly exclude?: ReadonlyArray; + } +} + +/** +Automatically bind methods to their class instance. + +@param self - Object with methods to bind. + +@example +``` +import autoBind = require('auto-bind'); + +class Unicorn { + constructor(name) { + this.name = name; + autoBind(this); + } + + message() { + return `${this.name} is awesome!`; + } +} + +const unicorn = new Unicorn('Rainbow'); + +// Grab the method off the class instance +const message = unicorn.message; + +// Still bound to the class instance +message(); +//=> 'Rainbow is awesome!' + +// Without `autoBind(this)`, the above would have resulted in +message(); +//=> Error: Cannot read property 'name' of undefined +``` +*/ +declare function autoBind( + self: SelfType, + options?: autoBind.Options +): SelfType; + +export = autoBind; diff --git a/node_modules/auto-bind/index.js b/node_modules/auto-bind/index.js new file mode 100644 index 0000000..c4487af --- /dev/null +++ b/node_modules/auto-bind/index.js @@ -0,0 +1,43 @@ +'use strict'; + +// Gets all non-builtin properties up the prototype chain +const getAllProperties = object => { + const properties = new Set(); + + do { + for (const key of Reflect.ownKeys(object)) { + properties.add([object, key]); + } + } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype); + + return properties; +}; + +module.exports = (self, {include, exclude} = {}) => { + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + + if (include) { + return include.some(match); + } + + if (exclude) { + return !exclude.some(match); + } + + return true; + }; + + for (const [object, key] of getAllProperties(self.constructor.prototype)) { + if (key === 'constructor' || !filter(key)) { + continue; + } + + const descriptor = Reflect.getOwnPropertyDescriptor(object, key); + if (descriptor && typeof descriptor.value === 'function') { + self[key] = self[key].bind(self); + } + } + + return self; +}; diff --git a/node_modules/auto-bind/license b/node_modules/auto-bind/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/auto-bind/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/auto-bind/package.json b/node_modules/auto-bind/package.json new file mode 100644 index 0000000..fc4f00e --- /dev/null +++ b/node_modules/auto-bind/package.json @@ -0,0 +1,46 @@ +{ + "name": "auto-bind", + "version": "4.0.0", + "description": "Automatically bind methods to their class instance", + "license": "MIT", + "repository": "sindresorhus/auto-bind", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "react.js", + "react.d.ts" + ], + "keywords": [ + "auto", + "bind", + "class", + "methods", + "method", + "automatically", + "prototype", + "instance", + "function", + "this", + "self", + "react", + "component" + ], + "devDependencies": { + "@types/react": "^16.9.9", + "ava": "^2.4.0", + "tsd": "^0.11.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/auto-bind/react.d.ts b/node_modules/auto-bind/react.d.ts new file mode 100644 index 0000000..bc4d7f4 --- /dev/null +++ b/node_modules/auto-bind/react.d.ts @@ -0,0 +1,28 @@ +import {Component as ReactComponent} from 'react'; +import autoBind = require('.'); + +/** +Same as `autoBind`, but excludes the default [React component methods](https://reactjs.org/docs/react-component.html). + +@param self - Object with methods to bind. + +@example +``` +import autoBindReact = require('auto-bind/react'); + +class Foo extends React.Component { + constructor(props) { + super(props); + autoBindReact(this); + } + + // … +} +``` +*/ +declare function autoBindReact( + self: SelfType, + options?: autoBind.Options +): SelfType; + +export = autoBindReact; diff --git a/node_modules/auto-bind/react.js b/node_modules/auto-bind/react.js new file mode 100644 index 0000000..8f0ae3a --- /dev/null +++ b/node_modules/auto-bind/react.js @@ -0,0 +1,29 @@ +'use strict'; +const autoBind = require('.'); + +const excludedReactMethods = [ + 'componentWillMount', + 'UNSAFE_componentWillMount', + 'render', + 'getSnapshotBeforeUpdate', + 'componentDidMount', + 'componentWillReceiveProps', + 'UNSAFE_componentWillReceiveProps', + 'shouldComponentUpdate', + 'componentWillUpdate', + 'UNSAFE_componentWillUpdate', + 'componentDidUpdate', + 'componentWillUnmount', + 'componentDidCatch', + 'setState', + 'forceUpdate' +]; + +module.exports = (self, {exclude = [], ...options} = {}) => { + options.exclude = [ + ...exclude, + ...excludedReactMethods + ]; + + return autoBind(self, options); +}; diff --git a/node_modules/auto-bind/readme.md b/node_modules/auto-bind/readme.md new file mode 100644 index 0000000..b999282 --- /dev/null +++ b/node_modules/auto-bind/readme.md @@ -0,0 +1,92 @@ +# auto-bind [![Build Status](https://travis-ci.org/sindresorhus/auto-bind.svg?branch=master)](https://travis-ci.org/sindresorhus/auto-bind) + +> Automatically bind methods to their class instance + +It also correctly binds inherited properties. + +## Install + +``` +$ npm install auto-bind +``` + +## Usage + +```js +const autoBind = require('auto-bind'); + +class Unicorn { + constructor(name) { + this.name = name; + autoBind(this); + } + + message() { + return `${this.name} is awesome!`; + } +} + +const unicorn = new Unicorn('Rainbow'); + +// Grab the method off the class instance +const message = unicorn.message; + +// Still bound to the class instance +message(); +//=> 'Rainbow is awesome!' + +// Without `autoBind(this)`, the above would have resulted in +message(); +//=> Error: Cannot read property 'name' of undefined +``` + +## API + +### autoBind(self, options?) + +Bind methods in `self` to their class instance. + +Returns the `self` object. + +#### self + +Type: `object` + +Object with methods to bind. + +#### options + +Type: `object` + +##### include + +Type: `Array` + +Bind only the given methods. + +##### exclude + +Type: `Array` + +Bind methods except for the given methods. + +### React + +Same as `autoBind`, but excludes the default [React component methods](https://reactjs.org/docs/react-component.html). + +```js +const autoBindReact = require('auto-bind/react'); + +class Foo extends React.Component { + constructor(props) { + super(props); + autoBindReact(this); + } + + // … +} +``` + +## Related + +- [bind-methods](https://github.com/sindresorhus/bind-methods) - Bind all methods in an object to itself or a specified context diff --git a/node_modules/axios/CHANGELOG.md b/node_modules/axios/CHANGELOG.md new file mode 100644 index 0000000..0699819 --- /dev/null +++ b/node_modules/axios/CHANGELOG.md @@ -0,0 +1,492 @@ +# Changelog + +## [1.3.4](https://github.com/axios/axios/compare/v1.3.3...v1.3.4) (2023-02-22) + + +### Bug Fixes + +* **blob:** added a check to make sure the Blob class is available in the browser's global scope; ([#5548](https://github.com/axios/axios/issues/5548)) ([3772c8f](https://github.com/axios/axios/commit/3772c8fe74112a56e3e9551f894d899bc3a9443a)) +* **http:** fixed regression bug when handling synchronous errors inside the adapter; ([#5564](https://github.com/axios/axios/issues/5564)) ([a3b246c](https://github.com/axios/axios/commit/a3b246c9de5c3bc4b5a742e15add55b375479451)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+38/-26 (#5564 )") +- avatar [lcysgsg](https://github.com/lcysgsg "+4/-0 (#5548 )") +- avatar [Michael Di Prisco](https://github.com/Cadienvan "+3/-0 (#5444 )") + +## [1.3.3](https://github.com/axios/axios/compare/v1.3.2...v1.3.3) (2023-02-13) + + +### Bug Fixes + +* **formdata:** added a check to make sure the FormData class is available in the browser's global scope; ([#5545](https://github.com/axios/axios/issues/5545)) ([a6dfa72](https://github.com/axios/axios/commit/a6dfa72010db5ad52db8bd13c0f98e537e8fd05d)) +* **formdata:** fixed setting NaN as Content-Length for form payload in some cases; ([#5535](https://github.com/axios/axios/issues/5535)) ([c19f7bf](https://github.com/axios/axios/commit/c19f7bf770f90ae8307f4ea3104f227056912da1)) +* **headers:** fixed the filtering logic of the clear method; ([#5542](https://github.com/axios/axios/issues/5542)) ([ea87ebf](https://github.com/axios/axios/commit/ea87ebfe6d1699af072b9e7cd40faf8f14b0ab93)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+11/-7 (#5545 #5535 #5542 )") +- avatar [陈若枫](https://github.com/ruofee "+2/-2 (#5467 )") + +## [1.3.2](https://github.com/axios/axios/compare/v1.3.1...v1.3.2) (2023-02-03) + + +### Bug Fixes + +* **http:** treat http://localhost as base URL for relative paths to avoid `ERR_INVALID_URL` error; ([#5528](https://github.com/axios/axios/issues/5528)) ([128d56f](https://github.com/axios/axios/commit/128d56f4a0fb8f5f2ed6e0dd80bc9225fee9538c)) +* **http:** use explicit import instead of TextEncoder global; ([#5530](https://github.com/axios/axios/issues/5530)) ([6b3c305](https://github.com/axios/axios/commit/6b3c305fc40c56428e0afabedc6f4d29c2830f6f)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+2/-1 (#5530 #5528 )") + +## [1.3.1](https://github.com/axios/axios/compare/v1.3.0...v1.3.1) (2023-02-01) + + +### Bug Fixes + +* **formdata:** add hotfix to use the asynchronous API to compute the content-length header value; ([#5521](https://github.com/axios/axios/issues/5521)) ([96d336f](https://github.com/axios/axios/commit/96d336f527619f21da012fe1f117eeb53e5a2120)) +* **serializer:** fixed serialization of array-like objects; ([#5518](https://github.com/axios/axios/issues/5518)) ([08104c0](https://github.com/axios/axios/commit/08104c028c0f9353897b1b6691d74c440fd0c32d)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+27/-8 (#5521 #5518 )") + +# [1.3.0](https://github.com/axios/axios/compare/v1.2.6...v1.3.0) (2023-01-31) + + +### Bug Fixes + +* **headers:** fixed & optimized clear method; ([#5507](https://github.com/axios/axios/issues/5507)) ([9915635](https://github.com/axios/axios/commit/9915635c69d0ab70daca5738488421f67ca60959)) +* **http:** add zlib headers if missing ([#5497](https://github.com/axios/axios/issues/5497)) ([65e8d1e](https://github.com/axios/axios/commit/65e8d1e28ce829f47a837e45129730e541950d3c)) + + +### Features + +* **fomdata:** added support for spec-compliant FormData & Blob types; ([#5316](https://github.com/axios/axios/issues/5316)) ([6ac574e](https://github.com/axios/axios/commit/6ac574e00a06731288347acea1e8246091196953)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+352/-67 (#5514 #5512 #5510 #5509 #5508 #5316 #5507 )") +- avatar [ItsNotGoodName](https://github.com/ItsNotGoodName "+43/-2 (#5497 )") + +## [1.2.6](https://github.com/axios/axios/compare/v1.2.5...v1.2.6) (2023-01-28) + + +### Bug Fixes + +* **headers:** added missed Authorization accessor; ([#5502](https://github.com/axios/axios/issues/5502)) ([342c0ba](https://github.com/axios/axios/commit/342c0ba9a16ea50f5ed7d2366c5c1a2c877e3f26)) +* **types:** fixed `CommonRequestHeadersList` & `CommonResponseHeadersList` types to be private in commonJS; ([#5503](https://github.com/axios/axios/issues/5503)) ([5a3d0a3](https://github.com/axios/axios/commit/5a3d0a3234d77361a1bc7cedee2da1e11df08e2c)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+24/-9 (#5503 #5502 )") + +## [1.2.5](https://github.com/axios/axios/compare/v1.2.4...v1.2.5) (2023-01-26) + + +### Bug Fixes + +* **types:** fixed AxiosHeaders to handle spread syntax by making all methods non-enumerable; ([#5499](https://github.com/axios/axios/issues/5499)) ([580f1e8](https://github.com/axios/axios/commit/580f1e8033a61baa38149d59fd16019de3932c22)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+82/-54 (#5499 )") +- ![avatar](https://avatars.githubusercontent.com/u/20516159?v=4&s=16) [Elliot Ford](https://github.com/EFord36 "+1/-1 (#5462 )") + +## [1.2.4](https://github.com/axios/axios/compare/v1.2.3...v1.2.4) (2023-01-22) + + +### Bug Fixes + +* **types:** renamed `RawAxiosRequestConfig` back to `AxiosRequestConfig`; ([#5486](https://github.com/axios/axios/issues/5486)) ([2a71f49](https://github.com/axios/axios/commit/2a71f49bc6c68495fa419003a3107ed8bd703ad0)) +* **types:** fix `AxiosRequestConfig` generic; ([#5478](https://github.com/axios/axios/issues/5478)) ([9bce81b](https://github.com/axios/axios/commit/186ea062da8b7d578ae78b1a5c220986b9bce81b)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+242/-108 (#5486 #5482 )") +- ![avatar](https://avatars.githubusercontent.com/u/9430821?v=4&s=16) [Daniel Hillmann](https://github.com/hilleer "+1/-1 (#5478 )") + +## [1.2.3](https://github.com/axios/axios/compare/1.2.2...1.2.3) (2023-01-10) + + +### Bug Fixes + +* **types:** fixed AxiosRequestConfig header interface by refactoring it to RawAxiosRequestConfig; ([#5420](https://github.com/axios/axios/issues/5420)) ([0811963](https://github.com/axios/axios/commit/08119634a22f1d5b19f5c9ea0adccb6d3eebc3bc)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+938/-442 (#5456 #5455 #5453 #5451 #5449 #5447 #5446 #5443 #5442 #5439 #5420 )") + +## [1.2.2] - 2022-12-29 + +### Fixed +- fix(ci): fix release script inputs [#5392](https://github.com/axios/axios/pull/5392) +- fix(ci): prerelease scipts [#5377](https://github.com/axios/axios/pull/5377) +- fix(ci): release scripts [#5376](https://github.com/axios/axios/pull/5376) +- fix(ci): typescript tests [#5375](https://github.com/axios/axios/pull/5375) +- fix: Brotli decompression [#5353](https://github.com/axios/axios/pull/5353) +- fix: add missing HttpStatusCode [#5345](https://github.com/axios/axios/pull/5345) + +### Chores +- chore(ci): set conventional-changelog header config [#5406](https://github.com/axios/axios/pull/5406) +- chore(ci): fix automatic contributors resolving [#5403](https://github.com/axios/axios/pull/5403) +- chore(ci): improved logging for the contributors list generator [#5398](https://github.com/axios/axios/pull/5398) +- chore(ci): fix release action [#5397](https://github.com/axios/axios/pull/5397) +- chore(ci): fix version bump script by adding bump argument for target version [#5393](https://github.com/axios/axios/pull/5393) +- chore(deps): bump decode-uri-component from 0.2.0 to 0.2.2 [#5342](https://github.com/axios/axios/pull/5342) +- chore(ci): GitHub Actions Release script [#5384](https://github.com/axios/axios/pull/5384) +- chore(ci): release scripts [#5364](https://github.com/axios/axios/pull/5364) + +### Contributors to this release +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- ![avatar](https://avatars.githubusercontent.com/u/1652293?v=4&s=16) [Winnie](https://github.com/winniehell) + +## [1.2.1] - 2022-12-05 + +### Changed +- feat(exports): export mergeConfig [#5151](https://github.com/axios/axios/pull/5151) + +### Fixed +- fix(CancelledError): include config [#4922](https://github.com/axios/axios/pull/4922) +- fix(general): removing multiple/trailing/leading whitespace [#5022](https://github.com/axios/axios/pull/5022) +- fix(headers): decompression for responses without Content-Length header [#5306](https://github.com/axios/axios/pull/5306) +- fix(webWorker): exception to sending form data in web worker [#5139](https://github.com/axios/axios/pull/5139) + +### Refactors +- refactor(types): AxiosProgressEvent.event type to any [#5308](https://github.com/axios/axios/pull/5308) +- refactor(types): add missing types for static AxiosError.from method [#4956](https://github.com/axios/axios/pull/4956) + +### Chores +- chore(docs): remove README link to non-existent upgrade guide [#5307](https://github.com/axios/axios/pull/5307) +- chore(docs): typo in issue template name [#5159](https://github.com/axios/axios/pull/5159) + +### Contributors to this release + +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Zachary Lysobey](https://github.com/zachlysobey) +- [Kevin Ennis](https://github.com/kevincennis) +- [Philipp Loose](https://github.com/phloose) +- [secondl1ght](https://github.com/secondl1ght) +- [wenzheng](https://github.com/0x30) +- [Ivan Barsukov](https://github.com/ovarn) +- [Arthur Fiorette](https://github.com/arthurfiorette) + +## [1.2.0] - 2022-11-10 + +### Changed + +- changed: refactored module exports [#5162](https://github.com/axios/axios/pull/5162) +- change: re-added support for loading Axios with require('axios').default [#5225](https://github.com/axios/axios/pull/5225) + +### Fixed + +- fix: improve AxiosHeaders class [#5224](https://github.com/axios/axios/pull/5224) +- fix: TypeScript type definitions for commonjs [#5196](https://github.com/axios/axios/pull/5196) +- fix: type definition of use method on AxiosInterceptorManager to match the the README [#5071](https://github.com/axios/axios/pull/5071) +- fix: __dirname is not defined in the sandbox [#5269](https://github.com/axios/axios/pull/5269) +- fix: AxiosError.toJSON method to avoid circular references [#5247](https://github.com/axios/axios/pull/5247) +- fix: Z_BUF_ERROR when content-encoding is set but the response body is empty [#5250](https://github.com/axios/axios/pull/5250) + +### Refactors +- refactor: allowing adapters to be loaded by name [#5277](https://github.com/axios/axios/pull/5277) + +### Chores + +- chore: force CI restart [#5243](https://github.com/axios/axios/pull/5243) +- chore: update ECOSYSTEM.md [#5077](https://github.com/axios/axios/pull/5077) +- chore: update get/index.html [#5116](https://github.com/axios/axios/pull/5116) +- chore: update Sandbox UI/UX [#5205](https://github.com/axios/axios/pull/5205) +- chore:(actions): remove git credentials after checkout [#5235](https://github.com/axios/axios/pull/5235) +- chore(actions): bump actions/dependency-review-action from 2 to 3 [#5266](https://github.com/axios/axios/pull/5266) +- chore(packages): bump loader-utils from 1.4.1 to 1.4.2 [#5295](https://github.com/axios/axios/pull/5295) +- chore(packages): bump engine.io from 6.2.0 to 6.2.1 [#5294](https://github.com/axios/axios/pull/5294) +- chore(packages): bump socket.io-parser from 4.0.4 to 4.0.5 [#5241](https://github.com/axios/axios/pull/5241) +- chore(packages): bump loader-utils from 1.4.0 to 1.4.1 [#5245](https://github.com/axios/axios/pull/5245) +- chore(docs): update Resources links in README [#5119](https://github.com/axios/axios/pull/5119) +- chore(docs): update the link for JSON url [#5265](https://github.com/axios/axios/pull/5265) +- chore(docs): fix broken links [#5218](https://github.com/axios/axios/pull/5218) +- chore(docs): update and rename UPGRADE_GUIDE.md to MIGRATION_GUIDE.md [#5170](https://github.com/axios/axios/pull/5170) +- chore(docs): typo fix line #856 and #920 [#5194](https://github.com/axios/axios/pull/5194) +- chore(docs): typo fix #800 [#5193](https://github.com/axios/axios/pull/5193) +- chore(docs): fix typos [#5184](https://github.com/axios/axios/pull/5184) +- chore(docs): fix punctuation in README.md [#5197](https://github.com/axios/axios/pull/5197) +- chore(docs): update readme in the Handling Errors section - issue reference #5260 [#5261](https://github.com/axios/axios/pull/5261) +- chore: remove \b from filename [#5207](https://github.com/axios/axios/pull/5207) +- chore(docs): update CHANGELOG.md [#5137](https://github.com/axios/axios/pull/5137) +- chore: add sideEffects false to package.json [#5025](https://github.com/axios/axios/pull/5025) + +### Contributors to this release + +- [Maddy Miller](https://github.com/me4502) +- [Amit Saini](https://github.com/amitsainii) +- [ecyrbe](https://github.com/ecyrbe) +- [Ikko Ashimine](https://github.com/eltociear) +- [Geeth Gunnampalli](https://github.com/thetechie7) +- [Shreem Asati](https://github.com/shreem-123) +- [Frieder Bluemle](https://github.com/friederbluemle) +- [윤세영](https://github.com/yunseyeong) +- [Claudio Busatto](https://github.com/cjcbusatto) +- [Remco Haszing](https://github.com/remcohaszing) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Csaba Maulis](https://github.com/om4csaba) +- [MoPaMo](https://github.com/MoPaMo) +- [Daniel Fjeldstad](https://github.com/w3bdesign) +- [Adrien Brunet](https://github.com/adrien-may) +- [Frazer Smith](https://github.com/Fdawgs) +- [HaiTao](https://github.com/836334258) +- [AZM](https://github.com/aziyatali) +- [relbns](https://github.com/relbns) + +## [1.1.3] - 2022-10-15 + +### Added + +- Added custom params serializer support [#5113](https://github.com/axios/axios/pull/5113) + +### Fixed + +- Fixed top-level export to keep them in-line with static properties [#5109](https://github.com/axios/axios/pull/5109) +- Stopped including null values to query string. [#5108](https://github.com/axios/axios/pull/5108) +- Restored proxy config backwards compatibility with 0.x [#5097](https://github.com/axios/axios/pull/5097) +- Added back AxiosHeaders in AxiosHeaderValue [#5103](https://github.com/axios/axios/pull/5103) +- Pin CDN install instructions to a specific version [#5060](https://github.com/axios/axios/pull/5060) +- Handling of array values fixed for AxiosHeaders [#5085](https://github.com/axios/axios/pull/5085) + +### Chores + +- docs: match badge style, add link to them [#5046](https://github.com/axios/axios/pull/5046) +- chore: fixing comments typo [#5054](https://github.com/axios/axios/pull/5054) +- chore: update issue template [#5061](https://github.com/axios/axios/pull/5061) +- chore: added progress capturing section to the docs; [#5084](https://github.com/axios/axios/pull/5084) + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) +- [scarf](https://github.com/scarf005) +- [Lenz Weber-Tronic](https://github.com/phryneas) +- [Arvindh](https://github.com/itsarvindh) +- [Félix Legrelle](https://github.com/FelixLgr) +- [Patrick Petrovic](https://github.com/ppati000) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [littledian](https://github.com/littledian) +- [ChronosMasterOfAllTime](https://github.com/ChronosMasterOfAllTime) + +## [1.1.2] - 2022-10-07 + +### Fixed + +- Fixed broken exports for UMD builds. + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) + +## [1.1.1] - 2022-10-07 + +### Fixed + +- Fixed broken exports for common js. This fix breaks a prior fix, I will fix both issues ASAP but the commonJS use is more impactful. + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) + +## [1.1.0] - 2022-10-06 + +### Fixed + +- Fixed missing exports in type definition index.d.ts [#5003](https://github.com/axios/axios/pull/5003) +- Fixed query params composing [#5018](https://github.com/axios/axios/pull/5018) +- Fixed GenericAbortSignal interface by making it more generic [#5021](https://github.com/axios/axios/pull/5021) +- Fixed adding "clear" to AxiosInterceptorManager [#5010](https://github.com/axios/axios/pull/5010) +- Fixed commonjs & umd exports [#5030](https://github.com/axios/axios/pull/5030) +- Fixed inability to access response headers when using axios 1.x with Jest [#5036](https://github.com/axios/axios/pull/5036) + +### Contributors to this release + +- [Trim21](https://github.com/trim21) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [shingo.sasaki](https://github.com/s-sasaki-0529) +- [Ivan Pepelko](https://github.com/ivanpepelko) +- [Richard Kořínek](https://github.com/risa) + +## [1.0.0] - 2022-10-04 + +### Added + +- Added stack trace to AxiosError [#4624](https://github.com/axios/axios/pull/4624) +- Add AxiosError to AxiosStatic [#4654](https://github.com/axios/axios/pull/4654) +- Replaced Rollup as our build runner [#4596](https://github.com/axios/axios/pull/4596) +- Added generic TS types for the exposed toFormData helper [#4668](https://github.com/axios/axios/pull/4668) +- Added listen callback function [#4096](https://github.com/axios/axios/pull/4096) +- Added instructions for installing using PNPM [#4207](https://github.com/axios/axios/pull/4207) +- Added generic AxiosAbortSignal TS interface to avoid importing AbortController polyfill [#4229](https://github.com/axios/axios/pull/4229) +- Added axios-url-template in ECOSYSTEM.md [#4238](https://github.com/axios/axios/pull/4238) +- Added a clear() function to the request and response interceptors object so a user can ensure that all interceptors have been removed from an axios instance [#4248](https://github.com/axios/axios/pull/4248) +- Added react hook plugin [#4319](https://github.com/axios/axios/pull/4319) +- Adding HTTP status code for transformResponse [#4580](https://github.com/axios/axios/pull/4580) +- Added blob to the list of protocols supported by the browser [#4678](https://github.com/axios/axios/pull/4678) +- Resolving proxy from env on redirect [#4436](https://github.com/axios/axios/pull/4436) +- Added enhanced toFormData implementation with additional options [4704](https://github.com/axios/axios/pull/4704) +- Adding Canceler parameters config and request [#4711](https://github.com/axios/axios/pull/4711) +- Added automatic payload serialization to application/x-www-form-urlencoded [#4714](https://github.com/axios/axios/pull/4714) +- Added the ability for webpack users to overwrite built-ins [#4715](https://github.com/axios/axios/pull/4715) +- Added string[] to AxiosRequestHeaders type [#4322](https://github.com/axios/axios/pull/4322) +- Added the ability for the url-encoded-form serializer to respect the formSerializer config [#4721](https://github.com/axios/axios/pull/4721) +- Added isCancel type assert [#4293](https://github.com/axios/axios/pull/4293) +- Added data URL support for node.js [#4725](https://github.com/axios/axios/pull/4725) +- Adding types for progress event callbacks [#4675](https://github.com/axios/axios/pull/4675) +- URL params serializer [#4734](https://github.com/axios/axios/pull/4734) +- Added axios.formToJSON method [#4735](https://github.com/axios/axios/pull/4735) +- Bower platform add data protocol [#4804](https://github.com/axios/axios/pull/4804) +- Use WHATWG URL API instead of url.parse() [#4852](https://github.com/axios/axios/pull/4852) +- Add ENUM containing Http Status Codes to typings [#4903](https://github.com/axios/axios/pull/4903) +- Improve typing of timeout in index.d.ts [#4934](https://github.com/axios/axios/pull/4934) + +### Changed + +- Updated AxiosError.config to be optional in the type definition [#4665](https://github.com/axios/axios/pull/4665) +- Updated README emphasizing the URLSearchParam built-in interface over other solutions [#4590](https://github.com/axios/axios/pull/4590) +- Include request and config when creating a CanceledError instance [#4659](https://github.com/axios/axios/pull/4659) +- Changed func-names eslint rule to as-needed [#4492](https://github.com/axios/axios/pull/4492) +- Replacing deprecated substr() with slice() as substr() is deprecated [#4468](https://github.com/axios/axios/pull/4468) +- Updating HTTP links in README.md to use HTTPS [#4387](https://github.com/axios/axios/pull/4387) +- Updated to a better trim() polyfill [#4072](https://github.com/axios/axios/pull/4072) +- Updated types to allow specifying partial default headers on instance create [#4185](https://github.com/axios/axios/pull/4185) +- Expanded isAxiosError types [#4344](https://github.com/axios/axios/pull/4344) +- Updated type definition for axios instance methods [#4224](https://github.com/axios/axios/pull/4224) +- Updated eslint config [#4722](https://github.com/axios/axios/pull/4722) +- Updated Docs [#4742](https://github.com/axios/axios/pull/4742) +- Refactored Axios to use ES2017 [#4787](https://github.com/axios/axios/pull/4787) + + +### Deprecated +- There are multiple deprecations, refactors and fixes provided in this release. Please read through the full release notes to see how this may impact your project and use case. + +### Removed + +- Removed incorrect argument for NetworkError constructor [#4656](https://github.com/axios/axios/pull/4656) +- Removed Webpack [#4596](https://github.com/axios/axios/pull/4596) +- Removed function that transform arguments to array [#4544](https://github.com/axios/axios/pull/4544) + +### Fixed + +- Fixed grammar in README [#4649](https://github.com/axios/axios/pull/4649) +- Fixed code error in README [#4599](https://github.com/axios/axios/pull/4599) +- Optimized the code that checks cancellation [#4587](https://github.com/axios/axios/pull/4587) +- Fix url pointing to defaults.js in README [#4532](https://github.com/axios/axios/pull/4532) +- Use type alias instead of interface for AxiosPromise [#4505](https://github.com/axios/axios/pull/4505) +- Fix some word spelling and lint style in code comments [#4500](https://github.com/axios/axios/pull/4500) +- Edited readme with 3 updated browser icons of Chrome, FireFox and Safari [#4414](https://github.com/axios/axios/pull/4414) +- Bump follow-redirects from 1.14.9 to 1.15.0 [#4673](https://github.com/axios/axios/pull/4673) +- Fixing http tests to avoid hanging when assertions fail [#4435](https://github.com/axios/axios/pull/4435) +- Fix TS definition for AxiosRequestTransformer [#4201](https://github.com/axios/axios/pull/4201) +- Fix grammatical issues in README [#4232](https://github.com/axios/axios/pull/4232) +- Fixing instance.defaults.headers type [#4557](https://github.com/axios/axios/pull/4557) +- Fixed race condition on immediate requests cancellation [#4261](https://github.com/axios/axios/pull/4261) +- Fixing Z_BUF_ERROR when no content [#4701](https://github.com/axios/axios/pull/4701) +- Fixing proxy beforeRedirect regression [#4708](https://github.com/axios/axios/pull/4708) +- Fixed AxiosError status code type [#4717](https://github.com/axios/axios/pull/4717) +- Fixed AxiosError stack capturing [#4718](https://github.com/axios/axios/pull/4718) +- Fixing AxiosRequestHeaders typings [#4334](https://github.com/axios/axios/pull/4334) +- Fixed max body length defaults [#4731](https://github.com/axios/axios/pull/4731) +- Fixed toFormData Blob issue on node>v17 [#4728](https://github.com/axios/axios/pull/4728) +- Bump grunt from 1.5.2 to 1.5.3 [#4743](https://github.com/axios/axios/pull/4743) +- Fixing content-type header repeated [#4745](https://github.com/axios/axios/pull/4745) +- Fixed timeout error message for http [4738](https://github.com/axios/axios/pull/4738) +- Request ignores false, 0 and empty string as body values [#4785](https://github.com/axios/axios/pull/4785) +- Added back missing minified builds [#4805](https://github.com/axios/axios/pull/4805) +- Fixed a type error [#4815](https://github.com/axios/axios/pull/4815) +- Fixed a regression bug with unsubscribing from cancel token; [#4819](https://github.com/axios/axios/pull/4819) +- Remove repeated compression algorithm [#4820](https://github.com/axios/axios/pull/4820) +- The error of calling extend to pass parameters [#4857](https://github.com/axios/axios/pull/4857) +- SerializerOptions.indexes allows boolean | null | undefined [#4862](https://github.com/axios/axios/pull/4862) +- Require interceptors to return values [#4874](https://github.com/axios/axios/pull/4874) +- Removed unused imports [#4949](https://github.com/axios/axios/pull/4949) +- Allow null indexes on formSerializer and paramsSerializer [#4960](https://github.com/axios/axios/pull/4960) + +### Chores +- Set permissions for GitHub actions [#4765](https://github.com/axios/axios/pull/4765) +- Included githubactions in the dependabot config [#4770](https://github.com/axios/axios/pull/4770) +- Included dependency review [#4771](https://github.com/axios/axios/pull/4771) +- Update security.md [#4784](https://github.com/axios/axios/pull/4784) +- Remove unnecessary spaces [#4854](https://github.com/axios/axios/pull/4854) +- Simplify the import path of AxiosError [#4875](https://github.com/axios/axios/pull/4875) +- Fix Gitpod dead link [#4941](https://github.com/axios/axios/pull/4941) +- Enable syntax highlighting for a code block [#4970](https://github.com/axios/axios/pull/4970) +- Using Logo Axios in Readme.md [#4993](https://github.com/axios/axios/pull/4993) +- Fix markup for note in README [#4825](https://github.com/axios/axios/pull/4825) +- Fix typo and formatting, add colons [#4853](https://github.com/axios/axios/pull/4853) +- Fix typo in readme [#4942](https://github.com/axios/axios/pull/4942) + +### Security + +- Update SECURITY.md [#4687](https://github.com/axios/axios/pull/4687) + +### Contributors to this release + +- [Bertrand Marron](https://github.com/tusbar) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Dan Mooney](https://github.com/danmooney) +- [Michael Li](https://github.com/xiaoyu-tamu) +- [aong](https://github.com/yxwzaxns) +- [Des Preston](https://github.com/despreston) +- [Ted Robertson](https://github.com/tredondo) +- [zhoulixiang](https://github.com/zh-lx) +- [Arthur Fiorette](https://github.com/arthurfiorette) +- [Kumar Shanu](https://github.com/Kr-Shanu) +- [JALAL](https://github.com/JLL32) +- [Jingyi Lin](https://github.com/MageeLin) +- [Philipp Loose](https://github.com/phloose) +- [Alexander Shchukin](https://github.com/sashsvamir) +- [Dave Cardwell](https://github.com/davecardwell) +- [Cat Scarlet](https://github.com/catscarlet) +- [Luca Pizzini](https://github.com/lpizzinidev) +- [Kai](https://github.com/Schweinepriester) +- [Maxime Bargiel](https://github.com/mbargiel) +- [Brian Helba](https://github.com/brianhelba) +- [reslear](https://github.com/reslear) +- [Jamie Slome](https://github.com/JamieSlome) +- [Landro3](https://github.com/Landro3) +- [rafw87](https://github.com/rafw87) +- [Afzal Sayed](https://github.com/afzalsayed96) +- [Koki Oyatsu](https://github.com/kaishuu0123) +- [Dave](https://github.com/wangcch) +- [暴走老七](https://github.com/baozouai) +- [Spencer](https://github.com/spalger) +- [Adrian Wieprzkowicz](https://github.com/Argeento) +- [Jamie Telin](https://github.com/lejahmie) +- [毛呆](https://github.com/aweikalee) +- [Kirill Shakirov](https://github.com/turisap) +- [Rraji Abdelbari](https://github.com/estarossa0) +- [Jelle Schutter](https://github.com/jelleschutter) +- [Tom Ceuppens](https://github.com/KyorCode) +- [Johann Cooper](https://github.com/JohannCooper) +- [Dimitris Halatsis](https://github.com/mitsos1os) +- [chenjigeng](https://github.com/chenjigeng) +- [João Gabriel Quaresma](https://github.com/joaoGabriel55) +- [Victor Augusto](https://github.com/VictorAugDB) +- [neilnaveen](https://github.com/neilnaveen) +- [Pavlos](https://github.com/psmoros) +- [Kiryl Valkovich](https://github.com/visortelle) +- [Naveen](https://github.com/naveensrinivasan) +- [wenzheng](https://github.com/0x30) +- [hcwhan](https://github.com/hcwhan) +- [Bassel Rachid](https://github.com/basselworkforce) +- [Grégoire Pineau](https://github.com/lyrixx) +- [felipedamin](https://github.com/felipedamin) +- [Karl Horky](https://github.com/karlhorky) +- [Yue JIN](https://github.com/kingyue737) +- [Usman Ali Siddiqui](https://github.com/usman250994) +- [WD](https://github.com/techbirds) +- [Günther Foidl](https://github.com/gfoidl) +- [Stephen Jennings](https://github.com/jennings) +- [C.T.Lin](https://github.com/chentsulin) +- [mia-z](https://github.com/mia-z) +- [Parth Banathia](https://github.com/Parth0105) +- [parth0105pluang](https://github.com/parth0105pluang) +- [Marco Weber](https://github.com/mrcwbr) +- [Luca Pizzini](https://github.com/lpizzinidev) +- [Willian Agostini](https://github.com/WillianAgostini) +- [Huyen Nguyen](https://github.com/huyenltnguyen) \ No newline at end of file diff --git a/node_modules/axios/LICENSE b/node_modules/axios/LICENSE new file mode 100644 index 0000000..05006a5 --- /dev/null +++ b/node_modules/axios/LICENSE @@ -0,0 +1,7 @@ +# Copyright (c) 2014-present Matt Zabriskie & Collaborators + +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. diff --git a/node_modules/axios/MIGRATION_GUIDE.md b/node_modules/axios/MIGRATION_GUIDE.md new file mode 100644 index 0000000..ec3ae0d --- /dev/null +++ b/node_modules/axios/MIGRATION_GUIDE.md @@ -0,0 +1,3 @@ +# Migration Guide + +## 0.x.x -> 1.1.0 diff --git a/node_modules/axios/README.md b/node_modules/axios/README.md new file mode 100644 index 0000000..997d201 --- /dev/null +++ b/node_modules/axios/README.md @@ -0,0 +1,1313 @@ +

+ +
+
+

+ +

Promise based HTTP client for the browser and node.js

+ +

+ Website • + Documentation +

+ +
+ +[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) +[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios) +[![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=CI&logo=github&style=flat-square)](https://github.com/axios/axios/actions/workflows/ci.yml) +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/axios/axios) +[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) +[![install size](https://img.shields.io/badge/dynamic/json?url=https://packagephobia.com/v2/api.json?p=axios&query=$.install.pretty&label=install%20size&style=flat-square)](https://packagephobia.now.sh/result?p=axios) +[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest) +[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios) +[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) +[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) +[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios) + + + + +
+ +## Table of Contents + + - [Features](#features) + - [Browser Support](#browser-support) + - [Installing](#installing) + - [Package manager](#package-manager) + - [CDN](#cdn) + - [Example](#example) + - [Axios API](#axios-api) + - [Request method aliases](#request-method-aliases) + - [Concurrency 👎](#concurrency-deprecated) + - [Creating an instance](#creating-an-instance) + - [Instance methods](#instance-methods) + - [Request Config](#request-config) + - [Response Schema](#response-schema) + - [Config Defaults](#config-defaults) + - [Global axios defaults](#global-axios-defaults) + - [Custom instance defaults](#custom-instance-defaults) + - [Config order of precedence](#config-order-of-precedence) + - [Interceptors](#interceptors) + - [Multiple Interceptors](#multiple-interceptors) + - [Handling Errors](#handling-errors) + - [Cancellation](#cancellation) + - [AbortController](#abortcontroller) + - [CancelToken 👎](#canceltoken-deprecated) + - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) + - [URLSearchParams](#urlsearchparams) + - [Query string](#query-string-older-browsers) + - [🆕 Automatic serialization](#-automatic-serialization-to-urlsearchparams) + - [Using multipart/form-data format](#using-multipartform-data-format) + - [FormData](#formdata) + - [🆕 Automatic serialization](#-automatic-serialization-to-formdata) + - [Files Posting](#files-posting) + - [HTML Form Posting](#-html-form-posting-browser) + - [🆕 Progress capturing](#-progress-capturing) + - [🆕 Rate limiting](#-progress-capturing) + - [Semver](#semver) + - [Promises](#promises) + - [TypeScript](#typescript) + - [Resources](#resources) + - [Credits](#credits) + - [License](#license) + +## Features + +- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser +- Make [http](https://nodejs.org/api/http.html) requests from node.js +- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API +- Intercept request and response +- Transform request and response data +- Cancel requests +- Automatic transforms for [JSON](https://www.json.org/json-en.html) data +- 🆕 Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings +- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) + +## Browser Support + +![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | +--- | --- | --- | --- | --- | --- | +Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | + +[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) + +## Installing + +### Package manager + +Using npm: + +```bash +$ npm install axios +``` + +Using bower: + +```bash +$ bower install axios +``` + +Using yarn: + +```bash +$ yarn add axios +``` + +Using pnpm: + +```bash +$ pnpm add axios +``` + +Once the package is installed, you can import the library using `import` or `require` approach: + +```js +import axios, {isCancel, AxiosError} from 'axios'; +``` + +You can also use the default export, since the named export is just a re-export from the Axios factory: + +```js +import axios from 'axios'; + +console.log(axios.isCancel('something')); +```` + +If you use `require` for importing, **only default export is available**: + +```js +const axios = require('axios'); + +console.log(axios.isCancel('something')); +``` + +For cases where something went wrong when trying to import a module into a custom or legacy environment, +you can try importing the module package directly: + +```js +const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017) +// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017) +``` + +### CDN + +Using jsDelivr CDN (ES5 UMD browser module): + +```html + +``` + +Using unpkg CDN: + +```html + +``` + +## Example + +> **Note** CommonJS usage +> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach: + +```js +import axios from 'axios'; +//const axios = require('axios'); // legacy way + +// Make a request for a user with a given ID +axios.get('/user?ID=12345') + .then(function (response) { + // handle success + console.log(response); + }) + .catch(function (error) { + // handle error + console.log(error); + }) + .finally(function () { + // always executed + }); + +// Optionally the request above could also be done as +axios.get('/user', { + params: { + ID: 12345 + } + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }) + .finally(function () { + // always executed + }); + +// Want to use async/await? Add the `async` keyword to your outer function/method. +async function getUser() { + try { + const response = await axios.get('/user?ID=12345'); + console.log(response); + } catch (error) { + console.error(error); + } +} +``` + +> **Note** `async/await` is part of ECMAScript 2017 and is not supported in Internet +> Explorer and older browsers, so use with caution. + +Performing a `POST` request + +```js +axios.post('/user', { + firstName: 'Fred', + lastName: 'Flintstone' + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }); +``` + +Performing multiple concurrent requests + +```js +function getUserAccount() { + return axios.get('/user/12345'); +} + +function getUserPermissions() { + return axios.get('/user/12345/permissions'); +} + +Promise.all([getUserAccount(), getUserPermissions()]) + .then(function (results) { + const acct = results[0]; + const perm = results[1]; + }); +``` + +## axios API + +Requests can be made by passing the relevant config to `axios`. + +##### axios(config) + +```js +// Send a POST request +axios({ + method: 'post', + url: '/user/12345', + data: { + firstName: 'Fred', + lastName: 'Flintstone' + } +}); +``` + +```js +// GET request for remote image in node.js +axios({ + method: 'get', + url: 'https://bit.ly/2mTM3nY', + responseType: 'stream' +}) + .then(function (response) { + response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) + }); +``` + +##### axios(url[, config]) + +```js +// Send a GET request (default method) +axios('/user/12345'); +``` + +### Request method aliases + +For convenience, aliases have been provided for all common request methods. + +##### axios.request(config) +##### axios.get(url[, config]) +##### axios.delete(url[, config]) +##### axios.head(url[, config]) +##### axios.options(url[, config]) +##### axios.post(url[, data[, config]]) +##### axios.put(url[, data[, config]]) +##### axios.patch(url[, data[, config]]) + +###### NOTE +When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. + +### Concurrency (Deprecated) +Please use `Promise.all` to replace the below functions. + +Helper functions for dealing with concurrent requests. + +axios.all(iterable) +axios.spread(callback) + +### Creating an instance + +You can create a new instance of axios with a custom config. + +##### axios.create([config]) + +```js +const instance = axios.create({ + baseURL: 'https://some-domain.com/api/', + timeout: 1000, + headers: {'X-Custom-Header': 'foobar'} +}); +``` + +### Instance methods + +The available instance methods are listed below. The specified config will be merged with the instance config. + +##### axios#request(config) +##### axios#get(url[, config]) +##### axios#delete(url[, config]) +##### axios#head(url[, config]) +##### axios#options(url[, config]) +##### axios#post(url[, data[, config]]) +##### axios#put(url[, data[, config]]) +##### axios#patch(url[, data[, config]]) +##### axios#getUri([config]) + +## Request Config + +These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. + +```js +{ + // `url` is the server URL that will be used for the request + url: '/user', + + // `method` is the request method to be used when making the request + method: 'get', // default + + // `baseURL` will be prepended to `url` unless `url` is absolute. + // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs + // to methods of that instance. + baseURL: 'https://some-domain.com/api/', + + // `transformRequest` allows changes to the request data before it is sent to the server + // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' + // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, + // FormData or Stream + // You may modify the headers object. + transformRequest: [function (data, headers) { + // Do whatever you want to transform the data + + return data; + }], + + // `transformResponse` allows changes to the response data to be made before + // it is passed to then/catch + transformResponse: [function (data) { + // Do whatever you want to transform the data + + return data; + }], + + // `headers` are custom headers to be sent + headers: {'X-Requested-With': 'XMLHttpRequest'}, + + // `params` are the URL parameters to be sent with the request + // Must be a plain object or a URLSearchParams object + params: { + ID: 12345 + }, + + // `paramsSerializer` is an optional config in charge of serializing `params` + paramsSerializer: { + encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashion + serialize?: (params: Record, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized. + indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes) + }, + + // `data` is the data to be sent as the request body + // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' + // When no `transformRequest` is set, must be of one of the following types: + // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams + // - Browser only: FormData, File, Blob + // - Node only: Stream, Buffer, FormData (form-data package) + data: { + firstName: 'Fred' + }, + + // syntax alternative to send data into the body + // method post + // only the value is sent, not the key + data: 'Country=Brasil&City=Belo Horizonte', + + // `timeout` specifies the number of milliseconds before the request times out. + // If the request takes longer than `timeout`, the request will be aborted. + timeout: 1000, // default is `0` (no timeout) + + // `withCredentials` indicates whether or not cross-site Access-Control requests + // should be made using credentials + withCredentials: false, // default + + // `adapter` allows custom handling of requests which makes testing easier. + // Return a promise and supply a valid response (see lib/adapters/README.md). + adapter: function (config) { + /* ... */ + }, + + // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. + // This will set an `Authorization` header, overwriting any existing + // `Authorization` custom headers you have set using `headers`. + // Please note that only HTTP Basic auth is configurable through this parameter. + // For Bearer tokens and such, use `Authorization` custom headers instead. + auth: { + username: 'janedoe', + password: 's00pers3cret' + }, + + // `responseType` indicates the type of data that the server will respond with + // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' + // browser only: 'blob' + responseType: 'json', // default + + // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) + // Note: Ignored for `responseType` of 'stream' or client-side requests + responseEncoding: 'utf8', // default + + // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token + xsrfCookieName: 'XSRF-TOKEN', // default + + // `xsrfHeaderName` is the name of the http header that carries the xsrf token value + xsrfHeaderName: 'X-XSRF-TOKEN', // default + + // `onUploadProgress` allows handling of progress events for uploads + // browser & node.js + onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) { + // Do whatever you want with the Axios progress event + }, + + // `onDownloadProgress` allows handling of progress events for downloads + // browser & node.js + onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) { + // Do whatever you want with the Axios progress event + }, + + // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js + maxContentLength: 2000, + + // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed + maxBodyLength: 2000, + + // `validateStatus` defines whether to resolve or reject the promise for a given + // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` + // or `undefined`), the promise will be resolved; otherwise, the promise will be + // rejected. + validateStatus: function (status) { + return status >= 200 && status < 300; // default + }, + + // `maxRedirects` defines the maximum number of redirects to follow in node.js. + // If set to 0, no redirects will be followed. + maxRedirects: 21, // default + + // `beforeRedirect` defines a function that will be called before redirect. + // Use this to adjust the request options upon redirecting, + // to inspect the latest response headers, + // or to cancel the request by throwing an error + // If maxRedirects is set to 0, `beforeRedirect` is not used. + beforeRedirect: (options, { headers }) => { + if (options.hostname === "example.com") { + options.auth = "user:password"; + } + }, + + // `socketPath` defines a UNIX Socket to be used in node.js. + // e.g. '/var/run/docker.sock' to send requests to the docker daemon. + // Only either `socketPath` or `proxy` can be specified. + // If both are specified, `socketPath` is used. + socketPath: null, // default + + // `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects. + transport: undefined, // default + + // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http + // and https requests, respectively, in node.js. This allows options to be added like + // `keepAlive` that are not enabled by default. + httpAgent: new http.Agent({ keepAlive: true }), + httpsAgent: new https.Agent({ keepAlive: true }), + + // `proxy` defines the hostname, port, and protocol of the proxy server. + // You can also define your proxy using the conventional `http_proxy` and + // `https_proxy` environment variables. If you are using environment variables + // for your proxy configuration, you can also define a `no_proxy` environment + // variable as a comma-separated list of domains that should not be proxied. + // Use `false` to disable proxies, ignoring environment variables. + // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and + // supplies credentials. + // This will set an `Proxy-Authorization` header, overwriting any existing + // `Proxy-Authorization` custom headers you have set using `headers`. + // If the proxy server uses HTTPS, then you must set the protocol to `https`. + proxy: { + protocol: 'https', + host: '127.0.0.1', + // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined + port: 9000, + auth: { + username: 'mikeymike', + password: 'rapunz3l' + } + }, + + // `cancelToken` specifies a cancel token that can be used to cancel the request + // (see Cancellation section below for details) + cancelToken: new CancelToken(function (cancel) { + }), + + // an alternative way to cancel Axios requests using AbortController + signal: new AbortController().signal, + + // `decompress` indicates whether or not the response body should be decompressed + // automatically. If set to `true` will also remove the 'content-encoding' header + // from the responses objects of all decompressed responses + // - Node only (XHR cannot turn off decompression) + decompress: true // default + + // `insecureHTTPParser` boolean. + // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. + // This may allow interoperability with non-conformant HTTP implementations. + // Using the insecure parser should be avoided. + // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback + // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none + insecureHTTPParser: undefined // default + + // transitional options for backward compatibility that may be removed in the newer versions + transitional: { + // silent JSON parsing mode + // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) + // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') + silentJSONParsing: true, // default value for the current Axios version + + // try to parse the response string as JSON even if `responseType` is not 'json' + forcedJSONParsing: true, + + // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts + clarifyTimeoutError: false, + }, + + env: { + // The FormData class to be used to automatically serialize the payload into a FormData object + FormData: window?.FormData || global?.FormData + }, + + formSerializer: { + visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values + dots: boolean; // use dots instead of brackets format + metaTokens: boolean; // keep special endings like {} in parameter key + indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes + }, + + // http adapter only (node.js) + maxRate: [ + 100 * 1024, // 100KB/s upload limit, + 100 * 1024 // 100KB/s download limit + ] +} +``` + +## Response Schema + +The response for a request contains the following information. + +```js +{ + // `data` is the response that was provided by the server + data: {}, + + // `status` is the HTTP status code from the server response + status: 200, + + // `statusText` is the HTTP status message from the server response + statusText: 'OK', + + // `headers` the HTTP headers that the server responded with + // All header names are lowercase and can be accessed using the bracket notation. + // Example: `response.headers['content-type']` + headers: {}, + + // `config` is the config that was provided to `axios` for the request + config: {}, + + // `request` is the request that generated this response + // It is the last ClientRequest instance in node.js (in redirects) + // and an XMLHttpRequest instance in the browser + request: {} +} +``` + +When using `then`, you will receive the response as follows: + +```js +axios.get('/user/12345') + .then(function (response) { + console.log(response.data); + console.log(response.status); + console.log(response.statusText); + console.log(response.headers); + console.log(response.config); + }); +``` + +When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. + +## Config Defaults + +You can specify config defaults that will be applied to every request. + +### Global axios defaults + +```js +axios.defaults.baseURL = 'https://api.example.com'; + +// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. +// See below for an example using Custom instance defaults instead. +axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; + +axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; +``` + +### Custom instance defaults + +```js +// Set config defaults when creating the instance +const instance = axios.create({ + baseURL: 'https://api.example.com' +}); + +// Alter defaults after instance has been created +instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; +``` + +### Config order of precedence + +Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults/index.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. + +```js +// Create an instance using the config defaults provided by the library +// At this point the timeout config value is `0` as is the default for the library +const instance = axios.create(); + +// Override timeout default for the library +// Now all requests using this instance will wait 2.5 seconds before timing out +instance.defaults.timeout = 2500; + +// Override timeout for this request as it's known to take a long time +instance.get('/longRequest', { + timeout: 5000 +}); +``` + +## Interceptors + +You can intercept requests or responses before they are handled by `then` or `catch`. + +```js +// Add a request interceptor +axios.interceptors.request.use(function (config) { + // Do something before request is sent + return config; + }, function (error) { + // Do something with request error + return Promise.reject(error); + }); + +// Add a response interceptor +axios.interceptors.response.use(function (response) { + // Any status code that lie within the range of 2xx cause this function to trigger + // Do something with response data + return response; + }, function (error) { + // Any status codes that falls outside the range of 2xx cause this function to trigger + // Do something with response error + return Promise.reject(error); + }); +``` + +If you need to remove an interceptor later you can. + +```js +const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); +axios.interceptors.request.eject(myInterceptor); +``` + +You can also clear all interceptors for requests or responses. +```js +const instance = axios.create(); +instance.interceptors.request.use(function () {/*...*/}); +instance.interceptors.request.clear(); // Removes interceptors from requests +instance.interceptors.response.use(function () {/*...*/}); +instance.interceptors.response.clear(); // Removes interceptors from responses +``` + +You can add interceptors to a custom instance of axios. + +```js +const instance = axios.create(); +instance.interceptors.request.use(function () {/*...*/}); +``` + +When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay +in the execution of your axios request when the main thread is blocked (a promise is created under the hood for +the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag +to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. + +```js +axios.interceptors.request.use(function (config) { + config.headers.test = 'I am only a header!'; + return config; +}, null, { synchronous: true }); +``` + +If you want to execute a particular interceptor based on a runtime check, +you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return +of `runWhen` is `false`. The function will be called with the config +object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an +asynchronous request interceptor that only needs to run at certain times. + +```js +function onGetCall(config) { + return config.method === 'get'; +} +axios.interceptors.request.use(function (config) { + config.headers.test = 'special get headers'; + return config; +}, null, { runWhen: onGetCall }); +``` + +### Multiple Interceptors + +Given you add multiple response interceptors +and when the response was fulfilled +- then each interceptor is executed +- then they are executed in the order they were added +- then only the last interceptor's result is returned +- then every interceptor receives the result of its predecessor +- and when the fulfillment-interceptor throws + - then the following fulfillment-interceptor is not called + - then the following rejection-interceptor is called + - once caught, another following fulfill-interceptor is called again (just like in a promise chain). + +Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code. + +## Handling Errors + +the default behavior is to reject every response that returns with a status code that falls out of the range of 2xx and treat it as an error. + +```js +axios.get('/user/12345') + .catch(function (error) { + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + console.log(error.response.data); + console.log(error.response.status); + console.log(error.response.headers); + } else if (error.request) { + // The request was made but no response was received + // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // http.ClientRequest in node.js + console.log(error.request); + } else { + // Something happened in setting up the request that triggered an Error + console.log('Error', error.message); + } + console.log(error.config); + }); +``` + +Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error. + +```js +axios.get('/user/12345', { + validateStatus: function (status) { + return status < 500; // Resolve only if the status code is less than 500 + } +}) +``` + +Using `toJSON` you get an object with more information about the HTTP error. + +```js +axios.get('/user/12345') + .catch(function (error) { + console.log(error.toJSON()); + }); +``` + +## Cancellation + +### AbortController + +Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way: + +```js +const controller = new AbortController(); + +axios.get('/foo/bar', { + signal: controller.signal +}).then(function(response) { + //... +}); +// cancel the request +controller.abort() +``` + +### CancelToken `👎deprecated` + +You can also cancel a request using a *CancelToken*. + +> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises). + +> This API is deprecated since v0.22.0 and shouldn't be used in new projects + +You can create a cancel token using the `CancelToken.source` factory as shown below: + +```js +const CancelToken = axios.CancelToken; +const source = CancelToken.source(); + +axios.get('/user/12345', { + cancelToken: source.token +}).catch(function (thrown) { + if (axios.isCancel(thrown)) { + console.log('Request canceled', thrown.message); + } else { + // handle error + } +}); + +axios.post('/user/12345', { + name: 'new name' +}, { + cancelToken: source.token +}) + +// cancel the request (the message parameter is optional) +source.cancel('Operation canceled by the user.'); +``` + +You can also create a cancel token by passing an executor function to the `CancelToken` constructor: + +```js +const CancelToken = axios.CancelToken; +let cancel; + +axios.get('/user/12345', { + cancelToken: new CancelToken(function executor(c) { + // An executor function receives a cancel function as a parameter + cancel = c; + }) +}); + +// cancel the request +cancel(); +``` + +> **Note:** you can cancel several requests with the same cancel token/abort controller. +> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make a real request. + +> During the transition period, you can use both cancellation APIs, even for the same request: + +## Using `application/x-www-form-urlencoded` format + +### URLSearchParams + +By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded` format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers,and [ Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018). + +```js +const params = new URLSearchParams({ foo: 'bar' }); +params.append('extraparam', 'value'); +axios.post('/foo', params); +``` + +### Query string (Older browsers) + +For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). + +Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: + +```js +const qs = require('qs'); +axios.post('/foo', qs.stringify({ 'bar': 123 })); +``` + +Or in another way (ES6), + +```js +import qs from 'qs'; +const data = { 'bar': 123 }; +const options = { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(data), + url, +}; +axios(options); +``` + +### Older Node.js versions + +For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: + +```js +const querystring = require('querystring'); +axios.post('https://something.com/', querystring.stringify({ foo: 'bar' })); +``` + +You can also use the [`qs`](https://github.com/ljharb/qs) library. + +> **Note** +> The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case. + +### 🆕 Automatic serialization to URLSearchParams + +Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded". + +```js +const data = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], +}; + +await axios.postForm('https://postman-echo.com/post', data, + {headers: {'content-type': 'application/x-www-form-urlencoded'}} +); +``` + +The server will handle it as: + +```js + { + x: '1', + 'arr[]': [ '1', '2', '3' ], + 'arr2[0]': '1', + 'arr2[1][0]': '2', + 'arr2[2]': '3', + 'arr3[]': [ '1', '2', '3' ], + 'users[0][name]': 'Peter', + 'users[0][surname]': 'griffin', + 'users[1][name]': 'Thomas', + 'users[1][surname]': 'Anderson' + } +```` + +If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically + +```js + var app = express(); + + app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies + + app.post('/', function (req, res, next) { + // echo body as JSON + res.send(JSON.stringify(req.body)); + }); + + server = app.listen(3000); +``` + +## Using `multipart/form-data` format + +### FormData + +To send the data as a `multipart/formdata` you need to pass a formData instance as a payload. +Setting the `Content-Type` header is not required as Axios guesses it based on the payload type. + +```js +const formData = new FormData(); +formData.append('foo', 'bar'); + +axios.post('https://httpbin.org/post', formData); +``` + +In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows: + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +axios.post('https://example.com', form) +``` + +### 🆕 Automatic serialization to FormData + +Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type` +header is set to `multipart/form-data`. + +The following request will submit the data in a FormData format (Browser & Node.js): + +```js +import axios from 'axios'; + +axios.post('https://httpbin.org/post', {x: 1}, { + headers: { + 'Content-Type': 'multipart/form-data' + } +}).then(({data}) => console.log(data)); +``` + +In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default. + +You can overload the FormData class by setting the `env.FormData` config variable, +but you probably won't need it in most cases: + +```js +const axios = require('axios'); +var FormData = require('form-data'); + +axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { + headers: { + 'Content-Type': 'multipart/form-data' + } +}).then(({data}) => console.log(data)); +``` + +Axios FormData serializer supports some special endings to perform the following operations: + +- `{}` - serialize the value with JSON.stringify +- `[]` - unwrap the array-like object as separate fields with the same key + +> **Note** +> unwrap/expand operation will be used by default on arrays and FileList objects + +FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases: + +- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object +to a `FormData` object by following custom rules. + +- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects; + +- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key. +The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON. + +- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects + + - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`) + - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`) + - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`) + +Let's say we have an object like this one: + +```js +const obj = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], + 'obj2{}': [{x:1}] +}; +``` + +The following steps will be executed by the Axios serializer internally: + +```js +const formData = new FormData(); +formData.append('x', '1'); +formData.append('arr[]', '1'); +formData.append('arr[]', '2'); +formData.append('arr[]', '3'); +formData.append('arr2[0]', '1'); +formData.append('arr2[1][0]', '2'); +formData.append('arr2[2]', '3'); +formData.append('users[0][name]', 'Peter'); +formData.append('users[0][surname]', 'Griffin'); +formData.append('users[1][name]', 'Thomas'); +formData.append('users[1][surname]', 'Anderson'); +formData.append('obj2{}', '[{"x":1}]'); +``` + +Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` +which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`. + +## Files Posting + +You can easily submit a single file: + +```js +await axios.postForm('https://httpbin.org/post', { + 'myVar' : 'foo', + 'file': document.querySelector('#fileInput').files[0] +}); +``` + +or multiple files as `multipart/form-data`: + +```js +await axios.postForm('https://httpbin.org/post', { + 'files[]': document.querySelector('#fileInput').files +}); +``` + +`FileList` object can be passed directly: + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) +``` + +All files will be sent with the same field names: `files[]`. + +## 🆕 HTML Form Posting (browser) + +Pass HTML Form element as a payload to submit it as `multipart/form-data` content. + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm')); +``` + +`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`: + +```js +await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), { + headers: { + 'Content-Type': 'application/json' + } +}) +``` + +For example, the Form + +```html +
+ + + + + + + + + +
+``` + +will be submitted as the following JSON object: + +```js +{ + "foo": "1", + "deep": { + "prop": { + "spaced": "3" + } + }, + "baz": [ + "4", + "5" + ], + "user": { + "age": "value2" + } +} +```` + +Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported. + +## 🆕 Progress capturing + +Axios supports both browser and node environments to capture request upload/download progress. + +```js +await axios.post(url, data, { + onUploadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; // in range [0..1] + bytes: number; // how many bytes have been transferred since the last trigger (delta) + estimated?: number; // estimated time in seconds + rate?: number; // upload speed in bytes + upload: true; // upload sign + }*/ + }, + + onDownloadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; + bytes: number; + estimated?: number; + rate?: number; // download speed in bytes + download: true; // download sign + }*/ + } +}); +``` + +You can also track stream upload/download progress in node.js: + +```js +const {data} = await axios.post(SERVER_URL, readableStream, { + onUploadProgress: ({progress}) => { + console.log((progress * 100).toFixed(2)); + }, + + headers: { + 'Content-Length': contentLength + }, + + maxRedirects: 0 // avoid buffering the entire stream +}); +```` + +> **Note:** +> Capturing FormData upload progress is currently not currently supported in node.js environments. + +> **⚠️ Warning** +> It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment, +> as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm. + + +## 🆕 Rate limiting + +Download and upload rate limits can only be set for the http adapter (node.js): + +```js +const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, { + onUploadProgress: ({progress, rate}) => { + console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`) + }, + + maxRate: [100 * 1024], // 100KB/s limit +}); +``` + +## Semver + +Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. + +## Promises + +axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises). +If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). + +## TypeScript + +axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors. + +```typescript +let user: User = null; +try { + const { data } = await axios.get('/user?ID=12345'); + user = data.userDetails; +} catch (error) { + if (axios.isAxiosError(error)) { + handleAxiosError(error); + } else { + handleUnexpectedError(error); + } +} +``` + +Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats. +The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater. +If use ESM, your settings should be fine. +If you compile TypeScript to CJS and you can’t use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`. +If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`. + +## Online one-click setup + +You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js) + + +## Resources + +* [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) +* [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md) +* [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md) +* [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md) + +## Credits + +axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS. + +## License + +[MIT](LICENSE) diff --git a/node_modules/axios/SECURITY.md b/node_modules/axios/SECURITY.md new file mode 100644 index 0000000..a5a2b7d --- /dev/null +++ b/node_modules/axios/SECURITY.md @@ -0,0 +1,6 @@ +# Reporting a Vulnerability + +If you discover a security vulnerability in axios please disclose it via [our huntr page](https://huntr.dev/repos/axios/axios/). Bounty eligibility, CVE assignment, response times and past reports are all there. + + +Thank you for improving the security of axios. diff --git a/node_modules/axios/index.d.cts b/node_modules/axios/index.d.cts new file mode 100644 index 0000000..0aee7aa --- /dev/null +++ b/node_modules/axios/index.d.cts @@ -0,0 +1,528 @@ +type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + +interface RawAxiosHeaders { + [key: string]: AxiosHeaderValue; +} + +type MethodsHeaders = Partial<{ + [Key in axios.Method as Lowercase]: AxiosHeaders; +} & {common: AxiosHeaders}>; + +type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean; + +type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent'| 'Content-Encoding' | 'Authorization'; + +type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream'; + +type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding'; + +declare class AxiosHeaders { + constructor( + headers?: RawAxiosHeaders | AxiosHeaders + ); + + [key: string]: any; + + set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + set(headers?: RawAxiosHeaders | AxiosHeaders, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; + + has(header: string, matcher?: true | AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat(...targets: Array): AxiosHeaders; + + toJSON(asStrings?: boolean): RawAxiosHeaders; + + static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat(...targets: Array): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; +} + +declare class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: axios.InternalAxiosRequestConfig, + request?: any, + response?: axios.AxiosResponse + ); + + config?: axios.InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: axios.AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_DEPRECATED = "ERR_DEPRECATED"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} + +declare class CanceledError extends AxiosError { +} + +declare class Axios { + constructor(config?: axios.AxiosRequestConfig); + defaults: axios.AxiosDefaults; + interceptors: { + request: axios.AxiosInterceptorManager; + response: axios.AxiosInterceptorManager; + }; + getUri(config?: axios.AxiosRequestConfig): string; + request, D = any>(config: axios.AxiosRequestConfig): Promise; + get, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + delete, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + head, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + options, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + post, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + put, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patch, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + postForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + putForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patchForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; +} + +declare enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +type InternalAxiosError = AxiosError; + +declare namespace axios { + type AxiosError = InternalAxiosError; + + type RawAxiosRequestHeaders = Partial; + + type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + + type RawCommonResponseHeaders = { + [Key in CommonResponseHeadersList]: AxiosHeaderValue; + } & { + "set-cookie": string[]; + }; + + type RawAxiosResponseHeaders = Partial; + + type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + + interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; + } + + interface AxiosResponseTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; + } + + interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; + } + + interface AxiosBasicCredentials { + username: string; + password: string; + } + + interface AxiosProxyConfig { + host: string; + port: number; + auth?: { + username: string; + password: string; + }; + protocol?: string; + } + + type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK'; + + type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + type responseEncoding = + | 'ascii' | 'ASCII' + | 'ansi' | 'ANSI' + | 'binary' | 'BINARY' + | 'base64' | 'BASE64' + | 'base64url' | 'BASE64URL' + | 'hex' | 'HEX' + | 'latin1' | 'LATIN1' + | 'ucs-2' | 'UCS-2' + | 'ucs2' | 'UCS2' + | 'utf-8' | 'UTF-8' + | 'utf8' | 'UTF8' + | 'utf16le' | 'UTF16LE'; + + interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; + } + + interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; + } + + interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; + } + + interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; + } + + interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; + } + + // tslint:disable-next-line + interface FormSerializerOptions extends SerializerOptions { + } + + interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; + } + + interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; + } + + interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; + } + + type MaxUploadRate = number; + + type MaxDownloadRate = number; + + type BrowserProgressEvent = any; + + interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; + } + + type Milliseconds = number; + + type AxiosAdapterName = 'xhr' | 'http' | string; + + type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + + interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: (options: Record, responseDetails: {headers: Record}) => void; + socketPath?: string | null; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + }; + formSerializer?: FormSerializerOptions; + } + + // Alias + type RawAxiosRequestConfig = AxiosRequestConfig; + + interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; + } + + interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; + } + + interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; + } + + interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; + } + + interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: RawAxiosResponseHeaders | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; + } + + type AxiosPromise = Promise>; + + interface CancelStatic { + new (message?: string): Cancel; + } + + interface Cancel { + message: string | undefined; + } + + interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; + } + + interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; + } + + interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; + } + + interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; + } + + interface AxiosInterceptorManager { + use(onFulfilled?: (value: V) => V | Promise, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number; + eject(id: number): void; + clear(): void; + } + + interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; + + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue + } + }; + } + + interface GenericFormData { + append(name: string, value: any, options?: any): any; + } + + interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; + } + + interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + CanceledError: typeof CanceledError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel(value: any): value is Cancel; + all(values: Array>): Promise; + spread(callback: (...args: T[]) => R): (array: T[]) => R; + isAxiosError(payload: any): payload is AxiosError; + toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; + formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + AxiosHeaders: typeof AxiosHeaders; + } +} + +declare const axios: axios.AxiosStatic; + +export = axios; diff --git a/node_modules/axios/index.d.ts b/node_modules/axios/index.d.ts new file mode 100644 index 0000000..be5f182 --- /dev/null +++ b/node_modules/axios/index.d.ts @@ -0,0 +1,543 @@ +// TypeScript Version: 4.7 +type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + +interface RawAxiosHeaders { + [key: string]: AxiosHeaderValue; +} + +type MethodsHeaders = Partial<{ + [Key in Method as Lowercase]: AxiosHeaders; +} & {common: AxiosHeaders}>; + +type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean; + +export class AxiosHeaders { + constructor( + headers?: RawAxiosHeaders | AxiosHeaders + ); + + [key: string]: any; + + set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + set(headers?: RawAxiosHeaders | AxiosHeaders, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; + + has(header: string, matcher?: true | AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat(...targets: Array): AxiosHeaders; + + toJSON(asStrings?: boolean): RawAxiosHeaders; + + static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat(...targets: Array): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; +} + +type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization'; + +type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream'; + +export type RawAxiosRequestHeaders = Partial; + +export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + +type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding'; + +type RawCommonResponseHeaders = { + [Key in CommonResponseHeadersList]: AxiosHeaderValue; +} & { + "set-cookie": string[]; +}; + +export type RawAxiosResponseHeaders = Partial; + +export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + +export interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; +} + +export interface AxiosResponseTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; +} + +export interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; +} + +export interface AxiosBasicCredentials { + username: string; + password: string; +} + +export interface AxiosProxyConfig { + host: string; + port: number; + auth?: { + username: string; + password: string; + }; + protocol?: string; +} + +export enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +export type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK'; + +export type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + +export type responseEncoding = + | 'ascii' | 'ASCII' + | 'ansi' | 'ANSI' + | 'binary' | 'BINARY' + | 'base64' | 'BASE64' + | 'base64url' | 'BASE64URL' + | 'hex' | 'HEX' + | 'latin1' | 'LATIN1' + | 'ucs-2' | 'UCS-2' + | 'ucs2' | 'UCS2' + | 'utf-8' | 'UTF-8' + | 'utf8' | 'UTF8' + | 'utf16le' | 'UTF16LE'; + +export interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; +} + +export interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; +} + +export interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; +} + +export interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; +} + +export interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; +} + +// tslint:disable-next-line +export interface FormSerializerOptions extends SerializerOptions { +} + +export interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; +} + +export interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; +} + +export interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; +} + +type MaxUploadRate = number; + +type MaxDownloadRate = number; + +type BrowserProgressEvent = any; + +export interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; +} + +type Milliseconds = number; + +type AxiosAdapterName = 'xhr' | 'http' | string; + +type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + +export interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: (options: Record, responseDetails: {headers: Record}) => void; + socketPath?: string | null; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + }; + formSerializer?: FormSerializerOptions; +} + +// Alias +export type RawAxiosRequestConfig = AxiosRequestConfig; + +export interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; +} + +export interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; +} + +export interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; +} + +export interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; +} + +export interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: RawAxiosResponseHeaders | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; +} + +export class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse + ); + + config?: InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + static from( + error: Error | unknown, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse, + customProps?: object, +): AxiosError; + static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_DEPRECATED = "ERR_DEPRECATED"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} + +export class CanceledError extends AxiosError { +} + +export type AxiosPromise = Promise>; + +export interface CancelStatic { + new (message?: string): Cancel; +} + +export interface Cancel { + message: string | undefined; +} + +export interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; +} + +export interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; +} + +export interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; +} + +export interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; +} + +export interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +} + +export interface AxiosInterceptorManager { + use(onFulfilled?: ((value: V) => V | Promise) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions): number; + eject(id: number): void; + clear(): void; +} + +export class Axios { + constructor(config?: AxiosRequestConfig); + defaults: AxiosDefaults; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri(config?: AxiosRequestConfig): string; + request, D = any>(config: AxiosRequestConfig): Promise; + get, D = any>(url: string, config?: AxiosRequestConfig): Promise; + delete, D = any>(url: string, config?: AxiosRequestConfig): Promise; + head, D = any>(url: string, config?: AxiosRequestConfig): Promise; + options, D = any>(url: string, config?: AxiosRequestConfig): Promise; + post, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + put, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + patch, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + postForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + putForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + patchForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; +} + +export interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; + + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue + } + }; +} + +export interface GenericFormData { + append(name: string, value: any, options?: any): any; +} + +export interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; +} + +export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; + +export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + +export function isAxiosError(payload: any): payload is AxiosError; + +export function spread(callback: (...args: T[]) => R): (array: T[]) => R; + +export function isCancel(value: any): value is Cancel; + +export function all(values: Array>): Promise; + +export interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel: typeof isCancel; + all: typeof all; + spread: typeof spread; + isAxiosError: typeof isAxiosError; + toFormData: typeof toFormData; + formToJSON: typeof formToJSON; + CanceledError: typeof CanceledError; + AxiosHeaders: typeof AxiosHeaders; +} + +declare const axios: AxiosStatic; + +export default axios; diff --git a/node_modules/axios/index.js b/node_modules/axios/index.js new file mode 100644 index 0000000..4920f55 --- /dev/null +++ b/node_modules/axios/index.js @@ -0,0 +1,41 @@ +import axios from './lib/axios.js'; + +// This module is intended to unwrap Axios default export as named. +// Keep top-level export same with static properties +// so that it can keep same with es module or cjs +const { + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + mergeConfig +} = axios; + +export { + axios as default, + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + mergeConfig +} diff --git a/node_modules/axios/package.json b/node_modules/axios/package.json new file mode 100644 index 0000000..630a945 --- /dev/null +++ b/node_modules/axios/package.json @@ -0,0 +1,206 @@ +{ + "name": "axios", + "version": "1.3.4", + "description": "Promise based HTTP client for the browser and node.js", + "main": "index.js", + "exports": { + ".": { + "types": { + "require": "./index.d.cts", + "default": "./index.d.ts" + }, + "browser": { + "require": "./dist/browser/axios.cjs", + "default": "./index.js" + }, + "default": { + "require": "./dist/node/axios.cjs", + "default": "./index.js" + } + }, + "./package.json": "./package.json" + }, + "type": "module", + "types": "index.d.ts", + "scripts": { + "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint && npm run test:exports", + "test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js", + "test:dtslint": "node bin/ssl_hotfix.js dtslint", + "test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit", + "test:exports": "node bin/ssl_hotfix.js mocha test/module/test.js --timeout 30000 --exit", + "test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run", + "test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs", + "test:build:version": "node ./bin/check-build-version.js", + "start": "node ./sandbox/server.js", + "preversion": "gulp version", + "version": "npm run build && git add dist && git add package.json", + "prepublishOnly": "npm run test:build:version", + "postpublish": "git push && git push --tags", + "build": "gulp clear && cross-env NODE_ENV=production rollup -c -m", + "examples": "node ./examples/server.js", + "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", + "fix": "eslint --fix lib/**/*.js", + "prepare": "husky install && npm run prepare:hooks", + "prepare:hooks": "npx husky set .husky/commit-msg \"npx commitlint --edit $1\"", + "release:dry": "release-it --dry-run --no-npm", + "release:info": "release-it --release-version", + "release:beta:no-npm": "release-it --preRelease=beta --no-npm", + "release:beta": "release-it --preRelease=beta", + "release:no-npm": "release-it --no-npm", + "release:changelog:fix": "node ./bin/injectContributorsList.js && git add CHANGELOG.md", + "release": "release-it" + }, + "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://axios-http.com", + "devDependencies": { + "@babel/core": "^7.18.2", + "@babel/preset-env": "^7.18.2", + "@commitlint/cli": "^17.3.0", + "@commitlint/config-conventional": "^17.3.0", + "@release-it/conventional-changelog": "^5.1.1", + "@rollup/plugin-babel": "^5.3.1", + "@rollup/plugin-commonjs": "^15.1.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-multi-entry": "^4.0.0", + "@rollup/plugin-node-resolve": "^9.0.0", + "abortcontroller-polyfill": "^1.7.3", + "auto-changelog": "^2.4.0", + "body-parser": "^1.20.0", + "chalk": "^5.2.0", + "coveralls": "^3.1.1", + "cross-env": "^7.0.3", + "dev-null": "^0.1.1", + "dtslint": "^4.2.1", + "es6-promise": "^4.2.8", + "eslint": "^8.17.0", + "express": "^4.18.1", + "formdata-node": "^5.0.0", + "formidable": "^2.0.1", + "fs-extra": "^10.1.0", + "get-stream": "^3.0.0", + "gulp": "^4.0.2", + "gzip-size": "^7.0.0", + "handlebars": "^4.7.7", + "husky": "^8.0.2", + "istanbul-instrumenter-loader": "^3.0.1", + "jasmine-core": "^2.4.1", + "karma": "^6.3.17", + "karma-chrome-launcher": "^3.1.1", + "karma-firefox-launcher": "^2.1.2", + "karma-jasmine": "^1.1.1", + "karma-jasmine-ajax": "^0.1.13", + "karma-rollup-preprocessor": "^7.0.8", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^4.3.6", + "karma-sinon": "^1.0.5", + "karma-sourcemap-loader": "^0.3.8", + "minimist": "^1.2.7", + "mocha": "^10.0.0", + "multer": "^1.4.4", + "pretty-bytes": "^6.0.0", + "release-it": "^15.5.1", + "rollup": "^2.67.0", + "rollup-plugin-auto-external": "^2.0.0", + "rollup-plugin-bundle-size": "^1.0.3", + "rollup-plugin-terser": "^7.0.2", + "sinon": "^4.5.0", + "stream-throttle": "^0.1.3", + "string-replace-async": "^3.0.2", + "terser-webpack-plugin": "^4.2.3", + "typescript": "^4.8.4", + "url-search-params": "^0.10.0" + }, + "browser": { + "./lib/adapters/http.js": "./lib/helpers/null.js", + "./lib/platform/node/index.js": "./lib/platform/browser/index.js", + "./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js" + }, + "jsdelivr": "dist/axios.min.js", + "unpkg": "dist/axios.min.js", + "typings": "./index.d.ts", + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + }, + "bundlesize": [ + { + "path": "./dist/axios.min.js", + "threshold": "5kB" + } + ], + "contributors": [ + "Matt Zabriskie (https://github.com/mzabriskie)", + "Nick Uraltsev (https://github.com/nickuraltsev)", + "Jay (https://github.com/jasonsaayman)", + "Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)", + "Emily Morehouse (https://github.com/emilyemorehouse)", + "Rubén Norte (https://github.com/rubennorte)", + "Justin Beckwith (https://github.com/JustinBeckwith)", + "Martti Laine (https://github.com/codeclown)", + "Xianming Zhong (https://github.com/chinesedfan)", + "Rikki Gibson (https://github.com/RikkiGibson)", + "Remco Haszing (https://github.com/remcohaszing)", + "Yasu Flores (https://github.com/yasuf)", + "Ben Carp (https://github.com/carpben)" + ], + "sideEffects": false, + "release-it": { + "git": { + "commitMessage": "chore(release): v${version}", + "push": true, + "commit": true, + "tag": true, + "requireCommits": false, + "requireCleanWorkingDir": false + }, + "github": { + "release": true, + "draft": true + }, + "npm": { + "publish": false, + "ignoreVersion": false + }, + "plugins": { + "@release-it/conventional-changelog": { + "preset": "angular", + "infile": "CHANGELOG.md", + "header": "# Changelog" + } + }, + "hooks": { + "before:init": "npm test", + "after:bump": "gulp version --bump ${version} && npm run build && npm run test:build:version && git add ./dist && git add ./package-lock.json", + "before:release": "npm run release:changelog:fix", + "after:release": "echo Successfully released ${name} v${version} to ${repo.repository}." + } + }, + "commitlint": { + "rules": { + "header-max-length": [ + 2, + "always", + 130 + ] + }, + "extends": [ + "@commitlint/config-conventional" + ] + } +} \ No newline at end of file diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'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) { + if(a===b) { + return [ai, bi]; + } + 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; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..ce6073e --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/base64-js/LICENSE b/node_modules/base64-js/LICENSE new file mode 100644 index 0000000..6d52b8a --- /dev/null +++ b/node_modules/base64-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +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. diff --git a/node_modules/base64-js/README.md b/node_modules/base64-js/README.md new file mode 100644 index 0000000..b42a48f --- /dev/null +++ b/node_modules/base64-js/README.md @@ -0,0 +1,34 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` and `var base64js = require('base64-js')` + +For use in web browsers do: + +`` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..908ac83 --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 0000000..c3972e3 --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/big-integer/BigInteger.d.ts b/node_modules/big-integer/BigInteger.d.ts new file mode 100644 index 0000000..df5b865 --- /dev/null +++ b/node_modules/big-integer/BigInteger.d.ts @@ -0,0 +1,2393 @@ +/** + * Type definitions for BigInteger.js + * Definitions by: Tommy Frazier + */ +export = bigInt; +export as namespace bigInt; + +declare var bigInt: bigInt.BigIntegerStatic; + +declare namespace bigInt { + type BigNumber = number | bigint | string | BigInteger; + + interface BigIntegerStatic { + /** + * Equivalent to bigInt(0). + */ + (): BigInteger; + + /** + * Parse a Javascript number into a bigInt. + */ + (number: number): BigInteger; + + /** + * Parse a Javascript native bigint into a bigInt. + */ + (number: bigint): BigInteger; + + /** + * Parse a string into a bigInt. + * Default base is 10. + * Default alphabet is "0123456789abcdefghijklmnopqrstuvwxyz". + * caseSensitive defaults to false. + */ + (string: string, base?: BigNumber, alphabet?: string, caseSensitive?: boolean): BigInteger; + + /** + * no-op. + */ + (bigInt: BigInteger): BigInteger; + + /** + * Constructs a bigInt from an array of digits in specified base. + * The optional isNegative flag will make the number negative. + */ + fromArray: (digits: BigNumber[], base?: BigNumber, isNegative?: boolean) => BigInteger; + + /** + * Finds the greatest common denominator of a and b. + */ + gcd: (a: BigNumber, b: BigNumber) => BigInteger; + + + /** + * Returns true if x is a BigInteger, false otherwise. + */ + isInstance: (x: any) => x is BigInteger; + + /** + * Finds the least common multiple of a and b. + */ + lcm: (a: BigNumber, b: BigNumber) => BigInteger; + + /** + * Returns the largest of a and b. + */ + max: (a: BigNumber, b: BigNumber) => BigInteger; + + /** + * Returns the smallest of a and b. + */ + min: (a: BigNumber, b: BigNumber) => BigInteger; + + /** + * Equivalent to bigInt(-1). + */ + minusOne: BigInteger; + + /** + * Equivalent to bigInt(1). + */ + one: BigInteger; + + /** + * Returns a random number between min and max. + */ + randBetween: (min: BigNumber, max: BigNumber, rng?: () => number) => BigInteger; + + /** + * Equivalent to bigInt(0). + */ + zero: BigInteger; + } + + interface BigInteger { + /** + * Returns the absolute value of a bigInt. + */ + abs(): BigInteger; + + /** + * Performs addition. + */ + add(number: BigNumber): BigInteger; + + /** + * Performs the bitwise AND operation. + */ + and(number: BigNumber): BigInteger; + + /** + * Returns the number of digits required to represent a bigInt in binary. + */ + bitLength(): BigInteger; + + /** + * Performs a comparison between two numbers. If the numbers are equal, it returns 0. + * If the first number is greater, it returns 1. If the first number is lesser, it returns -1. + */ + compare(number: BigNumber): number; + + /** + * Performs a comparison between the absolute value of two numbers. + */ + compareAbs(number: BigNumber): number; + + /** + * Alias for the compare method. + */ + compareTo(number: BigNumber): number; + + /** + * Performs integer division, disregarding the remainder. + */ + divide(number: BigNumber): BigInteger; + + /** + * Performs division and returns an object with two properties: quotient and remainder. + * The sign of the remainder will match the sign of the dividend. + */ + divmod(number: BigNumber): { quotient: BigInteger, remainder: BigInteger }; + + /** + * Alias for the equals method. + */ + eq(number: BigNumber): boolean; + + /** + * Checks if two numbers are equal. + */ + equals(number: BigNumber): boolean; + + /** + * Alias for the greaterOrEquals method. + */ + geq(number: BigNumber): boolean; + + /** + * Checks if the first number is greater than the second. + */ + greater(number: BigNumber): boolean; + + /** + * Checks if the first number is greater than or equal to the second. + */ + greaterOrEquals(number: BigNumber): boolean; + + /** + * Alias for the greater method. + */ + gt(number: BigNumber): boolean; + + /** + * Returns true if the first number is divisible by the second number, false otherwise. + */ + isDivisibleBy(number: BigNumber): boolean; + + /** + * Returns true if the number is even, false otherwise. + */ + isEven(): boolean; + + /** + * Returns true if the number is negative, false otherwise. + * Returns false for 0 and true for -0. + */ + isNegative(): boolean; + + /** + * Returns true if the number is odd, false otherwise. + */ + isOdd(): boolean; + + /** + * Return true if the number is positive, false otherwise. + * Returns true for 0 and false for -0. + */ + isPositive(): boolean; + + /** + * Returns true if the number is prime, false otherwise. + */ + isPrime(strict?: boolean): boolean; + + /** + * Returns true if the number is very likely to be prime, false otherwise. + */ + isProbablePrime(iterations?: number, rng?: () => number): boolean; + + /** + * Returns true if the number is 1 or -1, false otherwise. + */ + isUnit(): boolean; + + /** + * Return true if the number is 0 or -0, false otherwise. + */ + isZero(): boolean; + + /** + * Alias for the lesserOrEquals method. + */ + leq(number: BigNumber): boolean; + + /** + * Checks if the first number is lesser than the second. + */ + lesser(number: BigNumber): boolean; + + /** + * Checks if the first number is less than or equal to the second. + */ + lesserOrEquals(number: BigNumber): boolean; + + /** + * Alias for the lesser method. + */ + lt(number: BigNumber): boolean; + + /** + * Alias for the subtract method. + */ + minus(number: BigNumber): BigInteger; + + /** + * Performs division and returns the remainder, disregarding the quotient. + * The sign of the remainder will match the sign of the dividend. + */ + mod(number: BigNumber): BigInteger; + + /** + * Finds the multiplicative inverse of the number modulo mod. + */ + modInv(number: BigNumber): BigInteger; + + /** + * Takes the number to the power exp modulo mod. + */ + modPow(exp: BigNumber, mod: BigNumber): BigInteger; + + /** + * Performs multiplication. + */ + multiply(number: BigNumber): BigInteger; + + /** + * Reverses the sign of the number. + */ + negate(): BigInteger; + + /** + * Alias for the notEquals method. + */ + neq(number: BigNumber): boolean; + + /** + * Adds one to the number. + */ + next(): BigInteger; + + /** + * Performs the bitwise NOT operation. + */ + not(): BigInteger; + + /** + * Checks if two numbers are not equal. + */ + notEquals(number: BigNumber): boolean; + + /** + * Performs the bitwise OR operation. + */ + or(number: BigNumber): BigInteger; + + /** + * Alias for the divide method. + */ + over(number: BigNumber): BigInteger; + + /** + * Alias for the add method. + */ + plus(number: BigNumber): BigInteger; + + /** + * Performs exponentiation. If the exponent is less than 0, pow returns 0. + * bigInt.zero.pow(0) returns 1. + */ + pow(number: BigNumber): BigInteger; + + /** + * Subtracts one from the number. + */ + prev(): BigInteger; + + /** + * Alias for the mod method. + */ + remainder(number: BigNumber): BigInteger; + + /** + * Shifts the number left by n places in its binary representation. + * If a negative number is provided, it will shift right. + * + * Throws an error if number is outside of the range [-9007199254740992, 9007199254740992]. + */ + shiftLeft(number: BigNumber): BigInteger; + + /** + * Shifts the number right by n places in its binary representation. + * If a negative number is provided, it will shift left. + * + * Throws an error if number is outside of the range [-9007199254740992, 9007199254740992]. + */ + shiftRight(number: BigNumber): BigInteger; + + /** + * Squares the number. + */ + square(): BigInteger; + + /** + * Performs subtraction. + */ + subtract(number: BigNumber): BigInteger; + + /** + * Alias for the multiply method. + */ + times(number: BigNumber): BigInteger; + + /** + * + * Converts a bigInt to an object representing it as an array of integers module the given radix. + */ + toArray(radix: number): BaseArray; + + /** + * Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range. + */ + toJSNumber(): number; + + /** + * Converts a bigInt to a string. + */ + toString(radix?: number, alphabet?: string): string; + + /** + * Converts a bigInt to a string. This method is called behind the scenes in JSON.stringify. + */ + toJSON(): string; + + /** + * Converts a bigInt to a native Javascript number. This override allows you to use native + * arithmetic operators without explicit conversion. + */ + valueOf(): number; + + /** + * Performs the bitwise XOR operation. + */ + xor(number: BigNumber): BigInteger; + } + + // Array constant accessors + interface BigIntegerStatic { + '-999': BigInteger; + '-998': BigInteger; + '-997': BigInteger; + '-996': BigInteger; + '-995': BigInteger; + '-994': BigInteger; + '-993': BigInteger; + '-992': BigInteger; + '-991': BigInteger; + '-990': BigInteger; + '-989': BigInteger; + '-988': BigInteger; + '-987': BigInteger; + '-986': BigInteger; + '-985': BigInteger; + '-984': BigInteger; + '-983': BigInteger; + '-982': BigInteger; + '-981': BigInteger; + '-980': BigInteger; + '-979': BigInteger; + '-978': BigInteger; + '-977': BigInteger; + '-976': BigInteger; + '-975': BigInteger; + '-974': BigInteger; + '-973': BigInteger; + '-972': BigInteger; + '-971': BigInteger; + '-970': BigInteger; + '-969': BigInteger; + '-968': BigInteger; + '-967': BigInteger; + '-966': BigInteger; + '-965': BigInteger; + '-964': BigInteger; + '-963': BigInteger; + '-962': BigInteger; + '-961': BigInteger; + '-960': BigInteger; + '-959': BigInteger; + '-958': BigInteger; + '-957': BigInteger; + '-956': BigInteger; + '-955': BigInteger; + '-954': BigInteger; + '-953': BigInteger; + '-952': BigInteger; + '-951': BigInteger; + '-950': BigInteger; + '-949': BigInteger; + '-948': BigInteger; + '-947': BigInteger; + '-946': BigInteger; + '-945': BigInteger; + '-944': BigInteger; + '-943': BigInteger; + '-942': BigInteger; + '-941': BigInteger; + '-940': BigInteger; + '-939': BigInteger; + '-938': BigInteger; + '-937': BigInteger; + '-936': BigInteger; + '-935': BigInteger; + '-934': BigInteger; + '-933': BigInteger; + '-932': BigInteger; + '-931': BigInteger; + '-930': BigInteger; + '-929': BigInteger; + '-928': BigInteger; + '-927': BigInteger; + '-926': BigInteger; + '-925': BigInteger; + '-924': BigInteger; + '-923': BigInteger; + '-922': BigInteger; + '-921': BigInteger; + '-920': BigInteger; + '-919': BigInteger; + '-918': BigInteger; + '-917': BigInteger; + '-916': BigInteger; + '-915': BigInteger; + '-914': BigInteger; + '-913': BigInteger; + '-912': BigInteger; + '-911': BigInteger; + '-910': BigInteger; + '-909': BigInteger; + '-908': BigInteger; + '-907': BigInteger; + '-906': BigInteger; + '-905': BigInteger; + '-904': BigInteger; + '-903': BigInteger; + '-902': BigInteger; + '-901': BigInteger; + '-900': BigInteger; + '-899': BigInteger; + '-898': BigInteger; + '-897': BigInteger; + '-896': BigInteger; + '-895': BigInteger; + '-894': BigInteger; + '-893': BigInteger; + '-892': BigInteger; + '-891': BigInteger; + '-890': BigInteger; + '-889': BigInteger; + '-888': BigInteger; + '-887': BigInteger; + '-886': BigInteger; + '-885': BigInteger; + '-884': BigInteger; + '-883': BigInteger; + '-882': BigInteger; + '-881': BigInteger; + '-880': BigInteger; + '-879': BigInteger; + '-878': BigInteger; + '-877': BigInteger; + '-876': BigInteger; + '-875': BigInteger; + '-874': BigInteger; + '-873': BigInteger; + '-872': BigInteger; + '-871': BigInteger; + '-870': BigInteger; + '-869': BigInteger; + '-868': BigInteger; + '-867': BigInteger; + '-866': BigInteger; + '-865': BigInteger; + '-864': BigInteger; + '-863': BigInteger; + '-862': BigInteger; + '-861': BigInteger; + '-860': BigInteger; + '-859': BigInteger; + '-858': BigInteger; + '-857': BigInteger; + '-856': BigInteger; + '-855': BigInteger; + '-854': BigInteger; + '-853': BigInteger; + '-852': BigInteger; + '-851': BigInteger; + '-850': BigInteger; + '-849': BigInteger; + '-848': BigInteger; + '-847': BigInteger; + '-846': BigInteger; + '-845': BigInteger; + '-844': BigInteger; + '-843': BigInteger; + '-842': BigInteger; + '-841': BigInteger; + '-840': BigInteger; + '-839': BigInteger; + '-838': BigInteger; + '-837': BigInteger; + '-836': BigInteger; + '-835': BigInteger; + '-834': BigInteger; + '-833': BigInteger; + '-832': BigInteger; + '-831': BigInteger; + '-830': BigInteger; + '-829': BigInteger; + '-828': BigInteger; + '-827': BigInteger; + '-826': BigInteger; + '-825': BigInteger; + '-824': BigInteger; + '-823': BigInteger; + '-822': BigInteger; + '-821': BigInteger; + '-820': BigInteger; + '-819': BigInteger; + '-818': BigInteger; + '-817': BigInteger; + '-816': BigInteger; + '-815': BigInteger; + '-814': BigInteger; + '-813': BigInteger; + '-812': BigInteger; + '-811': BigInteger; + '-810': BigInteger; + '-809': BigInteger; + '-808': BigInteger; + '-807': BigInteger; + '-806': BigInteger; + '-805': BigInteger; + '-804': BigInteger; + '-803': BigInteger; + '-802': BigInteger; + '-801': BigInteger; + '-800': BigInteger; + '-799': BigInteger; + '-798': BigInteger; + '-797': BigInteger; + '-796': BigInteger; + '-795': BigInteger; + '-794': BigInteger; + '-793': BigInteger; + '-792': BigInteger; + '-791': BigInteger; + '-790': BigInteger; + '-789': BigInteger; + '-788': BigInteger; + '-787': BigInteger; + '-786': BigInteger; + '-785': BigInteger; + '-784': BigInteger; + '-783': BigInteger; + '-782': BigInteger; + '-781': BigInteger; + '-780': BigInteger; + '-779': BigInteger; + '-778': BigInteger; + '-777': BigInteger; + '-776': BigInteger; + '-775': BigInteger; + '-774': BigInteger; + '-773': BigInteger; + '-772': BigInteger; + '-771': BigInteger; + '-770': BigInteger; + '-769': BigInteger; + '-768': BigInteger; + '-767': BigInteger; + '-766': BigInteger; + '-765': BigInteger; + '-764': BigInteger; + '-763': BigInteger; + '-762': BigInteger; + '-761': BigInteger; + '-760': BigInteger; + '-759': BigInteger; + '-758': BigInteger; + '-757': BigInteger; + '-756': BigInteger; + '-755': BigInteger; + '-754': BigInteger; + '-753': BigInteger; + '-752': BigInteger; + '-751': BigInteger; + '-750': BigInteger; + '-749': BigInteger; + '-748': BigInteger; + '-747': BigInteger; + '-746': BigInteger; + '-745': BigInteger; + '-744': BigInteger; + '-743': BigInteger; + '-742': BigInteger; + '-741': BigInteger; + '-740': BigInteger; + '-739': BigInteger; + '-738': BigInteger; + '-737': BigInteger; + '-736': BigInteger; + '-735': BigInteger; + '-734': BigInteger; + '-733': BigInteger; + '-732': BigInteger; + '-731': BigInteger; + '-730': BigInteger; + '-729': BigInteger; + '-728': BigInteger; + '-727': BigInteger; + '-726': BigInteger; + '-725': BigInteger; + '-724': BigInteger; + '-723': BigInteger; + '-722': BigInteger; + '-721': BigInteger; + '-720': BigInteger; + '-719': BigInteger; + '-718': BigInteger; + '-717': BigInteger; + '-716': BigInteger; + '-715': BigInteger; + '-714': BigInteger; + '-713': BigInteger; + '-712': BigInteger; + '-711': BigInteger; + '-710': BigInteger; + '-709': BigInteger; + '-708': BigInteger; + '-707': BigInteger; + '-706': BigInteger; + '-705': BigInteger; + '-704': BigInteger; + '-703': BigInteger; + '-702': BigInteger; + '-701': BigInteger; + '-700': BigInteger; + '-699': BigInteger; + '-698': BigInteger; + '-697': BigInteger; + '-696': BigInteger; + '-695': BigInteger; + '-694': BigInteger; + '-693': BigInteger; + '-692': BigInteger; + '-691': BigInteger; + '-690': BigInteger; + '-689': BigInteger; + '-688': BigInteger; + '-687': BigInteger; + '-686': BigInteger; + '-685': BigInteger; + '-684': BigInteger; + '-683': BigInteger; + '-682': BigInteger; + '-681': BigInteger; + '-680': BigInteger; + '-679': BigInteger; + '-678': BigInteger; + '-677': BigInteger; + '-676': BigInteger; + '-675': BigInteger; + '-674': BigInteger; + '-673': BigInteger; + '-672': BigInteger; + '-671': BigInteger; + '-670': BigInteger; + '-669': BigInteger; + '-668': BigInteger; + '-667': BigInteger; + '-666': BigInteger; + '-665': BigInteger; + '-664': BigInteger; + '-663': BigInteger; + '-662': BigInteger; + '-661': BigInteger; + '-660': BigInteger; + '-659': BigInteger; + '-658': BigInteger; + '-657': BigInteger; + '-656': BigInteger; + '-655': BigInteger; + '-654': BigInteger; + '-653': BigInteger; + '-652': BigInteger; + '-651': BigInteger; + '-650': BigInteger; + '-649': BigInteger; + '-648': BigInteger; + '-647': BigInteger; + '-646': BigInteger; + '-645': BigInteger; + '-644': BigInteger; + '-643': BigInteger; + '-642': BigInteger; + '-641': BigInteger; + '-640': BigInteger; + '-639': BigInteger; + '-638': BigInteger; + '-637': BigInteger; + '-636': BigInteger; + '-635': BigInteger; + '-634': BigInteger; + '-633': BigInteger; + '-632': BigInteger; + '-631': BigInteger; + '-630': BigInteger; + '-629': BigInteger; + '-628': BigInteger; + '-627': BigInteger; + '-626': BigInteger; + '-625': BigInteger; + '-624': BigInteger; + '-623': BigInteger; + '-622': BigInteger; + '-621': BigInteger; + '-620': BigInteger; + '-619': BigInteger; + '-618': BigInteger; + '-617': BigInteger; + '-616': BigInteger; + '-615': BigInteger; + '-614': BigInteger; + '-613': BigInteger; + '-612': BigInteger; + '-611': BigInteger; + '-610': BigInteger; + '-609': BigInteger; + '-608': BigInteger; + '-607': BigInteger; + '-606': BigInteger; + '-605': BigInteger; + '-604': BigInteger; + '-603': BigInteger; + '-602': BigInteger; + '-601': BigInteger; + '-600': BigInteger; + '-599': BigInteger; + '-598': BigInteger; + '-597': BigInteger; + '-596': BigInteger; + '-595': BigInteger; + '-594': BigInteger; + '-593': BigInteger; + '-592': BigInteger; + '-591': BigInteger; + '-590': BigInteger; + '-589': BigInteger; + '-588': BigInteger; + '-587': BigInteger; + '-586': BigInteger; + '-585': BigInteger; + '-584': BigInteger; + '-583': BigInteger; + '-582': BigInteger; + '-581': BigInteger; + '-580': BigInteger; + '-579': BigInteger; + '-578': BigInteger; + '-577': BigInteger; + '-576': BigInteger; + '-575': BigInteger; + '-574': BigInteger; + '-573': BigInteger; + '-572': BigInteger; + '-571': BigInteger; + '-570': BigInteger; + '-569': BigInteger; + '-568': BigInteger; + '-567': BigInteger; + '-566': BigInteger; + '-565': BigInteger; + '-564': BigInteger; + '-563': BigInteger; + '-562': BigInteger; + '-561': BigInteger; + '-560': BigInteger; + '-559': BigInteger; + '-558': BigInteger; + '-557': BigInteger; + '-556': BigInteger; + '-555': BigInteger; + '-554': BigInteger; + '-553': BigInteger; + '-552': BigInteger; + '-551': BigInteger; + '-550': BigInteger; + '-549': BigInteger; + '-548': BigInteger; + '-547': BigInteger; + '-546': BigInteger; + '-545': BigInteger; + '-544': BigInteger; + '-543': BigInteger; + '-542': BigInteger; + '-541': BigInteger; + '-540': BigInteger; + '-539': BigInteger; + '-538': BigInteger; + '-537': BigInteger; + '-536': BigInteger; + '-535': BigInteger; + '-534': BigInteger; + '-533': BigInteger; + '-532': BigInteger; + '-531': BigInteger; + '-530': BigInteger; + '-529': BigInteger; + '-528': BigInteger; + '-527': BigInteger; + '-526': BigInteger; + '-525': BigInteger; + '-524': BigInteger; + '-523': BigInteger; + '-522': BigInteger; + '-521': BigInteger; + '-520': BigInteger; + '-519': BigInteger; + '-518': BigInteger; + '-517': BigInteger; + '-516': BigInteger; + '-515': BigInteger; + '-514': BigInteger; + '-513': BigInteger; + '-512': BigInteger; + '-511': BigInteger; + '-510': BigInteger; + '-509': BigInteger; + '-508': BigInteger; + '-507': BigInteger; + '-506': BigInteger; + '-505': BigInteger; + '-504': BigInteger; + '-503': BigInteger; + '-502': BigInteger; + '-501': BigInteger; + '-500': BigInteger; + '-499': BigInteger; + '-498': BigInteger; + '-497': BigInteger; + '-496': BigInteger; + '-495': BigInteger; + '-494': BigInteger; + '-493': BigInteger; + '-492': BigInteger; + '-491': BigInteger; + '-490': BigInteger; + '-489': BigInteger; + '-488': BigInteger; + '-487': BigInteger; + '-486': BigInteger; + '-485': BigInteger; + '-484': BigInteger; + '-483': BigInteger; + '-482': BigInteger; + '-481': BigInteger; + '-480': BigInteger; + '-479': BigInteger; + '-478': BigInteger; + '-477': BigInteger; + '-476': BigInteger; + '-475': BigInteger; + '-474': BigInteger; + '-473': BigInteger; + '-472': BigInteger; + '-471': BigInteger; + '-470': BigInteger; + '-469': BigInteger; + '-468': BigInteger; + '-467': BigInteger; + '-466': BigInteger; + '-465': BigInteger; + '-464': BigInteger; + '-463': BigInteger; + '-462': BigInteger; + '-461': BigInteger; + '-460': BigInteger; + '-459': BigInteger; + '-458': BigInteger; + '-457': BigInteger; + '-456': BigInteger; + '-455': BigInteger; + '-454': BigInteger; + '-453': BigInteger; + '-452': BigInteger; + '-451': BigInteger; + '-450': BigInteger; + '-449': BigInteger; + '-448': BigInteger; + '-447': BigInteger; + '-446': BigInteger; + '-445': BigInteger; + '-444': BigInteger; + '-443': BigInteger; + '-442': BigInteger; + '-441': BigInteger; + '-440': BigInteger; + '-439': BigInteger; + '-438': BigInteger; + '-437': BigInteger; + '-436': BigInteger; + '-435': BigInteger; + '-434': BigInteger; + '-433': BigInteger; + '-432': BigInteger; + '-431': BigInteger; + '-430': BigInteger; + '-429': BigInteger; + '-428': BigInteger; + '-427': BigInteger; + '-426': BigInteger; + '-425': BigInteger; + '-424': BigInteger; + '-423': BigInteger; + '-422': BigInteger; + '-421': BigInteger; + '-420': BigInteger; + '-419': BigInteger; + '-418': BigInteger; + '-417': BigInteger; + '-416': BigInteger; + '-415': BigInteger; + '-414': BigInteger; + '-413': BigInteger; + '-412': BigInteger; + '-411': BigInteger; + '-410': BigInteger; + '-409': BigInteger; + '-408': BigInteger; + '-407': BigInteger; + '-406': BigInteger; + '-405': BigInteger; + '-404': BigInteger; + '-403': BigInteger; + '-402': BigInteger; + '-401': BigInteger; + '-400': BigInteger; + '-399': BigInteger; + '-398': BigInteger; + '-397': BigInteger; + '-396': BigInteger; + '-395': BigInteger; + '-394': BigInteger; + '-393': BigInteger; + '-392': BigInteger; + '-391': BigInteger; + '-390': BigInteger; + '-389': BigInteger; + '-388': BigInteger; + '-387': BigInteger; + '-386': BigInteger; + '-385': BigInteger; + '-384': BigInteger; + '-383': BigInteger; + '-382': BigInteger; + '-381': BigInteger; + '-380': BigInteger; + '-379': BigInteger; + '-378': BigInteger; + '-377': BigInteger; + '-376': BigInteger; + '-375': BigInteger; + '-374': BigInteger; + '-373': BigInteger; + '-372': BigInteger; + '-371': BigInteger; + '-370': BigInteger; + '-369': BigInteger; + '-368': BigInteger; + '-367': BigInteger; + '-366': BigInteger; + '-365': BigInteger; + '-364': BigInteger; + '-363': BigInteger; + '-362': BigInteger; + '-361': BigInteger; + '-360': BigInteger; + '-359': BigInteger; + '-358': BigInteger; + '-357': BigInteger; + '-356': BigInteger; + '-355': BigInteger; + '-354': BigInteger; + '-353': BigInteger; + '-352': BigInteger; + '-351': BigInteger; + '-350': BigInteger; + '-349': BigInteger; + '-348': BigInteger; + '-347': BigInteger; + '-346': BigInteger; + '-345': BigInteger; + '-344': BigInteger; + '-343': BigInteger; + '-342': BigInteger; + '-341': BigInteger; + '-340': BigInteger; + '-339': BigInteger; + '-338': BigInteger; + '-337': BigInteger; + '-336': BigInteger; + '-335': BigInteger; + '-334': BigInteger; + '-333': BigInteger; + '-332': BigInteger; + '-331': BigInteger; + '-330': BigInteger; + '-329': BigInteger; + '-328': BigInteger; + '-327': BigInteger; + '-326': BigInteger; + '-325': BigInteger; + '-324': BigInteger; + '-323': BigInteger; + '-322': BigInteger; + '-321': BigInteger; + '-320': BigInteger; + '-319': BigInteger; + '-318': BigInteger; + '-317': BigInteger; + '-316': BigInteger; + '-315': BigInteger; + '-314': BigInteger; + '-313': BigInteger; + '-312': BigInteger; + '-311': BigInteger; + '-310': BigInteger; + '-309': BigInteger; + '-308': BigInteger; + '-307': BigInteger; + '-306': BigInteger; + '-305': BigInteger; + '-304': BigInteger; + '-303': BigInteger; + '-302': BigInteger; + '-301': BigInteger; + '-300': BigInteger; + '-299': BigInteger; + '-298': BigInteger; + '-297': BigInteger; + '-296': BigInteger; + '-295': BigInteger; + '-294': BigInteger; + '-293': BigInteger; + '-292': BigInteger; + '-291': BigInteger; + '-290': BigInteger; + '-289': BigInteger; + '-288': BigInteger; + '-287': BigInteger; + '-286': BigInteger; + '-285': BigInteger; + '-284': BigInteger; + '-283': BigInteger; + '-282': BigInteger; + '-281': BigInteger; + '-280': BigInteger; + '-279': BigInteger; + '-278': BigInteger; + '-277': BigInteger; + '-276': BigInteger; + '-275': BigInteger; + '-274': BigInteger; + '-273': BigInteger; + '-272': BigInteger; + '-271': BigInteger; + '-270': BigInteger; + '-269': BigInteger; + '-268': BigInteger; + '-267': BigInteger; + '-266': BigInteger; + '-265': BigInteger; + '-264': BigInteger; + '-263': BigInteger; + '-262': BigInteger; + '-261': BigInteger; + '-260': BigInteger; + '-259': BigInteger; + '-258': BigInteger; + '-257': BigInteger; + '-256': BigInteger; + '-255': BigInteger; + '-254': BigInteger; + '-253': BigInteger; + '-252': BigInteger; + '-251': BigInteger; + '-250': BigInteger; + '-249': BigInteger; + '-248': BigInteger; + '-247': BigInteger; + '-246': BigInteger; + '-245': BigInteger; + '-244': BigInteger; + '-243': BigInteger; + '-242': BigInteger; + '-241': BigInteger; + '-240': BigInteger; + '-239': BigInteger; + '-238': BigInteger; + '-237': BigInteger; + '-236': BigInteger; + '-235': BigInteger; + '-234': BigInteger; + '-233': BigInteger; + '-232': BigInteger; + '-231': BigInteger; + '-230': BigInteger; + '-229': BigInteger; + '-228': BigInteger; + '-227': BigInteger; + '-226': BigInteger; + '-225': BigInteger; + '-224': BigInteger; + '-223': BigInteger; + '-222': BigInteger; + '-221': BigInteger; + '-220': BigInteger; + '-219': BigInteger; + '-218': BigInteger; + '-217': BigInteger; + '-216': BigInteger; + '-215': BigInteger; + '-214': BigInteger; + '-213': BigInteger; + '-212': BigInteger; + '-211': BigInteger; + '-210': BigInteger; + '-209': BigInteger; + '-208': BigInteger; + '-207': BigInteger; + '-206': BigInteger; + '-205': BigInteger; + '-204': BigInteger; + '-203': BigInteger; + '-202': BigInteger; + '-201': BigInteger; + '-200': BigInteger; + '-199': BigInteger; + '-198': BigInteger; + '-197': BigInteger; + '-196': BigInteger; + '-195': BigInteger; + '-194': BigInteger; + '-193': BigInteger; + '-192': BigInteger; + '-191': BigInteger; + '-190': BigInteger; + '-189': BigInteger; + '-188': BigInteger; + '-187': BigInteger; + '-186': BigInteger; + '-185': BigInteger; + '-184': BigInteger; + '-183': BigInteger; + '-182': BigInteger; + '-181': BigInteger; + '-180': BigInteger; + '-179': BigInteger; + '-178': BigInteger; + '-177': BigInteger; + '-176': BigInteger; + '-175': BigInteger; + '-174': BigInteger; + '-173': BigInteger; + '-172': BigInteger; + '-171': BigInteger; + '-170': BigInteger; + '-169': BigInteger; + '-168': BigInteger; + '-167': BigInteger; + '-166': BigInteger; + '-165': BigInteger; + '-164': BigInteger; + '-163': BigInteger; + '-162': BigInteger; + '-161': BigInteger; + '-160': BigInteger; + '-159': BigInteger; + '-158': BigInteger; + '-157': BigInteger; + '-156': BigInteger; + '-155': BigInteger; + '-154': BigInteger; + '-153': BigInteger; + '-152': BigInteger; + '-151': BigInteger; + '-150': BigInteger; + '-149': BigInteger; + '-148': BigInteger; + '-147': BigInteger; + '-146': BigInteger; + '-145': BigInteger; + '-144': BigInteger; + '-143': BigInteger; + '-142': BigInteger; + '-141': BigInteger; + '-140': BigInteger; + '-139': BigInteger; + '-138': BigInteger; + '-137': BigInteger; + '-136': BigInteger; + '-135': BigInteger; + '-134': BigInteger; + '-133': BigInteger; + '-132': BigInteger; + '-131': BigInteger; + '-130': BigInteger; + '-129': BigInteger; + '-128': BigInteger; + '-127': BigInteger; + '-126': BigInteger; + '-125': BigInteger; + '-124': BigInteger; + '-123': BigInteger; + '-122': BigInteger; + '-121': BigInteger; + '-120': BigInteger; + '-119': BigInteger; + '-118': BigInteger; + '-117': BigInteger; + '-116': BigInteger; + '-115': BigInteger; + '-114': BigInteger; + '-113': BigInteger; + '-112': BigInteger; + '-111': BigInteger; + '-110': BigInteger; + '-109': BigInteger; + '-108': BigInteger; + '-107': BigInteger; + '-106': BigInteger; + '-105': BigInteger; + '-104': BigInteger; + '-103': BigInteger; + '-102': BigInteger; + '-101': BigInteger; + '-100': BigInteger; + '-99': BigInteger; + '-98': BigInteger; + '-97': BigInteger; + '-96': BigInteger; + '-95': BigInteger; + '-94': BigInteger; + '-93': BigInteger; + '-92': BigInteger; + '-91': BigInteger; + '-90': BigInteger; + '-89': BigInteger; + '-88': BigInteger; + '-87': BigInteger; + '-86': BigInteger; + '-85': BigInteger; + '-84': BigInteger; + '-83': BigInteger; + '-82': BigInteger; + '-81': BigInteger; + '-80': BigInteger; + '-79': BigInteger; + '-78': BigInteger; + '-77': BigInteger; + '-76': BigInteger; + '-75': BigInteger; + '-74': BigInteger; + '-73': BigInteger; + '-72': BigInteger; + '-71': BigInteger; + '-70': BigInteger; + '-69': BigInteger; + '-68': BigInteger; + '-67': BigInteger; + '-66': BigInteger; + '-65': BigInteger; + '-64': BigInteger; + '-63': BigInteger; + '-62': BigInteger; + '-61': BigInteger; + '-60': BigInteger; + '-59': BigInteger; + '-58': BigInteger; + '-57': BigInteger; + '-56': BigInteger; + '-55': BigInteger; + '-54': BigInteger; + '-53': BigInteger; + '-52': BigInteger; + '-51': BigInteger; + '-50': BigInteger; + '-49': BigInteger; + '-48': BigInteger; + '-47': BigInteger; + '-46': BigInteger; + '-45': BigInteger; + '-44': BigInteger; + '-43': BigInteger; + '-42': BigInteger; + '-41': BigInteger; + '-40': BigInteger; + '-39': BigInteger; + '-38': BigInteger; + '-37': BigInteger; + '-36': BigInteger; + '-35': BigInteger; + '-34': BigInteger; + '-33': BigInteger; + '-32': BigInteger; + '-31': BigInteger; + '-30': BigInteger; + '-29': BigInteger; + '-28': BigInteger; + '-27': BigInteger; + '-26': BigInteger; + '-25': BigInteger; + '-24': BigInteger; + '-23': BigInteger; + '-22': BigInteger; + '-21': BigInteger; + '-20': BigInteger; + '-19': BigInteger; + '-18': BigInteger; + '-17': BigInteger; + '-16': BigInteger; + '-15': BigInteger; + '-14': BigInteger; + '-13': BigInteger; + '-12': BigInteger; + '-11': BigInteger; + '-10': BigInteger; + '-9': BigInteger; + '-8': BigInteger; + '-7': BigInteger; + '-6': BigInteger; + '-5': BigInteger; + '-4': BigInteger; + '-3': BigInteger; + '-2': BigInteger; + '-1': BigInteger; + '0': BigInteger; + '1': BigInteger; + '2': BigInteger; + '3': BigInteger; + '4': BigInteger; + '5': BigInteger; + '6': BigInteger; + '7': BigInteger; + '8': BigInteger; + '9': BigInteger; + '10': BigInteger; + '11': BigInteger; + '12': BigInteger; + '13': BigInteger; + '14': BigInteger; + '15': BigInteger; + '16': BigInteger; + '17': BigInteger; + '18': BigInteger; + '19': BigInteger; + '20': BigInteger; + '21': BigInteger; + '22': BigInteger; + '23': BigInteger; + '24': BigInteger; + '25': BigInteger; + '26': BigInteger; + '27': BigInteger; + '28': BigInteger; + '29': BigInteger; + '30': BigInteger; + '31': BigInteger; + '32': BigInteger; + '33': BigInteger; + '34': BigInteger; + '35': BigInteger; + '36': BigInteger; + '37': BigInteger; + '38': BigInteger; + '39': BigInteger; + '40': BigInteger; + '41': BigInteger; + '42': BigInteger; + '43': BigInteger; + '44': BigInteger; + '45': BigInteger; + '46': BigInteger; + '47': BigInteger; + '48': BigInteger; + '49': BigInteger; + '50': BigInteger; + '51': BigInteger; + '52': BigInteger; + '53': BigInteger; + '54': BigInteger; + '55': BigInteger; + '56': BigInteger; + '57': BigInteger; + '58': BigInteger; + '59': BigInteger; + '60': BigInteger; + '61': BigInteger; + '62': BigInteger; + '63': BigInteger; + '64': BigInteger; + '65': BigInteger; + '66': BigInteger; + '67': BigInteger; + '68': BigInteger; + '69': BigInteger; + '70': BigInteger; + '71': BigInteger; + '72': BigInteger; + '73': BigInteger; + '74': BigInteger; + '75': BigInteger; + '76': BigInteger; + '77': BigInteger; + '78': BigInteger; + '79': BigInteger; + '80': BigInteger; + '81': BigInteger; + '82': BigInteger; + '83': BigInteger; + '84': BigInteger; + '85': BigInteger; + '86': BigInteger; + '87': BigInteger; + '88': BigInteger; + '89': BigInteger; + '90': BigInteger; + '91': BigInteger; + '92': BigInteger; + '93': BigInteger; + '94': BigInteger; + '95': BigInteger; + '96': BigInteger; + '97': BigInteger; + '98': BigInteger; + '99': BigInteger; + '100': BigInteger; + '101': BigInteger; + '102': BigInteger; + '103': BigInteger; + '104': BigInteger; + '105': BigInteger; + '106': BigInteger; + '107': BigInteger; + '108': BigInteger; + '109': BigInteger; + '110': BigInteger; + '111': BigInteger; + '112': BigInteger; + '113': BigInteger; + '114': BigInteger; + '115': BigInteger; + '116': BigInteger; + '117': BigInteger; + '118': BigInteger; + '119': BigInteger; + '120': BigInteger; + '121': BigInteger; + '122': BigInteger; + '123': BigInteger; + '124': BigInteger; + '125': BigInteger; + '126': BigInteger; + '127': BigInteger; + '128': BigInteger; + '129': BigInteger; + '130': BigInteger; + '131': BigInteger; + '132': BigInteger; + '133': BigInteger; + '134': BigInteger; + '135': BigInteger; + '136': BigInteger; + '137': BigInteger; + '138': BigInteger; + '139': BigInteger; + '140': BigInteger; + '141': BigInteger; + '142': BigInteger; + '143': BigInteger; + '144': BigInteger; + '145': BigInteger; + '146': BigInteger; + '147': BigInteger; + '148': BigInteger; + '149': BigInteger; + '150': BigInteger; + '151': BigInteger; + '152': BigInteger; + '153': BigInteger; + '154': BigInteger; + '155': BigInteger; + '156': BigInteger; + '157': BigInteger; + '158': BigInteger; + '159': BigInteger; + '160': BigInteger; + '161': BigInteger; + '162': BigInteger; + '163': BigInteger; + '164': BigInteger; + '165': BigInteger; + '166': BigInteger; + '167': BigInteger; + '168': BigInteger; + '169': BigInteger; + '170': BigInteger; + '171': BigInteger; + '172': BigInteger; + '173': BigInteger; + '174': BigInteger; + '175': BigInteger; + '176': BigInteger; + '177': BigInteger; + '178': BigInteger; + '179': BigInteger; + '180': BigInteger; + '181': BigInteger; + '182': BigInteger; + '183': BigInteger; + '184': BigInteger; + '185': BigInteger; + '186': BigInteger; + '187': BigInteger; + '188': BigInteger; + '189': BigInteger; + '190': BigInteger; + '191': BigInteger; + '192': BigInteger; + '193': BigInteger; + '194': BigInteger; + '195': BigInteger; + '196': BigInteger; + '197': BigInteger; + '198': BigInteger; + '199': BigInteger; + '200': BigInteger; + '201': BigInteger; + '202': BigInteger; + '203': BigInteger; + '204': BigInteger; + '205': BigInteger; + '206': BigInteger; + '207': BigInteger; + '208': BigInteger; + '209': BigInteger; + '210': BigInteger; + '211': BigInteger; + '212': BigInteger; + '213': BigInteger; + '214': BigInteger; + '215': BigInteger; + '216': BigInteger; + '217': BigInteger; + '218': BigInteger; + '219': BigInteger; + '220': BigInteger; + '221': BigInteger; + '222': BigInteger; + '223': BigInteger; + '224': BigInteger; + '225': BigInteger; + '226': BigInteger; + '227': BigInteger; + '228': BigInteger; + '229': BigInteger; + '230': BigInteger; + '231': BigInteger; + '232': BigInteger; + '233': BigInteger; + '234': BigInteger; + '235': BigInteger; + '236': BigInteger; + '237': BigInteger; + '238': BigInteger; + '239': BigInteger; + '240': BigInteger; + '241': BigInteger; + '242': BigInteger; + '243': BigInteger; + '244': BigInteger; + '245': BigInteger; + '246': BigInteger; + '247': BigInteger; + '248': BigInteger; + '249': BigInteger; + '250': BigInteger; + '251': BigInteger; + '252': BigInteger; + '253': BigInteger; + '254': BigInteger; + '255': BigInteger; + '256': BigInteger; + '257': BigInteger; + '258': BigInteger; + '259': BigInteger; + '260': BigInteger; + '261': BigInteger; + '262': BigInteger; + '263': BigInteger; + '264': BigInteger; + '265': BigInteger; + '266': BigInteger; + '267': BigInteger; + '268': BigInteger; + '269': BigInteger; + '270': BigInteger; + '271': BigInteger; + '272': BigInteger; + '273': BigInteger; + '274': BigInteger; + '275': BigInteger; + '276': BigInteger; + '277': BigInteger; + '278': BigInteger; + '279': BigInteger; + '280': BigInteger; + '281': BigInteger; + '282': BigInteger; + '283': BigInteger; + '284': BigInteger; + '285': BigInteger; + '286': BigInteger; + '287': BigInteger; + '288': BigInteger; + '289': BigInteger; + '290': BigInteger; + '291': BigInteger; + '292': BigInteger; + '293': BigInteger; + '294': BigInteger; + '295': BigInteger; + '296': BigInteger; + '297': BigInteger; + '298': BigInteger; + '299': BigInteger; + '300': BigInteger; + '301': BigInteger; + '302': BigInteger; + '303': BigInteger; + '304': BigInteger; + '305': BigInteger; + '306': BigInteger; + '307': BigInteger; + '308': BigInteger; + '309': BigInteger; + '310': BigInteger; + '311': BigInteger; + '312': BigInteger; + '313': BigInteger; + '314': BigInteger; + '315': BigInteger; + '316': BigInteger; + '317': BigInteger; + '318': BigInteger; + '319': BigInteger; + '320': BigInteger; + '321': BigInteger; + '322': BigInteger; + '323': BigInteger; + '324': BigInteger; + '325': BigInteger; + '326': BigInteger; + '327': BigInteger; + '328': BigInteger; + '329': BigInteger; + '330': BigInteger; + '331': BigInteger; + '332': BigInteger; + '333': BigInteger; + '334': BigInteger; + '335': BigInteger; + '336': BigInteger; + '337': BigInteger; + '338': BigInteger; + '339': BigInteger; + '340': BigInteger; + '341': BigInteger; + '342': BigInteger; + '343': BigInteger; + '344': BigInteger; + '345': BigInteger; + '346': BigInteger; + '347': BigInteger; + '348': BigInteger; + '349': BigInteger; + '350': BigInteger; + '351': BigInteger; + '352': BigInteger; + '353': BigInteger; + '354': BigInteger; + '355': BigInteger; + '356': BigInteger; + '357': BigInteger; + '358': BigInteger; + '359': BigInteger; + '360': BigInteger; + '361': BigInteger; + '362': BigInteger; + '363': BigInteger; + '364': BigInteger; + '365': BigInteger; + '366': BigInteger; + '367': BigInteger; + '368': BigInteger; + '369': BigInteger; + '370': BigInteger; + '371': BigInteger; + '372': BigInteger; + '373': BigInteger; + '374': BigInteger; + '375': BigInteger; + '376': BigInteger; + '377': BigInteger; + '378': BigInteger; + '379': BigInteger; + '380': BigInteger; + '381': BigInteger; + '382': BigInteger; + '383': BigInteger; + '384': BigInteger; + '385': BigInteger; + '386': BigInteger; + '387': BigInteger; + '388': BigInteger; + '389': BigInteger; + '390': BigInteger; + '391': BigInteger; + '392': BigInteger; + '393': BigInteger; + '394': BigInteger; + '395': BigInteger; + '396': BigInteger; + '397': BigInteger; + '398': BigInteger; + '399': BigInteger; + '400': BigInteger; + '401': BigInteger; + '402': BigInteger; + '403': BigInteger; + '404': BigInteger; + '405': BigInteger; + '406': BigInteger; + '407': BigInteger; + '408': BigInteger; + '409': BigInteger; + '410': BigInteger; + '411': BigInteger; + '412': BigInteger; + '413': BigInteger; + '414': BigInteger; + '415': BigInteger; + '416': BigInteger; + '417': BigInteger; + '418': BigInteger; + '419': BigInteger; + '420': BigInteger; + '421': BigInteger; + '422': BigInteger; + '423': BigInteger; + '424': BigInteger; + '425': BigInteger; + '426': BigInteger; + '427': BigInteger; + '428': BigInteger; + '429': BigInteger; + '430': BigInteger; + '431': BigInteger; + '432': BigInteger; + '433': BigInteger; + '434': BigInteger; + '435': BigInteger; + '436': BigInteger; + '437': BigInteger; + '438': BigInteger; + '439': BigInteger; + '440': BigInteger; + '441': BigInteger; + '442': BigInteger; + '443': BigInteger; + '444': BigInteger; + '445': BigInteger; + '446': BigInteger; + '447': BigInteger; + '448': BigInteger; + '449': BigInteger; + '450': BigInteger; + '451': BigInteger; + '452': BigInteger; + '453': BigInteger; + '454': BigInteger; + '455': BigInteger; + '456': BigInteger; + '457': BigInteger; + '458': BigInteger; + '459': BigInteger; + '460': BigInteger; + '461': BigInteger; + '462': BigInteger; + '463': BigInteger; + '464': BigInteger; + '465': BigInteger; + '466': BigInteger; + '467': BigInteger; + '468': BigInteger; + '469': BigInteger; + '470': BigInteger; + '471': BigInteger; + '472': BigInteger; + '473': BigInteger; + '474': BigInteger; + '475': BigInteger; + '476': BigInteger; + '477': BigInteger; + '478': BigInteger; + '479': BigInteger; + '480': BigInteger; + '481': BigInteger; + '482': BigInteger; + '483': BigInteger; + '484': BigInteger; + '485': BigInteger; + '486': BigInteger; + '487': BigInteger; + '488': BigInteger; + '489': BigInteger; + '490': BigInteger; + '491': BigInteger; + '492': BigInteger; + '493': BigInteger; + '494': BigInteger; + '495': BigInteger; + '496': BigInteger; + '497': BigInteger; + '498': BigInteger; + '499': BigInteger; + '500': BigInteger; + '501': BigInteger; + '502': BigInteger; + '503': BigInteger; + '504': BigInteger; + '505': BigInteger; + '506': BigInteger; + '507': BigInteger; + '508': BigInteger; + '509': BigInteger; + '510': BigInteger; + '511': BigInteger; + '512': BigInteger; + '513': BigInteger; + '514': BigInteger; + '515': BigInteger; + '516': BigInteger; + '517': BigInteger; + '518': BigInteger; + '519': BigInteger; + '520': BigInteger; + '521': BigInteger; + '522': BigInteger; + '523': BigInteger; + '524': BigInteger; + '525': BigInteger; + '526': BigInteger; + '527': BigInteger; + '528': BigInteger; + '529': BigInteger; + '530': BigInteger; + '531': BigInteger; + '532': BigInteger; + '533': BigInteger; + '534': BigInteger; + '535': BigInteger; + '536': BigInteger; + '537': BigInteger; + '538': BigInteger; + '539': BigInteger; + '540': BigInteger; + '541': BigInteger; + '542': BigInteger; + '543': BigInteger; + '544': BigInteger; + '545': BigInteger; + '546': BigInteger; + '547': BigInteger; + '548': BigInteger; + '549': BigInteger; + '550': BigInteger; + '551': BigInteger; + '552': BigInteger; + '553': BigInteger; + '554': BigInteger; + '555': BigInteger; + '556': BigInteger; + '557': BigInteger; + '558': BigInteger; + '559': BigInteger; + '560': BigInteger; + '561': BigInteger; + '562': BigInteger; + '563': BigInteger; + '564': BigInteger; + '565': BigInteger; + '566': BigInteger; + '567': BigInteger; + '568': BigInteger; + '569': BigInteger; + '570': BigInteger; + '571': BigInteger; + '572': BigInteger; + '573': BigInteger; + '574': BigInteger; + '575': BigInteger; + '576': BigInteger; + '577': BigInteger; + '578': BigInteger; + '579': BigInteger; + '580': BigInteger; + '581': BigInteger; + '582': BigInteger; + '583': BigInteger; + '584': BigInteger; + '585': BigInteger; + '586': BigInteger; + '587': BigInteger; + '588': BigInteger; + '589': BigInteger; + '590': BigInteger; + '591': BigInteger; + '592': BigInteger; + '593': BigInteger; + '594': BigInteger; + '595': BigInteger; + '596': BigInteger; + '597': BigInteger; + '598': BigInteger; + '599': BigInteger; + '600': BigInteger; + '601': BigInteger; + '602': BigInteger; + '603': BigInteger; + '604': BigInteger; + '605': BigInteger; + '606': BigInteger; + '607': BigInteger; + '608': BigInteger; + '609': BigInteger; + '610': BigInteger; + '611': BigInteger; + '612': BigInteger; + '613': BigInteger; + '614': BigInteger; + '615': BigInteger; + '616': BigInteger; + '617': BigInteger; + '618': BigInteger; + '619': BigInteger; + '620': BigInteger; + '621': BigInteger; + '622': BigInteger; + '623': BigInteger; + '624': BigInteger; + '625': BigInteger; + '626': BigInteger; + '627': BigInteger; + '628': BigInteger; + '629': BigInteger; + '630': BigInteger; + '631': BigInteger; + '632': BigInteger; + '633': BigInteger; + '634': BigInteger; + '635': BigInteger; + '636': BigInteger; + '637': BigInteger; + '638': BigInteger; + '639': BigInteger; + '640': BigInteger; + '641': BigInteger; + '642': BigInteger; + '643': BigInteger; + '644': BigInteger; + '645': BigInteger; + '646': BigInteger; + '647': BigInteger; + '648': BigInteger; + '649': BigInteger; + '650': BigInteger; + '651': BigInteger; + '652': BigInteger; + '653': BigInteger; + '654': BigInteger; + '655': BigInteger; + '656': BigInteger; + '657': BigInteger; + '658': BigInteger; + '659': BigInteger; + '660': BigInteger; + '661': BigInteger; + '662': BigInteger; + '663': BigInteger; + '664': BigInteger; + '665': BigInteger; + '666': BigInteger; + '667': BigInteger; + '668': BigInteger; + '669': BigInteger; + '670': BigInteger; + '671': BigInteger; + '672': BigInteger; + '673': BigInteger; + '674': BigInteger; + '675': BigInteger; + '676': BigInteger; + '677': BigInteger; + '678': BigInteger; + '679': BigInteger; + '680': BigInteger; + '681': BigInteger; + '682': BigInteger; + '683': BigInteger; + '684': BigInteger; + '685': BigInteger; + '686': BigInteger; + '687': BigInteger; + '688': BigInteger; + '689': BigInteger; + '690': BigInteger; + '691': BigInteger; + '692': BigInteger; + '693': BigInteger; + '694': BigInteger; + '695': BigInteger; + '696': BigInteger; + '697': BigInteger; + '698': BigInteger; + '699': BigInteger; + '700': BigInteger; + '701': BigInteger; + '702': BigInteger; + '703': BigInteger; + '704': BigInteger; + '705': BigInteger; + '706': BigInteger; + '707': BigInteger; + '708': BigInteger; + '709': BigInteger; + '710': BigInteger; + '711': BigInteger; + '712': BigInteger; + '713': BigInteger; + '714': BigInteger; + '715': BigInteger; + '716': BigInteger; + '717': BigInteger; + '718': BigInteger; + '719': BigInteger; + '720': BigInteger; + '721': BigInteger; + '722': BigInteger; + '723': BigInteger; + '724': BigInteger; + '725': BigInteger; + '726': BigInteger; + '727': BigInteger; + '728': BigInteger; + '729': BigInteger; + '730': BigInteger; + '731': BigInteger; + '732': BigInteger; + '733': BigInteger; + '734': BigInteger; + '735': BigInteger; + '736': BigInteger; + '737': BigInteger; + '738': BigInteger; + '739': BigInteger; + '740': BigInteger; + '741': BigInteger; + '742': BigInteger; + '743': BigInteger; + '744': BigInteger; + '745': BigInteger; + '746': BigInteger; + '747': BigInteger; + '748': BigInteger; + '749': BigInteger; + '750': BigInteger; + '751': BigInteger; + '752': BigInteger; + '753': BigInteger; + '754': BigInteger; + '755': BigInteger; + '756': BigInteger; + '757': BigInteger; + '758': BigInteger; + '759': BigInteger; + '760': BigInteger; + '761': BigInteger; + '762': BigInteger; + '763': BigInteger; + '764': BigInteger; + '765': BigInteger; + '766': BigInteger; + '767': BigInteger; + '768': BigInteger; + '769': BigInteger; + '770': BigInteger; + '771': BigInteger; + '772': BigInteger; + '773': BigInteger; + '774': BigInteger; + '775': BigInteger; + '776': BigInteger; + '777': BigInteger; + '778': BigInteger; + '779': BigInteger; + '780': BigInteger; + '781': BigInteger; + '782': BigInteger; + '783': BigInteger; + '784': BigInteger; + '785': BigInteger; + '786': BigInteger; + '787': BigInteger; + '788': BigInteger; + '789': BigInteger; + '790': BigInteger; + '791': BigInteger; + '792': BigInteger; + '793': BigInteger; + '794': BigInteger; + '795': BigInteger; + '796': BigInteger; + '797': BigInteger; + '798': BigInteger; + '799': BigInteger; + '800': BigInteger; + '801': BigInteger; + '802': BigInteger; + '803': BigInteger; + '804': BigInteger; + '805': BigInteger; + '806': BigInteger; + '807': BigInteger; + '808': BigInteger; + '809': BigInteger; + '810': BigInteger; + '811': BigInteger; + '812': BigInteger; + '813': BigInteger; + '814': BigInteger; + '815': BigInteger; + '816': BigInteger; + '817': BigInteger; + '818': BigInteger; + '819': BigInteger; + '820': BigInteger; + '821': BigInteger; + '822': BigInteger; + '823': BigInteger; + '824': BigInteger; + '825': BigInteger; + '826': BigInteger; + '827': BigInteger; + '828': BigInteger; + '829': BigInteger; + '830': BigInteger; + '831': BigInteger; + '832': BigInteger; + '833': BigInteger; + '834': BigInteger; + '835': BigInteger; + '836': BigInteger; + '837': BigInteger; + '838': BigInteger; + '839': BigInteger; + '840': BigInteger; + '841': BigInteger; + '842': BigInteger; + '843': BigInteger; + '844': BigInteger; + '845': BigInteger; + '846': BigInteger; + '847': BigInteger; + '848': BigInteger; + '849': BigInteger; + '850': BigInteger; + '851': BigInteger; + '852': BigInteger; + '853': BigInteger; + '854': BigInteger; + '855': BigInteger; + '856': BigInteger; + '857': BigInteger; + '858': BigInteger; + '859': BigInteger; + '860': BigInteger; + '861': BigInteger; + '862': BigInteger; + '863': BigInteger; + '864': BigInteger; + '865': BigInteger; + '866': BigInteger; + '867': BigInteger; + '868': BigInteger; + '869': BigInteger; + '870': BigInteger; + '871': BigInteger; + '872': BigInteger; + '873': BigInteger; + '874': BigInteger; + '875': BigInteger; + '876': BigInteger; + '877': BigInteger; + '878': BigInteger; + '879': BigInteger; + '880': BigInteger; + '881': BigInteger; + '882': BigInteger; + '883': BigInteger; + '884': BigInteger; + '885': BigInteger; + '886': BigInteger; + '887': BigInteger; + '888': BigInteger; + '889': BigInteger; + '890': BigInteger; + '891': BigInteger; + '892': BigInteger; + '893': BigInteger; + '894': BigInteger; + '895': BigInteger; + '896': BigInteger; + '897': BigInteger; + '898': BigInteger; + '899': BigInteger; + '900': BigInteger; + '901': BigInteger; + '902': BigInteger; + '903': BigInteger; + '904': BigInteger; + '905': BigInteger; + '906': BigInteger; + '907': BigInteger; + '908': BigInteger; + '909': BigInteger; + '910': BigInteger; + '911': BigInteger; + '912': BigInteger; + '913': BigInteger; + '914': BigInteger; + '915': BigInteger; + '916': BigInteger; + '917': BigInteger; + '918': BigInteger; + '919': BigInteger; + '920': BigInteger; + '921': BigInteger; + '922': BigInteger; + '923': BigInteger; + '924': BigInteger; + '925': BigInteger; + '926': BigInteger; + '927': BigInteger; + '928': BigInteger; + '929': BigInteger; + '930': BigInteger; + '931': BigInteger; + '932': BigInteger; + '933': BigInteger; + '934': BigInteger; + '935': BigInteger; + '936': BigInteger; + '937': BigInteger; + '938': BigInteger; + '939': BigInteger; + '940': BigInteger; + '941': BigInteger; + '942': BigInteger; + '943': BigInteger; + '944': BigInteger; + '945': BigInteger; + '946': BigInteger; + '947': BigInteger; + '948': BigInteger; + '949': BigInteger; + '950': BigInteger; + '951': BigInteger; + '952': BigInteger; + '953': BigInteger; + '954': BigInteger; + '955': BigInteger; + '956': BigInteger; + '957': BigInteger; + '958': BigInteger; + '959': BigInteger; + '960': BigInteger; + '961': BigInteger; + '962': BigInteger; + '963': BigInteger; + '964': BigInteger; + '965': BigInteger; + '966': BigInteger; + '967': BigInteger; + '968': BigInteger; + '969': BigInteger; + '970': BigInteger; + '971': BigInteger; + '972': BigInteger; + '973': BigInteger; + '974': BigInteger; + '975': BigInteger; + '976': BigInteger; + '977': BigInteger; + '978': BigInteger; + '979': BigInteger; + '980': BigInteger; + '981': BigInteger; + '982': BigInteger; + '983': BigInteger; + '984': BigInteger; + '985': BigInteger; + '986': BigInteger; + '987': BigInteger; + '988': BigInteger; + '989': BigInteger; + '990': BigInteger; + '991': BigInteger; + '992': BigInteger; + '993': BigInteger; + '994': BigInteger; + '995': BigInteger; + '996': BigInteger; + '997': BigInteger; + '998': BigInteger; + '999': BigInteger; + } + + interface BaseArray { + value: number[], + isNegative: boolean + } +} diff --git a/node_modules/big-integer/BigInteger.js b/node_modules/big-integer/BigInteger.js new file mode 100644 index 0000000..c4263d5 --- /dev/null +++ b/node_modules/big-integer/BigInteger.js @@ -0,0 +1,1453 @@ +var bigInt = (function (undefined) { + "use strict"; + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + } + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + } + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + } + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + } + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + } + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + } + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + } + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + } + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + } + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + } + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + } + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + } + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + } + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, t, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined) return isPrime; + var n = this.abs(); + var t = iterations === undefined ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + } + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + } + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + } + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix !== 10) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined) radix = 10; + if (radix != 10) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + } + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; +})(); + +// Node.js check +if (typeof module !== "undefined" && module.hasOwnProperty("exports")) { + module.exports = bigInt; +} + +//amd check +if (typeof define === "function" && define.amd) { + define( function () { + return bigInt; + }); +} diff --git a/node_modules/big-integer/BigInteger.min.js b/node_modules/big-integer/BigInteger.min.js new file mode 100644 index 0000000..0070667 --- /dev/null +++ b/node_modules/big-integer/BigInteger.min.js @@ -0,0 +1 @@ +var bigInt=function(t){"use strict";var e=1e7,r=9007199254740992,o=f(r),n="0123456789abcdefghijklmnopqrstuvwxyz",i="function"==typeof BigInt;function u(t,e,r,o){return void 0===t?u[0]:void 0!==e&&(10!=+e||r)?_(t,e,r,o):K(t)}function p(t,e){this.value=t,this.sign=e,this.isSmall=!1}function a(t){this.value=t,this.sign=t<0,this.isSmall=!0}function s(t){this.value=t}function l(t){return-r0?Math.floor(t):Math.ceil(t)}function c(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(n=0;n=s?1:0,p[n]=o-a*s;for(;n0&&p.push(a),p}function m(t,e){return t.length>=e.length?c(t,e):c(e,t)}function d(t,r){var o,n,i=t.length,u=new Array(i),p=e;for(n=0;n0;)u[n++]=r%p,r=Math.floor(r/p);return u}function b(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(o=0;o0;)u[n++]=a%p,a=Math.floor(a/p);return u}function q(t,e){for(var r=[];e-- >0;)r.push(0);return r.concat(t)}function M(t,e){var r=Math.max(t.length,e.length);if(r<=30)return S(t,e);r=Math.ceil(r/2);var o=t.slice(r),n=t.slice(0,r),i=e.slice(r),u=e.slice(0,r),p=M(n,u),a=M(o,i),s=M(m(n,o),m(u,i)),l=m(m(p,q(b(b(s,p),a),r)),q(a,2*r));return h(l),l}function N(t,r,o){return new p(t=0;--r)n=(i=1e7*n+t[r])-(o=g(i/e))*e,p[r]=0|o;return[p,0|n]}function B(t,r){var o,n=K(r);if(i)return[new s(t.value/n.value),new s(t.value%n.value)];var l,c=t.value,m=n.value;if(0===m)throw new Error("Cannot divide by zero");if(t.isSmall)return n.isSmall?[new a(g(c/m)),new a(c%m)]:[u[0],t];if(n.isSmall){if(1===m)return[t,u[0]];if(-1==m)return[t.negate(),u[0]];var d=Math.abs(m);if(d=0;n--){for(o=h-1,d[n+f]!==c&&(o=Math.floor((d[n+f]*h+d[n+f-1])/c)),i=0,u=0,a=b.length,p=0;ps&&(i=(i+1)*y),o=Math.ceil(i/u);do{if(A(p=I(r,o),f)<=0)break;o--}while(o);l.push(o),f=b(f,p)}return l.reverse(),[v(l),v(f)]}(c,m),l=o[0];var q=t.sign!==n.sign,M=o[1],N=t.sign;return"number"==typeof l?(q&&(l=-l),l=new a(l)):l=new p(l,q),"number"==typeof M?(N&&(M=-M),M=new a(M)):M=new p(M,N),[l,M]}function A(t,e){if(t.length!==e.length)return t.length>e.length?1:-1;for(var r=t.length-1;r>=0;r--)if(t[r]!==e[r])return t[r]>e[r]?1:-1;return 0}function P(t){var e=t.abs();return!e.isUnit()&&(!!(e.equals(2)||e.equals(3)||e.equals(5))||!(e.isEven()||e.isDivisibleBy(3)||e.isDivisibleBy(5))&&(!!e.lesser(49)||void 0))}function Z(t,e){for(var r,o,n,i=t.prev(),u=i,p=0;u.isEven();)u=u.divide(2),p++;t:for(o=0;o=0?o=b(t,e):(o=b(e,t),r=!r),"number"==typeof(o=v(o))?(r&&(o=-o),new a(o)):new p(o,r)}(r,o,this.sign)},p.prototype.minus=p.prototype.subtract,a.prototype.subtract=function(t){var e=K(t),r=this.value;if(r<0!==e.sign)return this.add(e.negate());var o=e.value;return e.isSmall?new a(r-o):w(o,Math.abs(r),r>=0)},a.prototype.minus=a.prototype.subtract,s.prototype.subtract=function(t){return new s(this.value-K(t).value)},s.prototype.minus=s.prototype.subtract,p.prototype.negate=function(){return new p(this.value,!this.sign)},a.prototype.negate=function(){var t=this.sign,e=new a(-this.value);return e.sign=!t,e},s.prototype.negate=function(){return new s(-this.value)},p.prototype.abs=function(){return new p(this.value,!1)},a.prototype.abs=function(){return new a(Math.abs(this.value))},s.prototype.abs=function(){return new s(this.value>=0?this.value:-this.value)},p.prototype.multiply=function(t){var r,o,n,i=K(t),a=this.value,s=i.value,l=this.sign!==i.sign;if(i.isSmall){if(0===s)return u[0];if(1===s)return this;if(-1===s)return this.negate();if((r=Math.abs(s))0?M(a,s):S(a,s),l)},p.prototype.times=p.prototype.multiply,a.prototype._multiplyBySmall=function(t){return l(t.value*this.value)?new a(t.value*this.value):N(Math.abs(t.value),f(Math.abs(this.value)),this.sign!==t.sign)},p.prototype._multiplyBySmall=function(t){return 0===t.value?u[0]:1===t.value?this:-1===t.value?this.negate():N(Math.abs(t.value),this.value,this.sign!==t.sign)},a.prototype.multiply=function(t){return K(t)._multiplyBySmall(this)},a.prototype.times=a.prototype.multiply,s.prototype.multiply=function(t){return new s(this.value*K(t).value)},s.prototype.times=s.prototype.multiply,p.prototype.square=function(){return new p(E(this.value),!1)},a.prototype.square=function(){var t=this.value*this.value;return l(t)?new a(t):new p(E(f(Math.abs(this.value))),!1)},s.prototype.square=function(t){return new s(this.value*this.value)},p.prototype.divmod=function(t){var e=B(this,t);return{quotient:e[0],remainder:e[1]}},s.prototype.divmod=a.prototype.divmod=p.prototype.divmod,p.prototype.divide=function(t){return B(this,t)[0]},s.prototype.over=s.prototype.divide=function(t){return new s(this.value/K(t).value)},a.prototype.over=a.prototype.divide=p.prototype.over=p.prototype.divide,p.prototype.mod=function(t){return B(this,t)[1]},s.prototype.mod=s.prototype.remainder=function(t){return new s(this.value%K(t).value)},a.prototype.remainder=a.prototype.mod=p.prototype.remainder=p.prototype.mod,p.prototype.pow=function(t){var e,r,o,n=K(t),i=this.value,p=n.value;if(0===p)return u[1];if(0===i)return u[0];if(1===i)return u[1];if(-1===i)return n.isEven()?u[1]:u[-1];if(n.sign)return u[0];if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall&&l(e=Math.pow(i,p)))return new a(g(e));for(r=this,o=u[1];!0&p&&(o=o.times(r),--p),0!==p;)p/=2,r=r.square();return o},a.prototype.pow=p.prototype.pow,s.prototype.pow=function(t){var e=K(t),r=this.value,o=e.value,n=BigInt(0),i=BigInt(1),p=BigInt(2);if(o===n)return u[1];if(r===n)return u[0];if(r===i)return u[1];if(r===BigInt(-1))return e.isEven()?u[1]:u[-1];if(e.isNegative())return new s(n);for(var a=this,l=u[1];(o&i)===i&&(l=l.times(a),--o),o!==n;)o/=p,a=a.square();return l},p.prototype.modPow=function(t,e){if(t=K(t),(e=K(e)).isZero())throw new Error("Cannot take modPow with modulus 0");var r=u[1],o=this.mod(e);for(t.isNegative()&&(t=t.multiply(u[-1]),o=o.modInv(e));t.isPositive();){if(o.isZero())return u[0];t.isOdd()&&(r=r.multiply(o).mod(e)),t=t.divide(2),o=o.square().mod(e)}return r},s.prototype.modPow=a.prototype.modPow=p.prototype.modPow,p.prototype.compareAbs=function(t){var e=K(t),r=this.value,o=e.value;return e.isSmall?1:A(r,o)},a.prototype.compareAbs=function(t){var e=K(t),r=Math.abs(this.value),o=e.value;return e.isSmall?r===(o=Math.abs(o))?0:r>o?1:-1:-1},s.prototype.compareAbs=function(t){var e=this.value,r=K(t).value;return(e=e>=0?e:-e)===(r=r>=0?r:-r)?0:e>r?1:-1},p.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=K(t),r=this.value,o=e.value;return this.sign!==e.sign?e.sign?1:-1:e.isSmall?this.sign?-1:1:A(r,o)*(this.sign?-1:1)},p.prototype.compareTo=p.prototype.compare,a.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=K(t),r=this.value,o=e.value;return e.isSmall?r==o?0:r>o?1:-1:r<0!==e.sign?r<0?-1:1:r<0?1:-1},a.prototype.compareTo=a.prototype.compare,s.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=this.value,r=K(t).value;return e===r?0:e>r?1:-1},s.prototype.compareTo=s.prototype.compare,p.prototype.equals=function(t){return 0===this.compare(t)},s.prototype.eq=s.prototype.equals=a.prototype.eq=a.prototype.equals=p.prototype.eq=p.prototype.equals,p.prototype.notEquals=function(t){return 0!==this.compare(t)},s.prototype.neq=s.prototype.notEquals=a.prototype.neq=a.prototype.notEquals=p.prototype.neq=p.prototype.notEquals,p.prototype.greater=function(t){return this.compare(t)>0},s.prototype.gt=s.prototype.greater=a.prototype.gt=a.prototype.greater=p.prototype.gt=p.prototype.greater,p.prototype.lesser=function(t){return this.compare(t)<0},s.prototype.lt=s.prototype.lesser=a.prototype.lt=a.prototype.lesser=p.prototype.lt=p.prototype.lesser,p.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},s.prototype.geq=s.prototype.greaterOrEquals=a.prototype.geq=a.prototype.greaterOrEquals=p.prototype.geq=p.prototype.greaterOrEquals,p.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},s.prototype.leq=s.prototype.lesserOrEquals=a.prototype.leq=a.prototype.lesserOrEquals=p.prototype.leq=p.prototype.lesserOrEquals,p.prototype.isEven=function(){return 0==(1&this.value[0])},a.prototype.isEven=function(){return 0==(1&this.value)},s.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},p.prototype.isOdd=function(){return 1==(1&this.value[0])},a.prototype.isOdd=function(){return 1==(1&this.value)},s.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},p.prototype.isPositive=function(){return!this.sign},a.prototype.isPositive=function(){return this.value>0},s.prototype.isPositive=a.prototype.isPositive,p.prototype.isNegative=function(){return this.sign},a.prototype.isNegative=function(){return this.value<0},s.prototype.isNegative=a.prototype.isNegative,p.prototype.isUnit=function(){return!1},a.prototype.isUnit=function(){return 1===Math.abs(this.value)},s.prototype.isUnit=function(){return this.abs().value===BigInt(1)},p.prototype.isZero=function(){return!1},a.prototype.isZero=function(){return 0===this.value},s.prototype.isZero=function(){return this.value===BigInt(0)},p.prototype.isDivisibleBy=function(t){var e=K(t);return!e.isZero()&&(!!e.isUnit()||(0===e.compareAbs(2)?this.isEven():this.mod(e).isZero()))},s.prototype.isDivisibleBy=a.prototype.isDivisibleBy=p.prototype.isDivisibleBy,p.prototype.isPrime=function(e){var r=P(this);if(r!==t)return r;var o=this.abs(),n=o.bitLength();if(n<=64)return Z(o,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var i=Math.log(2)*n.toJSNumber(),u=Math.ceil(!0===e?2*Math.pow(i,2):i),p=[],a=0;a-r?new a(t-1):new p(o,!0)},s.prototype.prev=function(){return new s(this.value-BigInt(1))};for(var x=[1];2*x[x.length-1]<=e;)x.push(2*x[x.length-1]);var J=x.length,L=x[J-1];function U(t){return Math.abs(t)<=e}function T(t,e,r){e=K(e);for(var o=t.isNegative(),n=e.isNegative(),i=o?t.not():t,u=n?e.not():e,p=0,a=0,s=null,l=null,f=[];!i.isZero()||!u.isZero();)p=(s=B(i,L))[1].toJSNumber(),o&&(p=L-1-p),a=(l=B(u,L))[1].toJSNumber(),n&&(a=L-1-a),i=s[0],u=l[0],f.push(r(p,a));for(var v=0!==r(o?1:0,n?1:0)?bigInt(-1):bigInt(0),h=f.length-1;h>=0;h-=1)v=v.multiply(L).add(bigInt(f[h]));return v}p.prototype.shiftLeft=function(t){var e=K(t).toJSNumber();if(!U(e))throw new Error(String(e)+" is too large for shifting.");if(e<0)return this.shiftRight(-e);var r=this;if(r.isZero())return r;for(;e>=J;)r=r.multiply(L),e-=J-1;return r.multiply(x[e])},s.prototype.shiftLeft=a.prototype.shiftLeft=p.prototype.shiftLeft,p.prototype.shiftRight=function(t){var e,r=K(t).toJSNumber();if(!U(r))throw new Error(String(r)+" is too large for shifting.");if(r<0)return this.shiftLeft(-r);for(var o=this;r>=J;){if(o.isZero()||o.isNegative()&&o.isUnit())return o;o=(e=B(o,L))[1].isNegative()?e[0].prev():e[0],r-=J-1}return(e=B(o,x[r]))[1].isNegative()?e[0].prev():e[0]},s.prototype.shiftRight=a.prototype.shiftRight=p.prototype.shiftRight,p.prototype.not=function(){return this.negate().prev()},s.prototype.not=a.prototype.not=p.prototype.not,p.prototype.and=function(t){return T(this,t,(function(t,e){return t&e}))},s.prototype.and=a.prototype.and=p.prototype.and,p.prototype.or=function(t){return T(this,t,(function(t,e){return t|e}))},s.prototype.or=a.prototype.or=p.prototype.or,p.prototype.xor=function(t){return T(this,t,(function(t,e){return t^e}))},s.prototype.xor=a.prototype.xor=p.prototype.xor;var j=1<<30;function C(t){var r=t.value,o="number"==typeof r?r|j:"bigint"==typeof r?r|BigInt(j):r[0]+r[1]*e|1073758208;return o&-o}function D(t,e){if(e.compareTo(t)<=0){var r=D(t,e.square(e)),o=r.p,n=r.e,i=o.multiply(e);return i.compareTo(t)<=0?{p:i,e:2*n+1}:{p:o,e:2*n}}return{p:bigInt(1),e:0}}function z(t,e){return t=K(t),e=K(e),t.greater(e)?t:e}function R(t,e){return t=K(t),e=K(e),t.lesser(e)?t:e}function k(t,e){if(t=K(t).abs(),e=K(e).abs(),t.equals(e))return t;if(t.isZero())return e;if(e.isZero())return t;for(var r,o,n=u[1];t.isEven()&&e.isEven();)r=R(C(t),C(e)),t=t.divide(r),e=e.divide(r),n=n.multiply(r);for(;t.isEven();)t=t.divide(C(t));do{for(;e.isEven();)e=e.divide(C(e));t.greater(e)&&(o=e,e=t,t=o),e=e.subtract(t)}while(!e.isZero());return n.isUnit()?t:t.multiply(n)}p.prototype.bitLength=function(){var t=this;return t.compareTo(bigInt(0))<0&&(t=t.negate().subtract(bigInt(1))),0===t.compareTo(bigInt(0))?bigInt(0):bigInt(D(t,bigInt(2)).e).add(bigInt(1))},s.prototype.bitLength=a.prototype.bitLength=p.prototype.bitLength;var _=function(t,e,r,o){r=r||n,t=String(t),o||(t=t.toLowerCase(),r=r.toLowerCase());var i,u=t.length,p=Math.abs(e),a={};for(i=0;i=p)){if("1"===f&&1===p)continue;throw new Error(f+" is not a valid digit in base "+e+".")}}e=K(e);var s=[],l="-"===t[0];for(i=l?1:0;i"!==t[i]&&i=0;o--)n=n.add(t[o].times(i)),i=i.times(e);return r?n.negate():n}function F(t,e){if((e=bigInt(e)).isZero()){if(t.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(e.equals(-1)){if(t.isZero())return{value:[0],isNegative:!1};if(t.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-t.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var r=Array.apply(null,Array(t.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return r.unshift([1]),{value:[].concat.apply([],r),isNegative:!1}}var o=!1;if(t.isNegative()&&e.isPositive()&&(o=!0,t=t.abs()),e.isUnit())return t.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(t.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:o};for(var n,i=[],u=t;u.isNegative()||u.compareAbs(e)>=0;){n=u.divmod(e),u=n.quotient;var p=n.remainder;p.isNegative()&&(p=e.minus(p).abs(),u=u.next()),i.push(p.toJSNumber())}return i.push(u.toJSNumber()),{value:i.reverse(),isNegative:o}}function G(t,e,r){var o=F(t,e);return(o.isNegative?"-":"")+o.value.map((function(t){return function(t,e){return t<(e=e||n).length?e[t]:"<"+t+">"}(t,r)})).join("")}function H(t){if(l(+t)){var e=+t;if(e===g(e))return i?new s(BigInt(e)):new a(e);throw new Error("Invalid integer: "+t)}var r="-"===t[0];r&&(t=t.slice(1));var o=t.split(/e/i);if(o.length>2)throw new Error("Invalid integer: "+o.join("e"));if(2===o.length){var n=o[1];if("+"===n[0]&&(n=n.slice(1)),(n=+n)!==g(n)||!l(n))throw new Error("Invalid integer: "+n+" is not a valid exponent.");var u=o[0],f=u.indexOf(".");if(f>=0&&(n-=u.length-f-1,u=u.slice(0,f)+u.slice(f+1)),n<0)throw new Error("Cannot include negative exponent part for integers");t=u+=new Array(n+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);if(i)return new s(BigInt(r?"-"+t:t));for(var v=[],y=t.length,c=y-7;y>0;)v.push(+t.slice(c,y)),(c-=7)<0&&(c=0),y-=7;return h(v),new p(v,r)}function K(t){return"number"==typeof t?function(t){if(i)return new s(BigInt(t));if(l(t)){if(t!==g(t))throw new Error(t+" is not an integer.");return new a(t)}return H(t.toString())}(t):"string"==typeof t?H(t):"bigint"==typeof t?new s(t):t}p.prototype.toArray=function(t){return F(this,t)},a.prototype.toArray=function(t){return F(this,t)},s.prototype.toArray=function(t){return F(this,t)},p.prototype.toString=function(e,r){if(e===t&&(e=10),10!==e)return G(this,e,r);for(var o,n=this.value,i=n.length,u=String(n[--i]);--i>=0;)o=String(n[i]),u+="0000000".slice(o.length)+o;return(this.sign?"-":"")+u},a.prototype.toString=function(e,r){return e===t&&(e=10),10!=e?G(this,e,r):String(this.value)},s.prototype.toString=a.prototype.toString,s.prototype.toJSON=p.prototype.toJSON=a.prototype.toJSON=function(){return this.toString()},p.prototype.valueOf=function(){return parseInt(this.toString(),10)},p.prototype.toJSNumber=p.prototype.valueOf,a.prototype.valueOf=function(){return this.value},a.prototype.toJSNumber=a.prototype.valueOf,s.prototype.valueOf=s.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var Q=0;Q<1e3;Q++)u[Q]=K(Q),Q>0&&(u[-Q]=K(-Q));return u.one=u[1],u.zero=u[0],u.minusOne=u[-1],u.max=z,u.min=R,u.gcd=k,u.lcm=function(t,e){return t=K(t).abs(),e=K(e).abs(),t.divide(k(t,e)).multiply(e)},u.isInstance=function(t){return t instanceof p||t instanceof a||t instanceof s},u.randBetween=function(t,r,o){t=K(t),r=K(r);var n=o||Math.random,i=R(t,r),p=z(t,r).subtract(i).add(1);if(p.isSmall)return i.add(Math.floor(n()*p));for(var a=F(p,e).value,s=[],l=!0,f=0;f diff --git a/node_modules/big-integer/README.md b/node_modules/big-integer/README.md new file mode 100644 index 0000000..42a6cd4 --- /dev/null +++ b/node_modules/big-integer/README.md @@ -0,0 +1,589 @@ +# BigInteger.js [![Build Status][travis-img]][travis-url] [![Coverage Status][coveralls-img]][coveralls-url] [![Monthly Downloads][downloads-img]][downloads-url] + +[travis-url]: https://travis-ci.org/peterolson/BigInteger.js +[travis-img]: https://travis-ci.org/peterolson/BigInteger.js.svg?branch=master +[coveralls-url]: https://coveralls.io/github/peterolson/BigInteger.js?branch=master +[coveralls-img]: https://coveralls.io/repos/peterolson/BigInteger.js/badge.svg?branch=master&service=github +[downloads-url]: https://www.npmjs.com/package/big-integer +[downloads-img]: https://img.shields.io/npm/dm/big-integer.svg + +**BigInteger.js** is an arbitrary-length integer library for Javascript, allowing arithmetic operations on integers of unlimited size, notwithstanding memory and time limitations. + +**Update (December 2, 2018):** [`BigInt` is being added as a native feature of JavaScript](https://tc39.github.io/proposal-bigint/). This library now works as a polyfill: if the environment supports the native `BigInt`, this library acts as a thin wrapper over the native implementation. + +## Installation + +If you are using a browser, you can download [BigInteger.js from GitHub](http://peterolson.github.com/BigInteger.js/BigInteger.min.js) or just hotlink to it: + + + +If you are using node, you can install BigInteger with [npm](https://npmjs.org/). + + npm install big-integer + +Then you can include it in your code: + + var bigInt = require("big-integer"); + + +## Usage +### `bigInt(number, [base], [alphabet], [caseSensitive])` + +You can create a bigInt by calling the `bigInt` function. You can pass in + + - a string, which it will parse as an bigInt and throw an `"Invalid integer"` error if the parsing fails. + - a Javascript number, which it will parse as an bigInt and throw an `"Invalid integer"` error if the parsing fails. + - another bigInt. + - nothing, and it will return `bigInt.zero`. + + If you provide a second parameter, then it will parse `number` as a number in base `base`. Note that `base` can be any bigInt (even negative or zero). The letters "a-z" and "A-Z" will be interpreted as the numbers 10 to 35. Higher digits can be specified in angle brackets (`<` and `>`). The default `base` is `10`. + + You can specify a custom alphabet for base conversion with the third parameter. The default `alphabet` is `"0123456789abcdefghijklmnopqrstuvwxyz"`. + + The fourth parameter specifies whether or not the number string should be case-sensitive, i.e. whether `a` and `A` should be treated as different digits. By default `caseSensitive` is `false`. + +Examples: + + var zero = bigInt(); + var ninetyThree = bigInt(93); + var largeNumber = bigInt("75643564363473453456342378564387956906736546456235345"); + var googol = bigInt("1e100"); + var bigNumber = bigInt(largeNumber); + + var maximumByte = bigInt("FF", 16); + var fiftyFiveGoogol = bigInt("<55>0", googol); + +Note that Javascript numbers larger than `9007199254740992` and smaller than `-9007199254740992` are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings. + +### Method Chaining + +Note that bigInt operations return bigInts, which allows you to chain methods, for example: + + var salary = bigInt(dollarsPerHour).times(hoursWorked).plus(randomBonuses) + +### Constants + +There are three named constants already stored that you do not have to construct with the `bigInt` function yourself: + + - `bigInt.one`, equivalent to `bigInt(1)` + - `bigInt.zero`, equivalent to `bigInt(0)` + - `bigInt.minusOne`, equivalent to `bigInt(-1)` + +The numbers from -999 to 999 are also already prestored and can be accessed using `bigInt[index]`, for example: + + - `bigInt[-999]`, equivalent to `bigInt(-999)` + - `bigInt[256]`, equivalent to `bigInt(256)` + +### Methods + +#### `abs()` + +Returns the absolute value of a bigInt. + + - `bigInt(-45).abs()` => `45` + - `bigInt(45).abs()` => `45` + +#### `add(number)` + +Performs addition. + + - `bigInt(5).add(7)` => `12` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Addition) + +#### `and(number)` + +Performs the bitwise AND operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement). + + - `bigInt(6).and(3)` => `2` + - `bigInt(6).and(-3)` => `4` + +#### `bitLength()` + +Returns the number of digits required to represent a bigInt in binary. + + - `bigInt(5)` => `3` (since 5 is `101` in binary, which is three digits long) + +#### `compare(number)` + +Performs a comparison between two numbers. If the numbers are equal, it returns `0`. If the first number is greater, it returns `1`. If the first number is lesser, it returns `-1`. + + - `bigInt(5).compare(5)` => `0` + - `bigInt(5).compare(4)` => `1` + - `bigInt(4).compare(5)` => `-1` + +#### `compareAbs(number)` + +Performs a comparison between the absolute value of two numbers. + + - `bigInt(5).compareAbs(-5)` => `0` + - `bigInt(5).compareAbs(4)` => `1` + - `bigInt(4).compareAbs(-5)` => `-1` + +#### `compareTo(number)` + +Alias for the `compare` method. + +#### `divide(number)` + +Performs integer division, disregarding the remainder. + + - `bigInt(59).divide(5)` => `11` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division) + +#### `divmod(number)` + +Performs division and returns an object with two properties: `quotient` and `remainder`. The sign of the remainder will match the sign of the dividend. + + - `bigInt(59).divmod(5)` => `{quotient: bigInt(11), remainder: bigInt(4) }` + - `bigInt(-5).divmod(2)` => `{quotient: bigInt(-2), remainder: bigInt(-1) }` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division) + +#### `eq(number)` + +Alias for the `equals` method. + +#### `equals(number)` + +Checks if two numbers are equal. + + - `bigInt(5).equals(5)` => `true` + - `bigInt(4).equals(7)` => `false` + +#### `geq(number)` + +Alias for the `greaterOrEquals` method. + + +#### `greater(number)` + +Checks if the first number is greater than the second. + + - `bigInt(5).greater(6)` => `false` + - `bigInt(5).greater(5)` => `false` + - `bigInt(5).greater(4)` => `true` + +#### `greaterOrEquals(number)` + +Checks if the first number is greater than or equal to the second. + + - `bigInt(5).greaterOrEquals(6)` => `false` + - `bigInt(5).greaterOrEquals(5)` => `true` + - `bigInt(5).greaterOrEquals(4)` => `true` + +#### `gt(number)` + +Alias for the `greater` method. + +#### `isDivisibleBy(number)` + +Returns `true` if the first number is divisible by the second number, `false` otherwise. + + - `bigInt(999).isDivisibleBy(333)` => `true` + - `bigInt(99).isDivisibleBy(5)` => `false` + +#### `isEven()` + +Returns `true` if the number is even, `false` otherwise. + + - `bigInt(6).isEven()` => `true` + - `bigInt(3).isEven()` => `false` + +#### `isNegative()` + +Returns `true` if the number is negative, `false` otherwise. +Returns `false` for `0` and `-0`. + + - `bigInt(-23).isNegative()` => `true` + - `bigInt(50).isNegative()` => `false` + +#### `isOdd()` + +Returns `true` if the number is odd, `false` otherwise. + + - `bigInt(13).isOdd()` => `true` + - `bigInt(40).isOdd()` => `false` + +#### `isPositive()` + +Return `true` if the number is positive, `false` otherwise. +Returns `false` for `0` and `-0`. + + - `bigInt(54).isPositive()` => `true` + - `bigInt(-1).isPositive()` => `false` + +#### `isPrime(strict?)` + +Returns `true` if the number is prime, `false` otherwise. +Set "strict" boolean to true to force GRH-supported lower bound of 2*log(N)^2. + + - `bigInt(5).isPrime()` => `true` + - `bigInt(6).isPrime()` => `false` + +#### `isProbablePrime([iterations], [rng])` + +Returns `true` if the number is very likely to be prime, `false` otherwise. +Supplying `iterations` is optional - it determines the number of iterations of the test (default: `5`). The more iterations, the lower chance of getting a false positive. +This uses the [Miller Rabin test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test). + + - `bigInt(5).isProbablePrime()` => `true` + - `bigInt(49).isProbablePrime()` => `false` + - `bigInt(1729).isProbablePrime()` => `false` + +Note that this function is not deterministic, since it relies on random sampling of factors, so the result for some numbers is not always the same - unless you pass a predictable random number generator as `rng`. The behavior and requirements are the same as with `randBetween`. + + - `bigInt(1729).isProbablePrime(1, () => 0.1)` => `false` + - `bigInt(1729).isProbablePrime(1, () => 0.2)` => `true` + +If the number is composite then the Miller–Rabin primality test declares the number probably prime with a probability at most `4` to the power `−iterations`. +If the number is prime, this function always returns `true`. + +#### `isUnit()` + +Returns `true` if the number is `1` or `-1`, `false` otherwise. + + - `bigInt.one.isUnit()` => `true` + - `bigInt.minusOne.isUnit()` => `true` + - `bigInt(5).isUnit()` => `false` + +#### `isZero()` + +Return `true` if the number is `0` or `-0`, `false` otherwise. + + - `bigInt.zero.isZero()` => `true` + - `bigInt("-0").isZero()` => `true` + - `bigInt(50).isZero()` => `false` + +#### `leq(number)` + +Alias for the `lesserOrEquals` method. + +#### `lesser(number)` + +Checks if the first number is lesser than the second. + + - `bigInt(5).lesser(6)` => `true` + - `bigInt(5).lesser(5)` => `false` + - `bigInt(5).lesser(4)` => `false` + +#### `lesserOrEquals(number)` + +Checks if the first number is less than or equal to the second. + + - `bigInt(5).lesserOrEquals(6)` => `true` + - `bigInt(5).lesserOrEquals(5)` => `true` + - `bigInt(5).lesserOrEquals(4)` => `false` + +#### `lt(number)` + +Alias for the `lesser` method. + +#### `minus(number)` + +Alias for the `subtract` method. + + - `bigInt(3).minus(5)` => `-2` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Subtraction) + +#### `mod(number)` + +Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend. + + - `bigInt(59).mod(5)` => `4` + - `bigInt(-5).mod(2)` => `-1` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division) + +#### `modInv(mod)` + +Finds the [multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of the number modulo `mod`. + + - `bigInt(3).modInv(11)` => `4` + - `bigInt(42).modInv(2017)` => `1969` + +#### `modPow(exp, mod)` + +Takes the number to the power `exp` modulo `mod`. + + - `bigInt(10).modPow(3, 30)` => `10` + +#### `multiply(number)` + +Performs multiplication. + + - `bigInt(111).multiply(111)` => `12321` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Multiplication) + +#### `neq(number)` + +Alias for the `notEquals` method. + +#### `next()` + +Adds one to the number. + + - `bigInt(6).next()` => `7` + +#### `not()` + +Performs the bitwise NOT operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement). + + - `bigInt(10).not()` => `-11` + - `bigInt(0).not()` => `-1` + +#### `notEquals(number)` + +Checks if two numbers are not equal. + + - `bigInt(5).notEquals(5)` => `false` + - `bigInt(4).notEquals(7)` => `true` + +#### `or(number)` + +Performs the bitwise OR operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement). + + - `bigInt(13).or(10)` => `15` + - `bigInt(13).or(-8)` => `-3` + +#### `over(number)` + +Alias for the `divide` method. + + - `bigInt(59).over(5)` => `11` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division) + +#### `plus(number)` + +Alias for the `add` method. + + - `bigInt(5).plus(7)` => `12` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Addition) + +#### `pow(number)` + +Performs exponentiation. If the exponent is less than `0`, `pow` returns `0`. `bigInt.zero.pow(0)` returns `1`. + + - `bigInt(16).pow(16)` => `18446744073709551616` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Exponentiation) + +#### `prev(number)` + +Subtracts one from the number. + + - `bigInt(6).prev()` => `5` + +#### `remainder(number)` + +Alias for the `mod` method. + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division) + +#### `shiftLeft(n)` + +Shifts the number left by `n` places in its binary representation. If a negative number is provided, it will shift right. Throws an error if `n` is outside of the range `[-9007199254740992, 9007199254740992]`. + + - `bigInt(8).shiftLeft(2)` => `32` + - `bigInt(8).shiftLeft(-2)` => `2` + +#### `shiftRight(n)` + +Shifts the number right by `n` places in its binary representation. If a negative number is provided, it will shift left. Throws an error if `n` is outside of the range `[-9007199254740992, 9007199254740992]`. + + - `bigInt(8).shiftRight(2)` => `2` + - `bigInt(8).shiftRight(-2)` => `32` + +#### `square()` + +Squares the number + + - `bigInt(3).square()` => `9` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Squaring) + +#### `subtract(number)` + +Performs subtraction. + + - `bigInt(3).subtract(5)` => `-2` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Subtraction) + +#### `times(number)` + +Alias for the `multiply` method. + + - `bigInt(111).times(111)` => `12321` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Multiplication) + +#### `toArray(radix)` + +Converts a bigInt into an object with the properties "value" and "isNegative." "Value" is an array of integers modulo the given radix. "isNegative" is a boolean that represents the sign of the result. + + - `bigInt("1e9").toArray(10)` => { + value: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + isNegative: false + } + - `bigInt("1e9").toArray(16)` => { + value: [3, 11, 9, 10, 12, 10, 0, 0], + isNegative: false + } + - `bigInt(567890).toArray(100)` => { + value: [56, 78, 90], + isNegative: false + } + +Negative bases are supported. + + - `bigInt(12345).toArray(-10)` => { + value: [2, 8, 4, 6, 5], + isNegative: false + } + +Base 1 and base -1 are also supported. + + - `bigInt(-15).toArray(1)` => { + value: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + isNegative: true + } + - `bigInt(-15).toArray(-1)` => { + value: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], + isNegative: false + } + +Base 0 is only allowed for the number zero. + + - `bigInt(0).toArray(0)` => { + value: [0], + isNegative: false + } + - `bigInt(1).toArray(0)` => `Error: Cannot convert nonzero numbers to base 0.` + +#### `toJSNumber()` + +Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range `[-9007199254740992, 9007199254740992]`. + + - `bigInt("18446744073709551616").toJSNumber()` => `18446744073709552000` + +#### `xor(number)` + +Performs the bitwise XOR operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement). + + - `bigInt(12).xor(5)` => `9` + - `bigInt(12).xor(-5)` => `-9` + +### Static Methods + +#### `fromArray(digits, base = 10, isNegative?)` + +Constructs a bigInt from an array of digits in base `base`. The optional `isNegative` flag will make the number negative. + + - `bigInt.fromArray([1, 2, 3, 4, 5], 10)` => `12345` + - `bigInt.fromArray([1, 0, 0], 2, true)` => `-4` + +#### `gcd(a, b)` + +Finds the greatest common denominator of `a` and `b`. + + - `bigInt.gcd(42,56)` => `14` + +#### `isInstance(x)` + +Returns `true` if `x` is a BigInteger, `false` otherwise. + + - `bigInt.isInstance(bigInt(14))` => `true` + - `bigInt.isInstance(14)` => `false` + +#### `lcm(a,b)` + +Finds the least common multiple of `a` and `b`. + + - `bigInt.lcm(21, 6)` => `42` + +#### `max(a,b)` + +Returns the largest of `a` and `b`. + + - `bigInt.max(77, 432)` => `432` + +#### `min(a,b)` + +Returns the smallest of `a` and `b`. + + - `bigInt.min(77, 432)` => `77` + +#### `randBetween(min, max, [rng])` + +Returns a random number between `min` and `max`, optionally using `rng` to generate randomness. + + - `bigInt.randBetween("-1e100", "1e100")` => (for example) `8494907165436643479673097939554427056789510374838494147955756275846226209006506706784609314471378745` + +`rng` should take no arguments and return a `number` between 0 and 1. It defaults to `Math.random`. + + - `bigInt.randBetween("-1e100", "1e100", () => 0.5)` => (always) `50000005000000500000050000005000000500000050000005000000500000050000005000000500000050000005000000` + + +### Override Methods + +#### `toString(radix = 10, [alphabet])` + +Converts a bigInt to a string. There is an optional radix parameter (which defaults to 10) that converts the number to the given radix. Digits in the range `10-35` will use the letters `a-z`. + + - `bigInt("1e9").toString()` => `"1000000000"` + - `bigInt("1e9").toString(16)` => `"3b9aca00"` + + You can use a custom base alphabet with the second parameter. The default `alphabet` is `"0123456789abcdefghijklmnopqrstuvwxyz"`. + + - `bigInt("5").toString(2, "aA")` => `"AaA"` + +**Note that arithmetical operators will trigger the `valueOf` function rather than the `toString` function.** When converting a bigInteger to a string, you should use the `toString` method or the `String` function instead of adding the empty string. + + - `bigInt("999999999999999999").toString()` => `"999999999999999999"` + - `String(bigInt("999999999999999999"))` => `"999999999999999999"` + - `bigInt("999999999999999999") + ""` => `1000000000000000000` + +Bases larger than 36 are supported. If a digit is greater than or equal to 36, it will be enclosed in angle brackets. + + - `bigInt(567890).toString(100)` => `"<56><78><90>"` + +Negative bases are also supported. + + - `bigInt(12345).toString(-10)` => `"28465"` + +Base 1 and base -1 are also supported. + + - `bigInt(-15).toString(1)` => `"-111111111111111"` + - `bigInt(-15).toString(-1)` => `"101010101010101010101010101010"` + +Base 0 is only allowed for the number zero. + + - `bigInt(0).toString(0)` => `0` + - `bigInt(1).toString(0)` => `Error: Cannot convert nonzero numbers to base 0.` + +[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#toString) + +#### `valueOf()` + +Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion: + + - `bigInt("100") + bigInt("200") === 300; //true` + +## Contributors + +To contribute, just fork the project, make some changes, and submit a pull request. Please verify that the unit tests pass before submitting. + +The unit tests are contained in the `spec/spec.js` file. You can run them locally by opening the `spec/SpecRunner.html` or file or running `npm test`. You can also [run the tests online from GitHub](http://peterolson.github.io/BigInteger.js/spec/SpecRunner.html). + +There are performance benchmarks that can be viewed from the `benchmarks/index.html` page. You can [run them online from GitHub](http://peterolson.github.io/BigInteger.js/benchmark/). + +## License + +This project is public domain. For more details, read about the [Unlicense](http://unlicense.org/). diff --git a/node_modules/big-integer/bower.json b/node_modules/big-integer/bower.json new file mode 100644 index 0000000..c744605 --- /dev/null +++ b/node_modules/big-integer/bower.json @@ -0,0 +1,29 @@ +{ + "name": "big-integer", + "description": "An arbitrary length integer library for Javascript", + "main": "./BigInteger.js", + "authors": [ + "Peter Olson" + ], + "license": "Unlicense", + "keywords": [ + "math", + "big", + "bignum", + "bigint", + "biginteger", + "integer", + "arbitrary", + "precision", + "arithmetic" + ], + "homepage": "https://github.com/peterolson/BigInteger.js", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "coverage", + "tests" + ] +} diff --git a/node_modules/big-integer/package.json b/node_modules/big-integer/package.json new file mode 100644 index 0000000..5c1470d --- /dev/null +++ b/node_modules/big-integer/package.json @@ -0,0 +1,48 @@ +{ + "name": "big-integer", + "version": "1.6.51", + "author": "Peter Olson ", + "description": "An arbitrary length integer library for Javascript", + "contributors": [], + "bin": {}, + "scripts": { + "test": "tsc && karma start my.conf.js && node spec/tsDefinitions.js", + "minify": "uglifyjs BigInteger.js -o BigInteger.min.js" + }, + "main": "./BigInteger", + "repository": { + "type": "git", + "url": "git@github.com:peterolson/BigInteger.js.git" + }, + "keywords": [ + "math", + "big", + "bignum", + "bigint", + "biginteger", + "integer", + "arbitrary", + "precision", + "arithmetic" + ], + "devDependencies": { + "@types/lodash": "^4.14.175", + "@types/node": "^7.10.2", + "coveralls": "^3.0.6", + "jasmine": "3.5.0", + "jasmine-core": "^3.5.0", + "karma": "^6.3.4", + "karma-cli": "^2.0.0", + "karma-coverage": "^2.0.3", + "karma-jasmine": "^4.0.1", + "karma-phantomjs-launcher": "^1.0.4", + "lodash": "^4.17.21", + "typescript": "^3.6.3", + "uglifyjs": "^2.4.10" + }, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + }, + "typings": "./BigInteger.d.ts" +} diff --git a/node_modules/big-integer/tsconfig.json b/node_modules/big-integer/tsconfig.json new file mode 100644 index 0000000..8efb23c --- /dev/null +++ b/node_modules/big-integer/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "./", + "moduleResolution": "node", + "allowJs": true, + "typeRoots": [ + "./" + ], + "types": [ + "node" + ], + "forceConsistentCasingInFileNames": true + }, + "files": [ + "BigInteger.d.ts", + "spec/tsDefinitions.ts" + ] +} diff --git a/node_modules/bl/.github/dependabot.yml b/node_modules/bl/.github/dependabot.yml new file mode 100644 index 0000000..f468993 --- /dev/null +++ b/node_modules/bl/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + - package-ecosystem: 'github-actions' + directory: '/' + schedule: + interval: 'daily' + commit-message: + prefix: 'chore' + include: 'scope' + - package-ecosystem: 'npm' + directory: '/' + schedule: + interval: 'daily' + commit-message: + prefix: 'chore' + include: 'scope' diff --git a/node_modules/bl/.github/workflows/test-and-release.yml b/node_modules/bl/.github/workflows/test-and-release.yml new file mode 100644 index 0000000..65887a0 --- /dev/null +++ b/node_modules/bl/.github/workflows/test-and-release.yml @@ -0,0 +1,61 @@ +name: Test & Maybe Release +on: [push, pull_request] +jobs: + test: + strategy: + fail-fast: false + matrix: + node: [14.x, 16.x, 18.x, lts/*, current] + os: [macos-latest, ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout Repository + uses: actions/checkout@v3 + - name: Use Node.js ${{ matrix.node }} + uses: actions/setup-node@v3.5.1 + with: + node-version: ${{ matrix.node }} + - name: Install Dependencies + run: | + npm install --no-progress + - name: Run tests + run: | + npm config set script-shell bash + npm run test:ci + release: + name: Release + needs: test + runs-on: ubuntu-latest + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Setup Node.js + uses: actions/setup-node@v3.5.1 + with: + node-version: 14 + - name: Install dependencies + run: | + npm install --no-progress --no-package-lock --no-save + - name: Build + run: | + npm run build + - name: Install plugins + run: | + npm install \ + @semantic-release/commit-analyzer \ + conventional-changelog-conventionalcommits \ + @semantic-release/release-notes-generator \ + @semantic-release/npm \ + @semantic-release/github \ + @semantic-release/git \ + @semantic-release/changelog \ + --no-progress --no-package-lock --no-save + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npx semantic-release + diff --git a/node_modules/bl/BufferList.d.ts b/node_modules/bl/BufferList.d.ts new file mode 100644 index 0000000..1561583 --- /dev/null +++ b/node_modules/bl/BufferList.d.ts @@ -0,0 +1,382 @@ +export type BufferListAcceptedTypes = + | Buffer + | BufferList + | Uint8Array + | BufferListAcceptedTypes[] + | string + | number; + +export interface BufferListConstructor { + new (initData?: BufferListAcceptedTypes): BufferList; + (initData?: BufferListAcceptedTypes): BufferList; + + /** + * Determines if the passed object is a BufferList. It will return true + * if the passed object is an instance of BufferList or BufferListStream + * and false otherwise. + * + * N.B. this won't return true for BufferList or BufferListStream instances + * created by versions of this library before this static method was added. + * + * @param other + */ + + isBufferList(other: unknown): boolean; +} + +interface BufferList { + prototype: Object + + /** + * Get the length of the list in bytes. This is the sum of the lengths + * of all of the buffers contained in the list, minus any initial offset + * for a semi-consumed buffer at the beginning. Should accurately + * represent the total number of bytes that can be read from the list. + */ + + length: number; + + /** + * Adds an additional buffer or BufferList to the internal list. + * this is returned so it can be chained. + * + * @param buffer + */ + + append(buffer: BufferListAcceptedTypes): this; + + /** + * Will return the byte at the specified index. + * @param index + */ + + get(index: number): number; + + /** + * Returns a new Buffer object containing the bytes within the + * range specified. Both start and end are optional and will + * default to the beginning and end of the list respectively. + * + * If the requested range spans a single internal buffer then a + * slice of that buffer will be returned which shares the original + * memory range of that Buffer. If the range spans multiple buffers + * then copy operations will likely occur to give you a uniform Buffer. + * + * @param start + * @param end + */ + + slice(start?: number, end?: number): Buffer; + + /** + * Returns a new BufferList object containing the bytes within the + * range specified. Both start and end are optional and will default + * to the beginning and end of the list respectively. + * + * No copies will be performed. All buffers in the result share + * memory with the original list. + * + * @param start + * @param end + */ + + shallowSlice(start?: number, end?: number): this; + + /** + * Copies the content of the list in the `dest` buffer, starting from + * `destStart` and containing the bytes within the range specified + * with `srcStart` to `srcEnd`. + * + * `destStart`, `start` and `end` are optional and will default to the + * beginning of the dest buffer, and the beginning and end of the + * list respectively. + * + * @param dest + * @param destStart + * @param srcStart + * @param srcEnd + */ + + copy( + dest: Buffer, + destStart?: number, + srcStart?: number, + srcEnd?: number + ): Buffer; + + /** + * Performs a shallow-copy of the list. The internal Buffers remains the + * same, so if you change the underlying Buffers, the change will be + * reflected in both the original and the duplicate. + * + * This method is needed if you want to call consume() or pipe() and + * still keep the original list. + * + * @example + * + * ```js + * var bl = new BufferListStream(); + * bl.append('hello'); + * bl.append(' world'); + * bl.append('\n'); + * bl.duplicate().pipe(process.stdout, { end: false }); + * + * console.log(bl.toString()) + * ``` + */ + + duplicate(): this; + + /** + * Will shift bytes off the start of the list. The number of bytes + * consumed don't need to line up with the sizes of the internal + * Buffers—initial offsets will be calculated accordingly in order + * to give you a consistent view of the data. + * + * @param bytes + */ + + consume(bytes?: number): void; + + /** + * Will return a string representation of the buffer. The optional + * `start` and `end` arguments are passed on to `slice()`, while + * the encoding is passed on to `toString()` of the resulting Buffer. + * + * See the [`Buffer#toString()`](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) + * documentation for more information. + * + * @param encoding + * @param start + * @param end + */ + + toString(encoding?: string, start?: number, end?: number): string; + + /** + * Will return the byte at the specified index. indexOf() method + * returns the first index at which a given element can be found + * in the BufferList, or -1 if it is not present. + * + * @param value + * @param byteOffset + * @param encoding + */ + + indexOf( + value: string | number | Uint8Array | BufferList | Buffer, + byteOffset?: number, + encoding?: string + ): number; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readDoubleBE: Buffer['readDoubleBE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readDoubleLE: Buffer['readDoubleLE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readFloatBE: Buffer['readFloatBE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readFloatLE: Buffer['readFloatLE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readInt32BE: Buffer['readInt32BE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readInt32LE: Buffer['readInt32LE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readUInt32BE: Buffer['readUInt32BE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readUInt32LE: Buffer['readUInt32LE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently. + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + * + * @param offset + */ + + readInt16BE: Buffer['readInt16BE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readInt16LE: Buffer['readInt16LE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readUInt16BE: Buffer['readUInt16BE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readUInt16LE: Buffer['readUInt16LE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readInt8: Buffer['readInt8']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readUInt8: Buffer['readUInt8']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readIntBE: Buffer['readIntBE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readIntLE: Buffer['readIntLE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readUIntBE: Buffer['readUIntBE']; + + /** + * All of the standard byte-reading methods of the Buffer interface are + * implemented and will operate across internal Buffer boundaries transparently. + * + * See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) + * documentation for how these work. + * + * @param offset + */ + + readUIntLE: Buffer['readUIntLE']; +} + +/** + * No arguments are required for the constructor, but you can initialise + * the list by passing in a single Buffer object or an array of Buffer + * objects. + * + * `new` is not strictly required, if you don't instantiate a new object, + * it will be done automatically for you so you can create a new instance + * simply with: + * + * ```js + * const { BufferList } = require('bl') + * const bl = BufferList() + * + * // equivalent to: + * + * const { BufferList } = require('bl') + * const bl = new BufferList() + * ``` + */ + +declare const BufferList: BufferListConstructor; diff --git a/node_modules/bl/BufferList.js b/node_modules/bl/BufferList.js new file mode 100644 index 0000000..471ee77 --- /dev/null +++ b/node_modules/bl/BufferList.js @@ -0,0 +1,396 @@ +'use strict' + +const { Buffer } = require('buffer') +const symbol = Symbol.for('BufferList') + +function BufferList (buf) { + if (!(this instanceof BufferList)) { + return new BufferList(buf) + } + + BufferList._init.call(this, buf) +} + +BufferList._init = function _init (buf) { + Object.defineProperty(this, symbol, { value: true }) + + this._bufs = [] + this.length = 0 + + if (buf) { + this.append(buf) + } +} + +BufferList.prototype._new = function _new (buf) { + return new BufferList(buf) +} + +BufferList.prototype._offset = function _offset (offset) { + if (offset === 0) { + return [0, 0] + } + + let tot = 0 + + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot] + } + tot = _t + } +} + +BufferList.prototype._reverseOffset = function (blOffset) { + const bufferId = blOffset[0] + let offset = blOffset[1] + + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + + return offset +} + +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + + const offset = this._offset(index) + + return this._bufs[offset[0]][offset[1]] +} + +BufferList.prototype.slice = function slice (start, end) { + if (typeof start === 'number' && start < 0) { + start += this.length + } + + if (typeof end === 'number' && end < 0) { + end += this.length + } + + return this.copy(null, 0, start, end) +} + +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== 'number' || srcStart < 0) { + srcStart = 0 + } + + if (typeof srcEnd !== 'number' || srcEnd > this.length) { + srcEnd = this.length + } + + if (srcStart >= this.length) { + return dst || Buffer.alloc(0) + } + + if (srcEnd <= 0) { + return dst || Buffer.alloc(0) + } + + const copy = !!dst + const off = this._offset(srcStart) + const len = srcEnd - srcStart + let bytes = len + let bufoff = (copy && dstStart) || 0 + let start = off[1] + + // copy/slice everything + if (srcStart === 0 && srcEnd === this.length) { + if (!copy) { + // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } + + // copy, need to copy individual buffers + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } + + return dst + } + + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } + + if (!copy) { + // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + } + + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } + + bytes -= l + + if (start) { + start = 0 + } + } + + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + + return dst +} + +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end + + if (start < 0) { + start += this.length + } + + if (end < 0) { + end += this.length + } + + if (start === end) { + return this._new() + } + + const startOffset = this._offset(start) + const endOffset = this._offset(end) + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + + if (endOffset[1] === 0) { + buffers.pop() + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) + } + + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]) + } + + return this._new(buffers) +} + +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} + +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break + } + } + + return this +} + +BufferList.prototype.duplicate = function duplicate () { + const copy = this._new() + + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]) + } + + return copy +} + +BufferList.prototype.append = function append (buf) { + if (buf == null) { + return this + } + + if (buf.buffer) { + // append a view of the underlying ArrayBuffer + this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]) + } + } else if (this._isBufferList(buf)) { + // unwrap argument into individual BufferLists + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]) + } + } else { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf === 'number') { + buf = buf.toString() + } + + this._appendBuffer(Buffer.from(buf)) + } + + return this +} + +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} + +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } + + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (this._isBufferList(search)) { + search = search.slice() + } else if (Array.isArray(search.buffer)) { + search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } + + offset = Number(offset || 0) + + if (isNaN(offset)) { + offset = 0 + } + + if (offset < 0) { + offset = this.length + offset + } + + if (offset < 0) { + offset = 0 + } + + if (search.length === 0) { + return offset > this.length ? this.length : offset + } + + const blOffset = this._offset(offset) + let blIndex = blOffset[0] // index of which internal buffer we're working on + let buffOffset = blOffset[1] // offset of the internal buffer we're working on + + // scan over each buffer + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex] + + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset + + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset) + + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + const revOffset = this._reverseOffset([blIndex, buffOffset]) + + if (this._match(revOffset, search)) { + return revOffset + } + + buffOffset++ + } + } + + buffOffset = 0 + } + + return -1 +} + +BufferList.prototype._match = function (offset, search) { + if (this.length - offset < search.length) { + return false + } + + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false + } + } + return true +} + +;(function () { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + } + + for (const m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } else { + BufferList.prototype[m] = function (offset = 0) { + return this.slice(offset, offset + methods[m])[m](0) + } + } + }(m)) + } +}()) + +// Used internally by the class and also as an indicator of this object being +// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser +// environment because there could be multiple different copies of the +// BufferList class and some `BufferList`s might be `BufferList`s. +BufferList.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferList || BufferList.isBufferList(b) +} + +BufferList.isBufferList = function isBufferList (b) { + return b != null && b[symbol] +} + +module.exports = BufferList diff --git a/node_modules/bl/CHANGELOG.md b/node_modules/bl/CHANGELOG.md new file mode 100644 index 0000000..a6156dc --- /dev/null +++ b/node_modules/bl/CHANGELOG.md @@ -0,0 +1,17 @@ +## [5.1.0](https://github.com/rvagg/bl/compare/v5.0.0...v5.1.0) (2022-10-18) + + +### Features + +* added integrated TypeScript typings ([#108](https://github.com/rvagg/bl/issues/108)) ([433ff89](https://github.com/rvagg/bl/commit/433ff8942f47fab8a5c9d13b2c00989ccf8d0710)) + + +### Bug Fixes + +* windows support in tests ([387dfaf](https://github.com/rvagg/bl/commit/387dfaf9b2bca7849f12785436ceb01e42adac2c)) + + +### Trivial Changes + +* GH Actions, Dependabot, auto-release, remove Travis ([997f058](https://github.com/rvagg/bl/commit/997f058357de8f2a7f66998e80a72b491835573f)) +* **no-release:** bump standard from 16.0.4 to 17.0.0 ([#112](https://github.com/rvagg/bl/issues/112)) ([078bfe3](https://github.com/rvagg/bl/commit/078bfe33390d125297b1c946e5989c4aa9228961)) diff --git a/node_modules/bl/LICENSE.md b/node_modules/bl/LICENSE.md new file mode 100644 index 0000000..ecbe516 --- /dev/null +++ b/node_modules/bl/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2013-2019 bl contributors +---------------------------------- + +*bl contributors listed at * + +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. diff --git a/node_modules/bl/README.md b/node_modules/bl/README.md new file mode 100644 index 0000000..9680b1d --- /dev/null +++ b/node_modules/bl/README.md @@ -0,0 +1,247 @@ +# bl *(BufferList)* + +[![Build Status](https://api.travis-ci.com/rvagg/bl.svg?branch=master)](https://travis-ci.com/rvagg/bl/) + +**A Node.js Buffer list collector, reader and streamer thingy.** + +[![NPM](https://nodei.co/npm/bl.svg)](https://nodei.co/npm/bl/) + +**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! + +The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. + +```js +const { BufferList } = require('bl') + +const bl = new BufferList() +bl.append(Buffer.from('abcd')) +bl.append(Buffer.from('efg')) +bl.append('hi') // bl will also accept & convert Strings +bl.append(Buffer.from('j')) +bl.append(Buffer.from([ 0x3, 0x4 ])) + +console.log(bl.length) // 12 + +console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' +console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' +console.log(bl.slice(3, 6).toString('ascii')) // 'def' +console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' +console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' + +console.log(bl.indexOf('def')) // 3 +console.log(bl.indexOf('asdf')) // -1 + +// or just use toString! +console.log(bl.toString()) // 'abcdefghij\u0003\u0004' +console.log(bl.toString('ascii', 3, 8)) // 'defgh' +console.log(bl.toString('ascii', 5, 10)) // 'fghij' + +// other standard Buffer readables +console.log(bl.readUInt16BE(10)) // 0x0304 +console.log(bl.readUInt16LE(10)) // 0x0403 +``` + +Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: + +```js +const { BufferListStream } = require('bl') +const fs = require('fs') + +fs.createReadStream('README.md') + .pipe(BufferListStream((err, data) => { // note 'new' isn't strictly required + // `data` is a complete Buffer object containing the full data + console.log(data.toString()) + })) +``` + +Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. + +Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): + +```js +const hyperquest = require('hyperquest') +const { BufferListStream } = require('bl') + +const url = 'https://raw.github.com/rvagg/bl/master/README.md' + +hyperquest(url).pipe(BufferListStream((err, data) => { + console.log(data.toString()) +})) +``` + +Or, use it as a readable stream to recompose a list of Buffers to an output source: + +```js +const { BufferListStream } = require('bl') +const fs = require('fs') + +var bl = new BufferListStream() +bl.append(Buffer.from('abcd')) +bl.append(Buffer.from('efg')) +bl.append(Buffer.from('hi')) +bl.append(Buffer.from('j')) + +bl.pipe(fs.createWriteStream('gibberish.txt')) +``` + +## API + + * new BufferList([ buf ]) + * BufferList.isBufferList(obj) + * bl.length + * bl.append(buffer) + * bl.get(index) + * bl.indexOf(value[, byteOffset][, encoding]) + * bl.slice([ start[, end ] ]) + * bl.shallowSlice([ start[, end ] ]) + * bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) + * bl.duplicate() + * bl.consume(bytes) + * bl.toString([encoding, [ start, [ end ]]]) + * bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() + * new BufferListStream([ callback ]) + +-------------------------------------------------------- + +### new BufferList([ Buffer | Buffer array | BufferList | BufferList array | String ]) +No arguments are _required_ for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` objects. + +`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: + +```js +const { BufferList } = require('bl') +const bl = BufferList() + +// equivalent to: + +const { BufferList } = require('bl') +const bl = new BufferList() +``` + +-------------------------------------------------------- + +### BufferList.isBufferList(obj) +Determines if the passed object is a `BufferList`. It will return `true` if the passed object is an instance of `BufferList` **or** `BufferListStream` and `false` otherwise. + +N.B. this won't return `true` for `BufferList` or `BufferListStream` instances created by versions of this library before this static method was added. + +-------------------------------------------------------- + +### bl.length +Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. + +-------------------------------------------------------- + +### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) +`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. + +-------------------------------------------------------- + +### bl.get(index) +`get()` will return the byte at the specified index. + +-------------------------------------------------------- + +### bl.indexOf(value[, byteOffset][, encoding]) +`get()` will return the byte at the specified index. +`indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. + +-------------------------------------------------------- + +### bl.slice([ start, [ end ] ]) +`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. + +If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. + +-------------------------------------------------------- + +### bl.shallowSlice([ start, [ end ] ]) +`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. + +No copies will be performed. All buffers in the result share memory with the original list. + +-------------------------------------------------------- + +### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) +`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. + +-------------------------------------------------------- + +### bl.duplicate() +`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: + +```js +var bl = new BufferListStream() + +bl.append('hello') +bl.append(' world') +bl.append('\n') + +bl.duplicate().pipe(process.stdout, { end: false }) + +console.log(bl.toString()) +``` + +-------------------------------------------------------- + +### bl.consume(bytes) +`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data. + +-------------------------------------------------------- + +### bl.toString([encoding, [ start, [ end ]]]) +`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. + +-------------------------------------------------------- + +### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() + +All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. + +See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + +-------------------------------------------------------- + +### new BufferListStream([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) +**BufferListStream** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **BufferListStream** instance. + +The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. + +Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. + +`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: + +```js +const { BufferListStream } = require('bl') +const bl = BufferListStream() + +// equivalent to: + +const { BufferListStream } = require('bl') +const bl = new BufferListStream() +``` + +N.B. For backwards compatibility reasons, `BufferListStream` is the **default** export when you `require('bl')`: + +```js +const { BufferListStream } = require('bl') +// equivalent to: +const BufferListStream = require('bl') +``` + +-------------------------------------------------------- + +## Contributors + +**bl** is brought to you by the following hackers: + + * [Rod Vagg](https://github.com/rvagg) + * [Matteo Collina](https://github.com/mcollina) + * [Jarett Cruger](https://github.com/jcrugzz) + + +## License & copyright + +Copyright (c) 2013-2019 bl contributors (listed above). + +bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/node_modules/bl/bl.js b/node_modules/bl/bl.js new file mode 100644 index 0000000..40228f8 --- /dev/null +++ b/node_modules/bl/bl.js @@ -0,0 +1,84 @@ +'use strict' + +const DuplexStream = require('readable-stream').Duplex +const inherits = require('inherits') +const BufferList = require('./BufferList') + +function BufferListStream (callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback) + } + + if (typeof callback === 'function') { + this._callback = callback + + const piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) + + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + + callback = null + } + + BufferList._init.call(this, callback) + DuplexStream.call(this) +} + +inherits(BufferListStream, DuplexStream) +Object.assign(BufferListStream.prototype, BufferList.prototype) + +BufferListStream.prototype._new = function _new (callback) { + return new BufferListStream(callback) +} + +BufferListStream.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) + + if (typeof callback === 'function') { + callback() + } +} + +BufferListStream.prototype._read = function _read (size) { + if (!this.length) { + return this.push(null) + } + + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} + +BufferListStream.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) + + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} + +BufferListStream.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} + +BufferListStream.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) +} + +BufferListStream.isBufferList = BufferList.isBufferList + +module.exports = BufferListStream +module.exports.BufferListStream = BufferListStream +module.exports.BufferList = BufferList diff --git a/node_modules/bl/index.d.ts b/node_modules/bl/index.d.ts new file mode 100644 index 0000000..07a8ee3 --- /dev/null +++ b/node_modules/bl/index.d.ts @@ -0,0 +1,88 @@ +import { Duplex } from "readable-stream"; +import { + BufferList as BL, + BufferListConstructor, + BufferListAcceptedTypes, +} from "./BufferList"; + +type BufferListStreamInit = + | ((err: Error, buffer: Buffer) => void) + | BufferListAcceptedTypes; + +interface BufferListStreamConstructor { + new (initData?: BufferListStreamInit): BufferListStream; + (callback?: BufferListStreamInit): BufferListStream; + + /** + * Determines if the passed object is a BufferList. It will return true + * if the passed object is an instance of BufferList or BufferListStream + * and false otherwise. + * + * N.B. this won't return true for BufferList or BufferListStream instances + * created by versions of this library before this static method was added. + * + * @param other + */ + + isBufferList(other: unknown): boolean; + + /** + * Rexporting BufferList and BufferListStream to fix + * issue with require/commonjs import and "export = " below. + */ + + BufferList: BufferListConstructor; + BufferListStream: BufferListStreamConstructor; +} + +interface BufferListStream extends Duplex, BL { + prototype: BufferListStream & BL; +} + +/** + * BufferListStream is a Node Duplex Stream, so it can be read from + * and written to like a standard Node stream. You can also pipe() + * to and from a BufferListStream instance. + * + * The constructor takes an optional callback, if supplied, the + * callback will be called with an error argument followed by a + * reference to the bl instance, when bl.end() is called + * (i.e. from a piped stream). + * + * This is a convenient method of collecting the entire contents of + * a stream, particularly when the stream is chunky, such as a network + * stream. + * + * Normally, no arguments are required for the constructor, but you can + * initialise the list by passing in a single Buffer object or an array + * of Buffer object. + * + * `new` is not strictly required, if you don't instantiate a new object, + * it will be done automatically for you so you can create a new instance + * simply with: + * + * ```js + * const { BufferListStream } = require('bl'); + * const bl = BufferListStream(); + * + * // equivalent to: + * + * const { BufferListStream } = require('bl'); + * const bl = new BufferListStream(); + * ``` + * + * N.B. For backwards compatibility reasons, BufferListStream is the default + * export when you `require('bl')`: + * + * ```js + * const { BufferListStream } = require('bl') + * + * // equivalent to: + * + * const BufferListStream = require('bl') + * ``` + */ + +declare const BufferListStream: BufferListStreamConstructor; + +export = BufferListStream; diff --git a/node_modules/bl/package.json b/node_modules/bl/package.json new file mode 100644 index 0000000..92a08e3 --- /dev/null +++ b/node_modules/bl/package.json @@ -0,0 +1,123 @@ +{ + "name": "bl", + "version": "5.1.0", + "description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!", + "license": "MIT", + "main": "bl.js", + "scripts": { + "lint": "standard *.js test/*.js", + "test": "npm run lint && npm run test:types && node test/test.js | faucet", + "test:ci": "npm run lint && node test/test.js && npm run test:types", + "test:types": "tsc --allowJs --noEmit test/test.js", + "build": "true" + }, + "repository": { + "type": "git", + "url": "https://github.com/rvagg/bl.git" + }, + "homepage": "https://github.com/rvagg/bl", + "authors": [ + "Rod Vagg (https://github.com/rvagg)", + "Matteo Collina (https://github.com/mcollina)", + "Jarett Cruger (https://github.com/jcrugzz)" + ], + "keywords": [ + "buffer", + "buffers", + "stream", + "awesomesauce" + ], + "dependencies": { + "buffer": "^6.0.3", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + }, + "devDependencies": { + "@types/readable-stream": "^2.3.13", + "faucet": "~0.0.1", + "standard": "^17.0.0", + "tape": "^5.2.2", + "typescript": "~4.7.3" + }, + "release": { + "branches": [ + "master" + ], + "plugins": [ + [ + "@semantic-release/commit-analyzer", + { + "preset": "conventionalcommits", + "releaseRules": [ + { + "breaking": true, + "release": "major" + }, + { + "revert": true, + "release": "patch" + }, + { + "type": "feat", + "release": "minor" + }, + { + "type": "fix", + "release": "patch" + }, + { + "type": "chore", + "release": "patch" + }, + { + "type": "docs", + "release": "patch" + }, + { + "type": "test", + "release": "patch" + }, + { + "scope": "no-release", + "release": false + } + ] + } + ], + [ + "@semantic-release/release-notes-generator", + { + "preset": "conventionalcommits", + "presetConfig": { + "types": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "chore", + "section": "Trivial Changes" + }, + { + "type": "docs", + "section": "Trivial Changes" + }, + { + "type": "test", + "section": "Tests" + } + ] + } + } + ], + "@semantic-release/changelog", + "@semantic-release/npm", + "@semantic-release/github", + "@semantic-release/git" + ] + } +} diff --git a/node_modules/bl/test/convert.js b/node_modules/bl/test/convert.js new file mode 100644 index 0000000..9f3e235 --- /dev/null +++ b/node_modules/bl/test/convert.js @@ -0,0 +1,21 @@ +'use strict' + +const tape = require('tape') +const { BufferList, BufferListStream } = require('../') +const { Buffer } = require('buffer') + +tape('convert from BufferList to BufferListStream', (t) => { + const data = Buffer.from(`TEST-${Date.now()}`) + const bl = new BufferList(data) + const bls = new BufferListStream(bl) + t.ok(bl.slice().equals(bls.slice())) + t.end() +}) + +tape('convert from BufferListStream to BufferList', (t) => { + const data = Buffer.from(`TEST-${Date.now()}`) + const bls = new BufferListStream(data) + const bl = new BufferList(bls) + t.ok(bl.slice().equals(bls.slice())) + t.end() +}) diff --git a/node_modules/bl/test/indexOf.js b/node_modules/bl/test/indexOf.js new file mode 100644 index 0000000..62dcb01 --- /dev/null +++ b/node_modules/bl/test/indexOf.js @@ -0,0 +1,492 @@ +'use strict' + +const tape = require('tape') +const BufferList = require('../') +const { Buffer } = require('buffer') + +tape('indexOf single byte needle', (t) => { + const bl = new BufferList(['abcdefg', 'abcdefg', '12345']) + + t.equal(bl.indexOf('e'), 4) + t.equal(bl.indexOf('e', 5), 11) + t.equal(bl.indexOf('e', 12), -1) + t.equal(bl.indexOf('5'), 18) + + t.end() +}) + +tape('indexOf multiple byte needle', (t) => { + const bl = new BufferList(['abcdefg', 'abcdefg']) + + t.equal(bl.indexOf('ef'), 4) + t.equal(bl.indexOf('ef', 5), 11) + + t.end() +}) + +tape('indexOf multiple byte needles across buffer boundaries', (t) => { + const bl = new BufferList(['abcdefg', 'abcdefg']) + + t.equal(bl.indexOf('fgabc'), 5) + + t.end() +}) + +tape('indexOf takes a Uint8Array search', (t) => { + const bl = new BufferList(['abcdefg', 'abcdefg']) + const search = new Uint8Array([102, 103, 97, 98, 99]) // fgabc + + t.equal(bl.indexOf(search), 5) + + t.end() +}) + +tape('indexOf takes a buffer list search', (t) => { + const bl = new BufferList(['abcdefg', 'abcdefg']) + const search = new BufferList('fgabc') + + t.equal(bl.indexOf(search), 5) + + t.end() +}) + +tape('indexOf a zero byte needle', (t) => { + const b = new BufferList('abcdef') + const bufEmpty = Buffer.from('') + + t.equal(b.indexOf(''), 0) + t.equal(b.indexOf('', 1), 1) + t.equal(b.indexOf('', b.length + 1), b.length) + t.equal(b.indexOf('', Infinity), b.length) + t.equal(b.indexOf(bufEmpty), 0) + t.equal(b.indexOf(bufEmpty, 1), 1) + t.equal(b.indexOf(bufEmpty, b.length + 1), b.length) + t.equal(b.indexOf(bufEmpty, Infinity), b.length) + + t.end() +}) + +tape('indexOf buffers smaller and larger than the needle', (t) => { + const bl = new BufferList(['abcdefg', 'a', 'bcdefg', 'a', 'bcfgab']) + + t.equal(bl.indexOf('fgabc'), 5) + t.equal(bl.indexOf('fgabc', 6), 12) + t.equal(bl.indexOf('fgabc', 13), -1) + + t.end() +}) + +// only present in node 6+ +;(process.version.substr(1).split('.')[0] >= 6) && tape('indexOf latin1 and binary encoding', (t) => { + const b = new BufferList('abcdef') + + // test latin1 encoding + t.equal( + new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) + .indexOf('d', 0, 'latin1'), + 3 + ) + t.equal( + new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) + .indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'), + 3 + ) + t.equal( + new BufferList(Buffer.from('aa\u00e8aa', 'latin1')) + .indexOf('\u00e8', 'latin1'), + 2 + ) + t.equal( + new BufferList(Buffer.from('\u00e8', 'latin1')) + .indexOf('\u00e8', 'latin1'), + 0 + ) + t.equal( + new BufferList(Buffer.from('\u00e8', 'latin1')) + .indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'), + 0 + ) + + // test binary encoding + t.equal( + new BufferList(Buffer.from(b.toString('binary'), 'binary')) + .indexOf('d', 0, 'binary'), + 3 + ) + t.equal( + new BufferList(Buffer.from(b.toString('binary'), 'binary')) + .indexOf(Buffer.from('d', 'binary'), 0, 'binary'), + 3 + ) + t.equal( + new BufferList(Buffer.from('aa\u00e8aa', 'binary')) + .indexOf('\u00e8', 'binary'), + 2 + ) + t.equal( + new BufferList(Buffer.from('\u00e8', 'binary')) + .indexOf('\u00e8', 'binary'), + 0 + ) + t.equal( + new BufferList(Buffer.from('\u00e8', 'binary')) + .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), + 0 + ) + + t.end() +}) + +tape('indexOf the entire nodejs10 buffer test suite', (t) => { + const b = new BufferList('abcdef') + const bufA = Buffer.from('a') + const bufBc = Buffer.from('bc') + const bufF = Buffer.from('f') + const bufZ = Buffer.from('z') + + const stringComparison = 'abcdef' + + t.equal(b.indexOf('a'), 0) + t.equal(b.indexOf('a', 1), -1) + t.equal(b.indexOf('a', -1), -1) + t.equal(b.indexOf('a', -4), -1) + t.equal(b.indexOf('a', -b.length), 0) + t.equal(b.indexOf('a', NaN), 0) + t.equal(b.indexOf('a', -Infinity), 0) + t.equal(b.indexOf('a', Infinity), -1) + t.equal(b.indexOf('bc'), 1) + t.equal(b.indexOf('bc', 2), -1) + t.equal(b.indexOf('bc', -1), -1) + t.equal(b.indexOf('bc', -3), -1) + t.equal(b.indexOf('bc', -5), 1) + t.equal(b.indexOf('bc', NaN), 1) + t.equal(b.indexOf('bc', -Infinity), 1) + t.equal(b.indexOf('bc', Infinity), -1) + t.equal(b.indexOf('f'), b.length - 1) + t.equal(b.indexOf('z'), -1) + + // empty search tests + t.equal(b.indexOf(bufA), 0) + t.equal(b.indexOf(bufA, 1), -1) + t.equal(b.indexOf(bufA, -1), -1) + t.equal(b.indexOf(bufA, -4), -1) + t.equal(b.indexOf(bufA, -b.length), 0) + t.equal(b.indexOf(bufA, NaN), 0) + t.equal(b.indexOf(bufA, -Infinity), 0) + t.equal(b.indexOf(bufA, Infinity), -1) + t.equal(b.indexOf(bufBc), 1) + t.equal(b.indexOf(bufBc, 2), -1) + t.equal(b.indexOf(bufBc, -1), -1) + t.equal(b.indexOf(bufBc, -3), -1) + t.equal(b.indexOf(bufBc, -5), 1) + t.equal(b.indexOf(bufBc, NaN), 1) + t.equal(b.indexOf(bufBc, -Infinity), 1) + t.equal(b.indexOf(bufBc, Infinity), -1) + t.equal(b.indexOf(bufF), b.length - 1) + t.equal(b.indexOf(bufZ), -1) + t.equal(b.indexOf(0x61), 0) + t.equal(b.indexOf(0x61, 1), -1) + t.equal(b.indexOf(0x61, -1), -1) + t.equal(b.indexOf(0x61, -4), -1) + t.equal(b.indexOf(0x61, -b.length), 0) + t.equal(b.indexOf(0x61, NaN), 0) + t.equal(b.indexOf(0x61, -Infinity), 0) + t.equal(b.indexOf(0x61, Infinity), -1) + t.equal(b.indexOf(0x0), -1) + + // test offsets + t.equal(b.indexOf('d', 2), 3) + t.equal(b.indexOf('f', 5), 5) + t.equal(b.indexOf('f', -1), 5) + t.equal(b.indexOf('f', 6), -1) + + t.equal(b.indexOf(Buffer.from('d'), 2), 3) + t.equal(b.indexOf(Buffer.from('f'), 5), 5) + t.equal(b.indexOf(Buffer.from('f'), -1), 5) + t.equal(b.indexOf(Buffer.from('f'), 6), -1) + + t.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1) + + // test invalid and uppercase encoding + t.equal(b.indexOf('b', 'utf8'), 1) + t.equal(b.indexOf('b', 'UTF8'), 1) + t.equal(b.indexOf('62', 'HEX'), 1) + t.throws(() => b.indexOf('bad', 'enc'), TypeError) + + // test hex encoding + t.equal( + Buffer.from(b.toString('hex'), 'hex') + .indexOf('64', 0, 'hex'), + 3 + ) + t.equal( + Buffer.from(b.toString('hex'), 'hex') + .indexOf(Buffer.from('64', 'hex'), 0, 'hex'), + 3 + ) + + // test base64 encoding + t.equal( + Buffer.from(b.toString('base64'), 'base64') + .indexOf('ZA==', 0, 'base64'), + 3 + ) + t.equal( + Buffer.from(b.toString('base64'), 'base64') + .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), + 3 + ) + + // test ascii encoding + t.equal( + Buffer.from(b.toString('ascii'), 'ascii') + .indexOf('d', 0, 'ascii'), + 3 + ) + t.equal( + Buffer.from(b.toString('ascii'), 'ascii') + .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), + 3 + ) + + // test optional offset with passed encoding + t.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4) + t.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4) + + { + // test usc2 encoding + const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') + + t.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')) + t.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')) + t.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')) + t.equal(4, twoByteString.indexOf( + Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')) + t.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')) + } + + const mixedByteStringUcs2 = + Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2') + + t.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')) + t.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')) + t.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')) + + t.equal( + 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')) + t.equal( + 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')) + t.equal( + -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')) + + { + const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') + + // Test single char pattern + t.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')) + let index = twoByteString.indexOf('\u0391', 0, 'ucs2') + t.equal(2, index, `Alpha - at index ${index}`) + index = twoByteString.indexOf('\u03a3', 0, 'ucs2') + t.equal(4, index, `First Sigma - at index ${index}`) + index = twoByteString.indexOf('\u03a3', 6, 'ucs2') + t.equal(6, index, `Second Sigma - at index ${index}`) + index = twoByteString.indexOf('\u0395', 0, 'ucs2') + t.equal(8, index, `Epsilon - at index ${index}`) + index = twoByteString.indexOf('\u0392', 0, 'ucs2') + t.equal(-1, index, `Not beta - at index ${index}`) + + // Test multi-char pattern + index = twoByteString.indexOf('\u039a\u0391', 0, 'ucs2') + t.equal(0, index, `Lambda Alpha - at index ${index}`) + index = twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2') + t.equal(2, index, `Alpha Sigma - at index ${index}`) + index = twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2') + t.equal(4, index, `Sigma Sigma - at index ${index}`) + index = twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2') + t.equal(6, index, `Sigma Epsilon - at index ${index}`) + } + + const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395') + + t.equal(5, mixedByteStringUtf8.indexOf('bc')) + t.equal(5, mixedByteStringUtf8.indexOf('bc', 5)) + t.equal(5, mixedByteStringUtf8.indexOf('bc', -8)) + t.equal(7, mixedByteStringUtf8.indexOf('\u03a3')) + t.equal(-1, mixedByteStringUtf8.indexOf('\u0396')) + + // Test complex string indexOf algorithms. Only trigger for long strings. + // Long string that isn't a simple repeat of a shorter string. + let longString = 'A' + for (let i = 66; i < 76; i++) { // from 'B' to 'K' + longString = longString + String.fromCharCode(i) + longString + } + + const longBufferString = Buffer.from(longString) + + // pattern of 15 chars, repeated every 16 chars in long + let pattern = 'ABACABADABACABA' + for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { + const index = longBufferString.indexOf(pattern, i) + t.equal((i + 15) & ~0xf, index, + `Long ABACABA...-string at index ${i}`) + } + + let index = longBufferString.indexOf('AJABACA') + t.equal(510, index, `Long AJABACA, First J - at index ${index}`) + index = longBufferString.indexOf('AJABACA', 511) + t.equal(1534, index, `Long AJABACA, Second J - at index ${index}`) + + pattern = 'JABACABADABACABA' + index = longBufferString.indexOf(pattern) + t.equal(511, index, `Long JABACABA..., First J - at index ${index}`) + index = longBufferString.indexOf(pattern, 512) + t.equal( + 1535, index, `Long JABACABA..., Second J - at index ${index}`) + + // Search for a non-ASCII string in a pure ASCII string. + const asciiString = Buffer.from( + 'somethingnotatallsinisterwhichalsoworks') + t.equal(-1, asciiString.indexOf('\x2061')) + t.equal(3, asciiString.indexOf('eth', 0)) + + // Search in string containing many non-ASCII chars. + const allCodePoints = [] + for (let i = 0; i < 65536; i++) { + allCodePoints[i] = i + } + + const allCharsString = String.fromCharCode.apply(String, allCodePoints) + const allCharsBufferUtf8 = Buffer.from(allCharsString) + const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2') + + // Search for string long enough to trigger complex search with ASCII pattern + // and UC16 subject. + t.equal(-1, allCharsBufferUtf8.indexOf('notfound')) + t.equal(-1, allCharsBufferUcs2.indexOf('notfound')) + + // Needle is longer than haystack, but only because it's encoded as UTF-16 + t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1) + + t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0) + t.equal(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1) + + // Haystack has odd length, but the needle is UCS2. + t.equal(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1) + + { + // Find substrings in Utf8. + const lengths = [1, 3, 15] // Single char, simple and complex. + const indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b] + for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { + for (let i = 0; i < indices.length; i++) { + const index = indices[i] + let length = lengths[lengthIndex] + + if (index + length > 0x7F) { + length = 2 * length + } + + if (index + length > 0x7FF) { + length = 3 * length + } + + if (index + length > 0xFFFF) { + length = 4 * length + } + + const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length) + t.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)) + + const patternStringUtf8 = patternBufferUtf8.toString() + t.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)) + } + } + } + + { + // Find substrings in Usc2. + const lengths = [2, 4, 16] // Single char, simple and complex. + const indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0] + + for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { + for (let i = 0; i < indices.length; i++) { + const index = indices[i] * 2 + const length = lengths[lengthIndex] + + const patternBufferUcs2 = + allCharsBufferUcs2.slice(index, index + length) + t.equal( + index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')) + + const patternStringUcs2 = patternBufferUcs2.toString('ucs2') + t.equal( + index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')) + } + } + } + + [ + () => {}, + {}, + [] + ].forEach((val) => { + t.throws(() => b.indexOf(val), TypeError, `"${JSON.stringify(val)}" should throw`) + }) + + // Test weird offset arguments. + // The following offsets coerce to NaN or 0, searching the whole Buffer + t.equal(b.indexOf('b', undefined), 1) + t.equal(b.indexOf('b', {}), 1) + t.equal(b.indexOf('b', 0), 1) + t.equal(b.indexOf('b', null), 1) + t.equal(b.indexOf('b', []), 1) + + // The following offset coerces to 2, in other words +[2] === 2 + t.equal(b.indexOf('b', [2]), -1) + + // Behavior should match String.indexOf() + t.equal( + b.indexOf('b', undefined), + stringComparison.indexOf('b', undefined)) + t.equal( + b.indexOf('b', {}), + stringComparison.indexOf('b', {})) + t.equal( + b.indexOf('b', 0), + stringComparison.indexOf('b', 0)) + t.equal( + b.indexOf('b', null), + stringComparison.indexOf('b', null)) + t.equal( + b.indexOf('b', []), + stringComparison.indexOf('b', [])) + t.equal( + b.indexOf('b', [2]), + stringComparison.indexOf('b', [2])) + + // test truncation of Number arguments to uint8 + { + const buf = Buffer.from('this is a test') + + t.equal(buf.indexOf(0x6973), 3) + t.equal(buf.indexOf(0x697320), 4) + t.equal(buf.indexOf(0x69732069), 2) + t.equal(buf.indexOf(0x697374657374), 0) + t.equal(buf.indexOf(0x69737374), 0) + t.equal(buf.indexOf(0x69737465), 11) + t.equal(buf.indexOf(0x69737465), 11) + t.equal(buf.indexOf(-140), 0) + t.equal(buf.indexOf(-152), 1) + t.equal(buf.indexOf(0xff), -1) + t.equal(buf.indexOf(0xffff), -1) + } + + // Test that Uint8Array arguments are okay. + { + const needle = new Uint8Array([0x66, 0x6f, 0x6f]) + const haystack = new BufferList(Buffer.from('a foo b foo')) + t.equal(haystack.indexOf(needle), 2) + } + + t.end() +}) diff --git a/node_modules/bl/test/isBufferList.js b/node_modules/bl/test/isBufferList.js new file mode 100644 index 0000000..9d895d5 --- /dev/null +++ b/node_modules/bl/test/isBufferList.js @@ -0,0 +1,32 @@ +'use strict' + +const tape = require('tape') +const { BufferList, BufferListStream } = require('../') +const { Buffer } = require('buffer') + +tape('isBufferList positives', (t) => { + t.ok(BufferList.isBufferList(new BufferList())) + t.ok(BufferList.isBufferList(new BufferListStream())) + + t.end() +}) + +tape('isBufferList negatives', (t) => { + const types = [ + null, + undefined, + NaN, + true, + false, + {}, + [], + Buffer.alloc(0), + [Buffer.alloc(0)] + ] + + for (const obj of types) { + t.notOk(BufferList.isBufferList(obj)) + } + + t.end() +}) diff --git a/node_modules/bl/test/test.js b/node_modules/bl/test/test.js new file mode 100644 index 0000000..668dc17 --- /dev/null +++ b/node_modules/bl/test/test.js @@ -0,0 +1,914 @@ +// @ts-check +'use strict' + +const tape = require('tape') +const crypto = require('crypto') +const fs = require('fs') +const path = require('path') +const os = require('os') +const BufferListStream = require('../') +const { Buffer } = require('buffer') + +/** + * This typedef allows us to add _bufs to the API without declaring it publicly on types. + * @typedef { BufferListStream & { _bufs?: Buffer[] }} BufferListStreamWithPrivate + */ + +/** + * Just for typechecking in js + * @type { NodeJS.Process & { browser?: boolean }} + */ + +const process = globalThis.process + +/** @type {BufferEncoding[]} */ +const encodings = ['ascii', 'utf8', 'utf-8', 'hex', 'binary', 'base64'] + +if (process.browser) { + encodings.push( + 'ucs2', + 'ucs-2', + 'utf16le', + /** + * This alias is not in typescript typings for BufferEncoding. Still have to fix + * @see https://nodejs.org/api/buffer.html#buffers-and-character-encodings + */ + // @ts-ignore + 'utf-16le' + ) +} + +require('./indexOf') +require('./isBufferList') +require('./convert') + +tape('single bytes from single buffer', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + + t.equal(bl.length, 4) + t.equal(bl.get(-1), undefined) + t.equal(bl.get(0), 97) + t.equal(bl.get(1), 98) + t.equal(bl.get(2), 99) + t.equal(bl.get(3), 100) + t.equal(bl.get(4), undefined) + + t.end() +}) + +tape('single bytes from multiple buffers', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + bl.append(Buffer.from('efg')) + bl.append(Buffer.from('hi')) + bl.append(Buffer.from('j')) + + t.equal(bl.length, 10) + + t.equal(bl.get(0), 97) + t.equal(bl.get(1), 98) + t.equal(bl.get(2), 99) + t.equal(bl.get(3), 100) + t.equal(bl.get(4), 101) + t.equal(bl.get(5), 102) + t.equal(bl.get(6), 103) + t.equal(bl.get(7), 104) + t.equal(bl.get(8), 105) + t.equal(bl.get(9), 106) + + t.end() +}) + +tape('multi bytes from single buffer', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + + t.equal(bl.length, 4) + + t.equal(bl.slice(0, 4).toString('ascii'), 'abcd') + t.equal(bl.slice(0, 3).toString('ascii'), 'abc') + t.equal(bl.slice(1, 4).toString('ascii'), 'bcd') + t.equal(bl.slice(-4, -1).toString('ascii'), 'abc') + + t.end() +}) + +tape('multi bytes from single buffer (negative indexes)', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('buffer')) + + t.equal(bl.length, 6) + + t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe') + t.equal(bl.slice(-6, -2).toString('ascii'), 'buff') + t.equal(bl.slice(-5, -2).toString('ascii'), 'uff') + + t.end() +}) + +tape('multiple bytes from multiple buffers', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + bl.append(Buffer.from('efg')) + bl.append(Buffer.from('hi')) + bl.append(Buffer.from('j')) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') + t.equal(bl.slice(3, 6).toString('ascii'), 'def') + t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') + t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') + t.equal(bl.slice(-7, -4).toString('ascii'), 'def') + + t.end() +}) + +tape('multiple bytes from multiple buffer lists', function (t) { + const bl = new BufferListStream() + + bl.append(new BufferListStream([Buffer.from('abcd'), Buffer.from('efg')])) + bl.append(new BufferListStream([Buffer.from('hi'), Buffer.from('j')])) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + + t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') + t.equal(bl.slice(3, 6).toString('ascii'), 'def') + t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') + t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') + + t.end() +}) + +// same data as previous test, just using nested constructors +tape('multiple bytes from crazy nested buffer lists', function (t) { + const bl = new BufferListStream() + + bl.append( + new BufferListStream([ + new BufferListStream([ + new BufferListStream(Buffer.from('abc')), + Buffer.from('d'), + new BufferListStream(Buffer.from('efg')) + ]), + new BufferListStream([Buffer.from('hi')]), + new BufferListStream(Buffer.from('j')) + ]) + ) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + + t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') + t.equal(bl.slice(3, 6).toString('ascii'), 'def') + t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') + t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') + + t.end() +}) + +tape('append accepts arrays of Buffers', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abc')) + bl.append([Buffer.from('def')]) + bl.append([Buffer.from('ghi'), Buffer.from('jkl')]) + bl.append([Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz')]) + t.equal(bl.length, 26) + t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') + + t.end() +}) + +tape('append accepts arrays of Uint8Arrays', function (t) { + const bl = new BufferListStream() + + bl.append(new Uint8Array([97, 98, 99])) + bl.append([Uint8Array.from([100, 101, 102])]) + bl.append([new Uint8Array([103, 104, 105]), new Uint8Array([106, 107, 108])]) + bl.append([new Uint8Array([109, 110, 111, 112]), new Uint8Array([113, 114, 115, 116, 117]), new Uint8Array([118, 119, 120, 121, 122])]) + t.equal(bl.length, 26) + t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') + + t.end() +}) + +tape('append accepts arrays of BufferLists', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abc')) + bl.append([new BufferListStream('def')]) + bl.append( + new BufferListStream([Buffer.from('ghi'), new BufferListStream('jkl')]) + ) + bl.append([ + Buffer.from('mnop'), + new BufferListStream([Buffer.from('qrstu'), Buffer.from('vwxyz')]) + ]) + t.equal(bl.length, 26) + t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') + + t.end() +}) + +tape('append chainable', function (t) { + const bl = new BufferListStream() + + t.ok(bl.append(Buffer.from('abcd')) === bl) + t.ok(bl.append([Buffer.from('abcd')]) === bl) + t.ok(bl.append(new BufferListStream(Buffer.from('abcd'))) === bl) + t.ok(bl.append([new BufferListStream(Buffer.from('abcd'))]) === bl) + + t.end() +}) + +tape('append chainable (test results)', function (t) { + const bl = new BufferListStream('abc') + .append([new BufferListStream('def')]) + .append( + new BufferListStream([Buffer.from('ghi'), new BufferListStream('jkl')]) + ) + .append([ + Buffer.from('mnop'), + new BufferListStream([Buffer.from('qrstu'), Buffer.from('vwxyz')]) + ]) + + t.equal(bl.length, 26) + t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') + + t.end() +}) + +tape('consuming from multiple buffers', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + bl.append(Buffer.from('efg')) + bl.append(Buffer.from('hi')) + bl.append(Buffer.from('j')) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + + bl.consume(3) + t.equal(bl.length, 7) + t.equal(bl.slice(0, 7).toString('ascii'), 'defghij') + + bl.consume(2) + t.equal(bl.length, 5) + t.equal(bl.slice(0, 5).toString('ascii'), 'fghij') + + bl.consume(1) + t.equal(bl.length, 4) + t.equal(bl.slice(0, 4).toString('ascii'), 'ghij') + + bl.consume(1) + t.equal(bl.length, 3) + t.equal(bl.slice(0, 3).toString('ascii'), 'hij') + + bl.consume(2) + t.equal(bl.length, 1) + t.equal(bl.slice(0, 1).toString('ascii'), 'j') + + t.end() +}) + +tape('complete consumption', function (t) { + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream() + + bl.append(Buffer.from('a')) + bl.append(Buffer.from('b')) + + bl.consume(2) + + t.equal(bl.length, 0) + t.equal(bl._bufs.length, 0) + + t.end() +}) + +tape('test readUInt8 / readInt8', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(3) + const bl = new BufferListStream() + + buf1[0] = 0x1 + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt8(), 0x1) + t.equal(bl.readUInt8(2), 0x3) + t.equal(bl.readInt8(2), 0x3) + t.equal(bl.readUInt8(3), 0x4) + t.equal(bl.readInt8(3), 0x4) + t.equal(bl.readUInt8(4), 0x23) + t.equal(bl.readInt8(4), 0x23) + t.equal(bl.readUInt8(5), 0x42) + t.equal(bl.readInt8(5), 0x42) + + t.end() +}) + +tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(3) + const bl = new BufferListStream() + + buf1[0] = 0x1 + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt16BE(), 0x0100) + t.equal(bl.readUInt16LE(), 0x0001) + t.equal(bl.readUInt16BE(2), 0x0304) + t.equal(bl.readUInt16LE(2), 0x0403) + t.equal(bl.readInt16BE(2), 0x0304) + t.equal(bl.readInt16LE(2), 0x0403) + t.equal(bl.readUInt16BE(3), 0x0423) + t.equal(bl.readUInt16LE(3), 0x2304) + t.equal(bl.readInt16BE(3), 0x0423) + t.equal(bl.readInt16LE(3), 0x2304) + t.equal(bl.readUInt16BE(4), 0x2342) + t.equal(bl.readUInt16LE(4), 0x4223) + t.equal(bl.readInt16BE(4), 0x2342) + t.equal(bl.readInt16LE(4), 0x4223) + + t.end() +}) + +tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(3) + const bl = new BufferListStream() + + buf1[0] = 0x1 + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt32BE(), 0x01000304) + t.equal(bl.readUInt32LE(), 0x04030001) + t.equal(bl.readUInt32BE(2), 0x03042342) + t.equal(bl.readUInt32LE(2), 0x42230403) + t.equal(bl.readInt32BE(2), 0x03042342) + t.equal(bl.readInt32LE(2), 0x42230403) + + t.end() +}) + +tape('test readUIntLE / readUIntBE / readIntLE / readIntBE', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(3) + const bl = new BufferListStream() + + buf2[0] = 0x2 + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + buf3[2] = 0x61 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUIntBE(1, 1), 0x02) + t.equal(bl.readUIntBE(1, 2), 0x0203) + t.equal(bl.readUIntBE(1, 3), 0x020304) + t.equal(bl.readUIntBE(1, 4), 0x02030423) + t.equal(bl.readUIntBE(1, 5), 0x0203042342) + t.equal(bl.readUIntBE(1, 6), 0x020304234261) + t.equal(bl.readUIntLE(1, 1), 0x02) + t.equal(bl.readUIntLE(1, 2), 0x0302) + t.equal(bl.readUIntLE(1, 3), 0x040302) + t.equal(bl.readUIntLE(1, 4), 0x23040302) + t.equal(bl.readUIntLE(1, 5), 0x4223040302) + t.equal(bl.readUIntLE(1, 6), 0x614223040302) + t.equal(bl.readIntBE(1, 1), 0x02) + t.equal(bl.readIntBE(1, 2), 0x0203) + t.equal(bl.readIntBE(1, 3), 0x020304) + t.equal(bl.readIntBE(1, 4), 0x02030423) + t.equal(bl.readIntBE(1, 5), 0x0203042342) + t.equal(bl.readIntBE(1, 6), 0x020304234261) + t.equal(bl.readIntLE(1, 1), 0x02) + t.equal(bl.readIntLE(1, 2), 0x0302) + t.equal(bl.readIntLE(1, 3), 0x040302) + t.equal(bl.readIntLE(1, 4), 0x23040302) + t.equal(bl.readIntLE(1, 5), 0x4223040302) + t.equal(bl.readIntLE(1, 6), 0x614223040302) + + t.end() +}) + +tape('test readFloatLE / readFloatBE', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(3) + const bl = new BufferListStream() + + buf1[0] = 0x01 + buf2[1] = 0x00 + buf2[2] = 0x00 + buf3[0] = 0x80 + buf3[1] = 0x3f + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + const canonical = Buffer.concat([buf1, buf2, buf3]) + t.equal(bl.readFloatLE(), canonical.readFloatLE()) + t.equal(bl.readFloatBE(), canonical.readFloatBE()) + t.equal(bl.readFloatLE(2), canonical.readFloatLE(2)) + t.equal(bl.readFloatBE(2), canonical.readFloatBE(2)) + + t.end() +}) + +tape('test readDoubleLE / readDoubleBE', function (t) { + const buf1 = Buffer.alloc(1) + const buf2 = Buffer.alloc(3) + const buf3 = Buffer.alloc(10) + const bl = new BufferListStream() + + buf1[0] = 0x01 + buf2[1] = 0x55 + buf2[2] = 0x55 + buf3[0] = 0x55 + buf3[1] = 0x55 + buf3[2] = 0x55 + buf3[3] = 0x55 + buf3[4] = 0xd5 + buf3[5] = 0x3f + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + const canonical = Buffer.concat([buf1, buf2, buf3]) + t.equal(bl.readDoubleBE(), canonical.readDoubleBE()) + t.equal(bl.readDoubleLE(), canonical.readDoubleLE()) + t.equal(bl.readDoubleBE(2), canonical.readDoubleBE(2)) + t.equal(bl.readDoubleLE(2), canonical.readDoubleLE(2)) + + t.end() +}) + +tape('test toString', function (t) { + const bl = new BufferListStream() + + bl.append(Buffer.from('abcd')) + bl.append(Buffer.from('efg')) + bl.append(Buffer.from('hi')) + bl.append(Buffer.from('j')) + + t.equal(bl.toString('ascii', 0, 10), 'abcdefghij') + t.equal(bl.toString('ascii', 3, 10), 'defghij') + t.equal(bl.toString('ascii', 3, 6), 'def') + t.equal(bl.toString('ascii', 3, 8), 'defgh') + t.equal(bl.toString('ascii', 5, 10), 'fghij') + + t.end() +}) + +tape('test toString encoding', function (t) { + const bl = new BufferListStream() + const b = Buffer.from('abcdefghij\xff\x00') + + bl.append(Buffer.from('abcd')) + bl.append(Buffer.from('efg')) + bl.append(Buffer.from('hi')) + bl.append(Buffer.from('j')) + bl.append(Buffer.from('\xff\x00')) + + encodings.forEach(function (enc) { + t.equal(bl.toString(enc), b.toString(enc), enc) + }) + + t.end() +}) + +tape('uninitialized memory', function (t) { + const secret = crypto.randomBytes(256) + for (let i = 0; i < 1e6; i++) { + const clone = Buffer.from(secret) + const bl = new BufferListStream() + bl.append(Buffer.from('a')) + bl.consume(-1024) + const buf = bl.slice(1) + if (buf.indexOf(clone) !== -1) { + t.fail(`Match (at ${i})`) + break + } + } + t.end() +}) + +!process.browser && tape('test stream', function (t) { + const random = crypto.randomBytes(65534) + + const bl = new BufferListStream((err, buf) => { + t.ok(Buffer.isBuffer(buf)) + t.ok(err === null) + t.ok(random.equals(bl.slice())) + t.ok(random.equals(buf.slice())) + + bl.pipe(fs.createWriteStream(path.join(os.tmpdir(), 'bl_test_rnd_out.dat'))) + .on('close', function () { + const rndhash = crypto.createHash('md5').update(random).digest('hex') + const md5sum = crypto.createHash('md5') + const s = fs.createReadStream(path.join(os.tmpdir(), 'bl_test_rnd_out.dat')) + + s.on('data', md5sum.update.bind(md5sum)) + s.on('end', function () { + t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!') + t.end() + }) + }) + }) + + fs.writeFileSync(path.join(os.tmpdir(), 'bl_test_rnd.dat'), random) + fs.createReadStream(path.join(os.tmpdir(), 'bl_test_rnd.dat')).pipe(bl) +}) + +tape('instantiation with Buffer', function (t) { + const buf = crypto.randomBytes(1024) + const buf2 = crypto.randomBytes(1024) + let b = BufferListStream(buf) + + t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer') + b = BufferListStream([buf, buf2]) + t.equal(b.slice().toString('hex'), Buffer.concat([buf, buf2]).toString('hex'), 'same buffer') + + t.end() +}) + +tape('test String appendage', function (t) { + const bl = new BufferListStream() + const b = Buffer.from('abcdefghij\xff\x00') + + bl.append('abcd') + bl.append('efg') + bl.append('hi') + bl.append('j') + bl.append('\xff\x00') + + encodings.forEach(function (enc) { + t.equal(bl.toString(enc), b.toString(enc)) + }) + + t.end() +}) + +tape('test Number appendage', function (t) { + const bl = new BufferListStream() + const b = Buffer.from('1234567890') + + bl.append(1234) + bl.append(567) + bl.append(89) + bl.append(0) + + encodings.forEach(function (enc) { + t.equal(bl.toString(enc), b.toString(enc)) + }) + + t.end() +}) + +tape('write nothing, should get empty buffer', function (t) { + t.plan(3) + BufferListStream(function (err, data) { + t.notOk(err, 'no error') + t.ok(Buffer.isBuffer(data), 'got a buffer') + t.equal(0, data.length, 'got a zero-length buffer') + t.end() + }).end() +}) + +tape('unicode string', function (t) { + t.plan(2) + + const inp1 = '\u2600' + const inp2 = '\u2603' + const exp = inp1 + ' and ' + inp2 + const bl = BufferListStream() + + bl.write(inp1) + bl.write(' and ') + bl.write(inp2) + t.equal(exp, bl.toString()) + t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex')) +}) + +tape('should emit finish', function (t) { + const source = BufferListStream() + const dest = BufferListStream() + + source.write('hello') + source.pipe(dest) + + dest.on('finish', function () { + t.equal(dest.toString('utf8'), 'hello') + t.end() + }) +}) + +tape('basic copy', function (t) { + const buf = crypto.randomBytes(1024) + const buf2 = Buffer.alloc(1024) + const b = BufferListStream(buf) + + b.copy(buf2) + t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') + + t.end() +}) + +tape('copy after many appends', function (t) { + const buf = crypto.randomBytes(512) + const buf2 = Buffer.alloc(1024) + const b = BufferListStream(buf) + + b.append(buf) + b.copy(buf2) + t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') + + t.end() +}) + +tape('copy at a precise position', function (t) { + const buf = crypto.randomBytes(1004) + const buf2 = Buffer.alloc(1024) + const b = BufferListStream(buf) + + b.copy(buf2, 20) + t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer') + + t.end() +}) + +tape('copy starting from a precise location', function (t) { + const buf = crypto.randomBytes(10) + const buf2 = Buffer.alloc(5) + const b = BufferListStream(buf) + + b.copy(buf2, 0, 5) + t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer') + + t.end() +}) + +tape('copy in an interval', function (t) { + const rnd = crypto.randomBytes(10) + const b = BufferListStream(rnd) // put the random bytes there + const actual = Buffer.alloc(3) + const expected = Buffer.alloc(3) + + rnd.copy(expected, 0, 5, 8) + b.copy(actual, 0, 5, 8) + + t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer') + + t.end() +}) + +tape('copy an interval between two buffers', function (t) { + const buf = crypto.randomBytes(10) + const buf2 = Buffer.alloc(10) + const b = BufferListStream(buf) + + b.append(buf) + b.copy(buf2, 0, 5, 15) + + t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer') + + t.end() +}) + +tape('shallow slice across buffer boundaries', function (t) { + const bl = new BufferListStream(['First', 'Second', 'Third']) + + t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh') + + t.end() +}) + +tape('shallow slice within single buffer', function (t) { + t.plan(2) + + const bl = new BufferListStream(['First', 'Second', 'Third']) + + t.equal(bl.shallowSlice(5, 10).toString(), 'Secon') + t.equal(bl.shallowSlice(7, 10).toString(), 'con') + + t.end() +}) + +tape('shallow slice single buffer', function (t) { + t.plan(3) + + const bl = new BufferListStream(['First', 'Second', 'Third']) + + t.equal(bl.shallowSlice(0, 5).toString(), 'First') + t.equal(bl.shallowSlice(5, 11).toString(), 'Second') + t.equal(bl.shallowSlice(11, 16).toString(), 'Third') +}) + +tape('shallow slice with negative or omitted indices', function (t) { + t.plan(4) + + const bl = new BufferListStream(['First', 'Second', 'Third']) + + t.equal(bl.shallowSlice().toString(), 'FirstSecondThird') + t.equal(bl.shallowSlice(5).toString(), 'SecondThird') + t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh') + t.equal(bl.shallowSlice(-8).toString(), 'ondThird') +}) + +tape('shallow slice does not make a copy', function (t) { + t.plan(1) + + const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] + const bl = new BufferListStream(buffers).shallowSlice(5, -3) + + buffers[1].fill('h') + buffers[2].fill('h') + + t.equal(bl.toString(), 'hhhhhhhh') +}) + +tape('shallow slice with 0 length', function (t) { + t.plan(1) + + const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] + const bl = (new BufferListStream(buffers)).shallowSlice(0, 0) + + t.equal(bl.length, 0) +}) + +tape('shallow slice with 0 length from middle', function (t) { + t.plan(1) + + const buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] + const bl = (new BufferListStream(buffers)).shallowSlice(10, 10) + + t.equal(bl.length, 0) +}) + +tape('duplicate', function (t) { + t.plan(2) + + const bl = new BufferListStream('abcdefghij\xff\x00') + const dup = bl.duplicate() + + t.equal(bl.prototype, dup.prototype) + t.equal(bl.toString('hex'), dup.toString('hex')) +}) + +tape('destroy no pipe', function (t) { + t.plan(2) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream('alsdkfja;lsdkfja;lsdk') + + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) +}) + +tape('destroy with error', function (t) { + t.plan(3) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream('alsdkfja;lsdkfja;lsdk') + const err = new Error('kaboom') + + bl.destroy(err) + bl.on('error', function (_err) { + t.equal(_err, err) + }) + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) +}) + +!process.browser && tape('destroy with pipe before read end', function (t) { + t.plan(2) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream() + fs.createReadStream(path.join(__dirname, '/test.js')) + .pipe(bl) + + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) +}) + +!process.browser && tape('destroy with pipe before read end with race', function (t) { + t.plan(2) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream() + + fs.createReadStream(path.join(__dirname, '/test.js')) + .pipe(bl) + + setTimeout(function () { + bl.destroy() + setTimeout(function () { + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) + }, 500) + }, 500) +}) + +!process.browser && tape('destroy with pipe after read end', function (t) { + t.plan(2) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream() + fs.createReadStream(path.join(__dirname, '/test.js')) + .on('end', onEnd) + .pipe(bl) + + function onEnd () { + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) + } +}) + +!process.browser && tape('destroy with pipe while writing to a destination', function (t) { + t.plan(4) + + /** @type {BufferListStreamWithPrivate} */ + const bl = new BufferListStream() + const ds = new BufferListStream() + + fs.createReadStream(path.join(__dirname, '/test.js')) + .on('end', onEnd) + .pipe(bl) + + function onEnd () { + bl.pipe(ds) + + setTimeout(function () { + bl.destroy() + + t.equals(bl._bufs.length, 0) + t.equals(bl.length, 0) + + ds.destroy() + + t.equals(bl._bufs.length, 0) + t.equals(bl.length, 0) + }, 100) + } +}) + +!process.browser && tape('handle error', function (t) { + t.plan(2) + + fs.createReadStream('/does/not/exist').pipe(BufferListStream(function (err, data) { + t.ok(err instanceof Error, 'has error') + t.notOk(data, 'no data') + })) +}) diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +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. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +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(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + 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) }); + } + + 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; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..a18faa8 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,47 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.11", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/broadcast-channel/.github/FUNDING.yml b/node_modules/broadcast-channel/.github/FUNDING.yml new file mode 100644 index 0000000..2b2ef53 --- /dev/null +++ b/node_modules/broadcast-channel/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: pubkey diff --git a/node_modules/broadcast-channel/.github/README.md b/node_modules/broadcast-channel/.github/README.md new file mode 100644 index 0000000..31060ca --- /dev/null +++ b/node_modules/broadcast-channel/.github/README.md @@ -0,0 +1,262 @@ + +

+ + + +

+ +

BroadcastChannel

+

+ A BroadcastChannel to send data between different browser-tabs or nodejs-processes +
+ + LeaderElection over the channels
+

+ +

+ + follow on Twitter +

+ +![demo.gif](../docs/files/demo.gif) + +* * * + +A BroadcastChannel that allows you to send data between different browser-tabs or nodejs-processes. + +- It works completely **client-side** and **offline**. +- Tested on **old browsers**, **new browsers**, **WebWorkers**, **Iframes** and **NodeJs** + +This behaves similar to the [BroadcastChannel-API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API) which is currently only featured in [some browsers](https://caniuse.com/#feat=broadcastchannel). + +## Using the BroadcastChannel + +```bash +npm install --save broadcast-channel +``` + +#### Create a channel in one tab/process and send a message. + +```ts +import { BroadcastChannel } from 'broadcast-channel'; +const channel = new BroadcastChannel('foobar'); +channel.postMessage('I am not alone'); +``` + +#### Create a channel with the same name in another tab/process and recieve messages. + +```ts +import { BroadcastChannel } from 'broadcast-channel'; +const channel = new BroadcastChannel('foobar'); +channel.onmessage = msg => console.dir(msg); +// > 'I am not alone' +``` + + +#### Add and remove multiple eventlisteners + +```ts +import { BroadcastChannel } from 'broadcast-channel'; +const channel = new BroadcastChannel('foobar'); + +const handler = msg => console.log(msg); +channel.addEventListener('message', handler); + +// remove it +channel.removeEventListener('message', handler); +``` + +#### Close the channel if you do not need it anymore. +Returns a `Promise` that resolved when everything is processed. + +```js +await channel.close(); +``` + +#### Set options when creating a channel (optional): + +```js +const options = { + type: 'localstorage', // (optional) enforce a type, oneOf['native', 'idb', 'localstorage', 'node'] + webWorkerSupport: true; // (optional) set this to false if you know that your channel will never be used in a WebWorker (increases performance) +}; +const channel = new BroadcastChannel('foobar', options); +``` + +#### Create a typed channel in typescript: + +```typescript +import { BroadcastChannel } from 'broadcast-channel'; +declare type Message = { + foo: string; +}; +const channel: BroadcastChannel = new BroadcastChannel('foobar'); +channel.postMessage({ + foo: 'bar' +}); +``` + +#### Enforce a options globally + +When you use this module in a test-suite, it is recommended to enforce the fast `simulate` method on all channels so your tests run faster. You can do this with `enforceOptions()`. If you set this, all channels have the enforced options, no mather what options are given in the constructor. + +```typescript +import { enforceOptions } from 'broadcast-channel'; + +// enforce this config for all channels +enforceOptions({ + type: 'simulate' +}); + +// reset the enforcement +enforceOptions(null); +``` + + +#### Clear tmp-folder: +When used in NodeJs, the BroadcastChannel will communicate with other processes over filesystem based sockets. +When you create a huge amount of channels, like you would do when running unit tests, you might get problems because there are too many folders in the tmp-directory. Calling `BroadcastChannel.clearNodeFolder()` will clear the tmp-folder and it is recommended to run this at the beginning of your test-suite. + +```typescript +import { clearNodeFolder } from 'broadcast-channel'; +// jest +beforeAll(async () => { + const hasRun = await clearNodeFolder(); + console.log(hasRun); // > true on NodeJs, false on Browsers +}) +``` + +```typescript +import { clearNodeFolder } from 'broadcast-channel'; +// mocha +before(async () => { + const hasRun = await clearNodeFolder(); + console.log(hasRun); // > true on NodeJs, false on Browsers +}) +``` + +#### Handling IndexedDB onclose events + +IndexedDB databases can close unexpectedly for various reasons. This could happen, for example, if the underlying storage is removed or if the user clears the database in the browser's history preferences. Most often we have seen this happen in Mobile Safari. By default, we let the connection close and stop polling for changes. If you would like to continue listening you should close BroadcastChannel and create a new one. + +Example of how you might do this: + +```typescript +import { BroadcastChannel } from 'broadcast-channel'; + +let channel; + +const createChannel = () => { + channel = new BroadcastChannel(CHANNEL_NAME, { + idb: { + onclose: () => { + // the onclose event is just the IndexedDB closing. + // you should also close the channel before creating + // a new one. + channel.close(); + createChannel(); + }, + }, + }); + + channel.onmessage = message => { + // handle message + }; +}; +``` + +## Methods: + +Depending in which environment this is used, a proper method is automatically selected to ensure it always works. + +| Method | Used in | Description | +| ---------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Native** | [Modern Browsers](https://caniuse.com/broadcastchannel) | If the browser supports the BroadcastChannel-API, this method will be used because it is the fastest | +| **IndexedDB** | [Browsers with WebWorkers](https://caniuse.com/#feat=indexeddb) | If there is no native BroadcastChannel support, the IndexedDB method is used because it supports messaging between browser-tabs, iframes and WebWorkers | +| **LocalStorage** | [Older Browsers](https://caniuse.com/#feat=namevalue-storage) | In older browsers that do not support IndexedDb, a localstorage-method is used | +| **Sockets** | NodeJs | In NodeJs the communication is handled by sockets that send each other messages | +| **Simulate** | none per default | This method simulates the behavior of the other methods but only runs in the current process without sharing data between processes. Use this method in your test-suite because it is much faster. | + + + +## Using the LeaderElection + +This module also comes with a leader-election which can be used so elect a leader between different BroadcastChannels. +For example if you have a stable connection from the frontend to your server, you can use the LeaderElection to save server-side performance by only connecting once, even if the user has opened your website in multiple tabs. + +In this example the leader is marked with the crown ♛: +![leader-election.gif](../docs/files/leader-election.gif) + + +Create a channel and an elector. + +```ts +import { + BroadcastChannel, + createLeaderElection +} from 'broadcast-channel'; +const channel = new BroadcastChannel('foobar'); +const elector = createLeaderElection(channel); +``` + +Wait until the elector becomes leader. + +```js +import { createLeaderElection } from 'broadcast-channel'; +const elector = createLeaderElection(channel); +elector.awaitLeadership().then(()=> { + console.log('this tab is now leader'); +}) +``` + +If more than one tab is becoming leader adjust `LeaderElectionOptions` configuration. + +```js +import { createLeaderElection } from 'broadcast-channel'; +const elector = createLeaderElection(channel, { + fallbackInterval: 2000, // optional configuration for how often will renegotiation for leader occur + responseTime: 1000, // optional configuration for how long will instances have to respond +}); +elector.awaitLeadership().then(()=> { + console.log('this tab is now leader'); +}) +``` + +Let the leader die. (automatically happens if the tab is closed or the process exits). + +```js +const elector = createLeaderElection(channel); +await elector.die(); +``` + +Handle duplicate leaders. This can happen on rare occurences like when the [CPU is on 100%](https://github.com/pubkey/broadcast-channel/issues/385) for longer time, or the browser [has throttled the javascript timers](https://github.com/pubkey/broadcast-channel/issues/414). + +```js +const elector = createLeaderElection(channel); +elector.onduplicate = () => { + alert('have duplicate leaders!'); +} +``` + + +## What this is + +This module is optimised for: + +- **low latency**: When you postMessage on one channel, it should take as low as possible time until other channels recieve the message. +- **lossless**: When you send a message, it should be impossible that the message is lost before other channels recieved it +- **low idle workload**: During the time when no messages are send, there should be a low processor footprint. + +## What this is not + +- This is not a polyfill. Do not set this module to `window.BroadcastChannel`. This implementation behaves similiar to the [BroadcastChannel-Standard](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API) with these limitations: + - You can only send data that can be `JSON.stringify`-ed. + - While the offical API emits [onmessage-events](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel/onmessage), this module directly emitts the data which was posted +- This is not a replacement for a message queue. If you use this in NodeJs and want send more than 50 messages per second, you should use proper [IPC-Tooling](https://en.wikipedia.org/wiki/Message_queue) + + +## Browser Support +I have tested this in all browsers that I could find. For ie8 and ie9 you must transpile the code before you can use this. If you want to know if this works with your browser, [open the demo page](https://pubkey.github.io/broadcast-channel/e2e.html). + +## Thanks +Thanks to [Hemanth.HM](https://github.com/hemanth) for the module name. diff --git a/node_modules/broadcast-channel/.github/workflows/main.yml b/node_modules/broadcast-channel/.github/workflows/main.yml new file mode 100644 index 0000000..a0e589f --- /dev/null +++ b/node_modules/broadcast-channel/.github/workflows/main.yml @@ -0,0 +1,91 @@ +# This is a basic workflow to help you get started with Actions + +name: CI + +# Controls when the action will run. +on: + # Triggers the workflow on push or pull request events but only for the master branch + push: + branches: [ master ] + pull_request: + branches: [ master ] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + all: + # The type of runner that the job will run on + runs-on: ubuntu-18.04 + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + # https://docs.github.com/en/free-pro-team@latest/actions/guides/caching-dependencies-to-speed-up-workflows + - name: Reuse npm cache folder + uses: actions/cache@v2 + env: + cache-name: cache-node-modules + with: + # reuse the npm-cache and some node_modules folders + path: | + ~/.npm + ./node_modules + ./test-electron/node_modules + # invalidate cache when any package.json changes + key: ${{ runner.os }}-npm-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} + restore-keys: | + ${{ runner.os }}-npm-${{ env.cache-name }}- + ${{ runner.os }}-npm- + ${{ runner.os }}- + + # install + - name: install node modules + run: npm install + + - name: build + run: npm run build + + - name: check build size webpack + run: npm run size:webpack + + - name: check build size browserify + run: npm run size:browserify + + - name: check build size rollup + run: npm run size:rollup + + - name: code format + run: npm run lint + + - name: test typings + run: npm run test:typings + + - name: test node + run: npm run test:node + + - name: test browser + uses: GabrielBB/xvfb-action@v1 + with: + working-directory: ./ #optional + run: npm run test:browser + + - name: test performance + run: npm run test:performance + + - name: test e2e + uses: GabrielBB/xvfb-action@v1 + with: + working-directory: ./ #optional + run: npm run test:e2e + +# TODO this does not work atm. fix this. +# - name: test electron +# uses: GabrielBB/xvfb-action@v1 +# with: +# working-directory: ./test-electron +# run: npm install --depth 0 --silent && npm run test diff --git a/node_modules/broadcast-channel/CHANGELOG.md b/node_modules/broadcast-channel/CHANGELOG.md new file mode 100644 index 0000000..2844a27 --- /dev/null +++ b/node_modules/broadcast-channel/CHANGELOG.md @@ -0,0 +1,41 @@ +# CHANGELOG + +## X.X.X (comming soon) + +## 3.7.0 (13 June 2021) + +Other: + - Moved `ObliviousSet` into [its own npm module](https://www.npmjs.com/package/oblivious-set) + +## 3.6.0 (19 May 2021) + +Features: + - Added `BroadcastChannel.isClosed` [#544](https://github.com/pubkey/broadcast-channel/issues/544) + +Other: + - Updated dependencies to work with newer node versions + +## 3.5.3 (11 March 2021) + +Bugfixes: + - Fixed broken typings + +## 3.5.2 (11 March 2021) + +Bugfixes: + - `BroadcastChannel.close()` waits for all ongoing message sending to be finished before resolving. + +## 3.5.0 (11 March 2021) + +Features: + - Added `LeaderElector.onduplicate` + +## 3.4.0 (24 January 2021) + +Bugfixes: + - fix cursor error in Safari [#420](https://github.com/pubkey/broadcast-channel/pull/420) + +## 3.3.0 (20 October 2020) + +Bugfixes: + - `new BroadcastChannel().close()` should not resolve before all cleanup is done [#348](https://github.com/pubkey/broadcast-channel/pull/348) diff --git a/node_modules/broadcast-channel/LICENSE b/node_modules/broadcast-channel/LICENSE new file mode 100644 index 0000000..42ff19a --- /dev/null +++ b/node_modules/broadcast-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Daniel Meyer + +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. diff --git a/node_modules/broadcast-channel/README.md b/node_modules/broadcast-channel/README.md new file mode 100644 index 0000000..fdd2b8e --- /dev/null +++ b/node_modules/broadcast-channel/README.md @@ -0,0 +1,36 @@ + + +

+ + + +

+ +

BroadcastChannel

+

+ A BroadcastChannel that works in old browsers, new browsers, WebWorkers and NodeJs +
+ + LeaderElection over the channels +

+ +

+ + follow on Twitter +

+ +![demo.gif](docs/files/demo.gif) + +* * * + +A BroadcastChannel that allows you to send data between different browser-tabs or nodejs-processes. +And a LeaderElection over the channels. + +# [Read the full documentation on github](https://github.com/pubkey/broadcast-channel) diff --git a/node_modules/broadcast-channel/package.json b/node_modules/broadcast-channel/package.json new file mode 100644 index 0000000..4b78dfa --- /dev/null +++ b/node_modules/broadcast-channel/package.json @@ -0,0 +1,131 @@ +{ + "name": "broadcast-channel", + "version": "3.7.0", + "description": "A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers and NodeJs", + "homepage": "https://github.com/pubkey/broadcast-channel#readme", + "keywords": [ + "broadcast-channel", + "broadcastchannel", + "broadcast", + "polyfill", + "localstorage", + "indexeddb", + "postMessage", + "crosstab", + "ipc", + "leader-election" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/pubkey/broadcast-channel.git" + }, + "author": "pubkey", + "license": "MIT", + "bugs": { + "url": "https://github.com/pubkey/broadcast-channel/issues" + }, + "main": "./dist/lib/index.es5.js", + "jsnext:main": "./dist/es/index.js", + "module": "./dist/es/index.js", + "sideEffects": false, + "types": "./types/index.d.ts", + "scripts": { + "test": "echo \"RUN ALL:\" && npm run test:node && npm run test:browser && npm run test:e2e", + "test:node": "npm run build && mocha ./test/index.test.js -b --timeout 6000 --exit", + "test:node:loop": "npm run test:node && npm run test:node:loop", + "test:browser": "npm run build && karma start ./config/karma.conf.js --single-run", + "test:e2e": "concurrently \"npm run docs:serve\" \"sleep 20 && testcafe -b && testcafe chrome -e test/e2e.test.js --hostname localhost\" --kill-others --success first", + "test:typings": "npm run build && mocha ./test/typings.test.js -b --timeout 12000 --exit", + "test:performance": "npm run build && mocha ./test/performance.test.js -b --timeout 24000 --exit", + "test:simple": "npm run build && node ./test_tmp/simple.test.js", + "test:electron": "(cd ./test-electron && npm run test)", + "size:prewebpack": "npm run build && cross-env NODE_ENV=build webpack --config ./config/webpack.config.js", + "size:webpack": "npm run size:prewebpack && echo \"Build-Size Webpack (minified+gzip):\" && gzip-size --raw ./test_tmp/webpack.bundle.js", + "size:browserify": "npm run build && rimraf test_tmp/browserify.js && browserify --no-builtins dist/lib/browserify.index.js > test_tmp/browserify.js && uglifyjs --compress --mangle --output test_tmp/browserify.min.js -- test_tmp/browserify.js && echo \"Build-Size browserify (minified+gzip):\" && gzip-size --raw test_tmp/browserify.min.js", + "size:rollup": "npm run build && rollup --config ./config/rollup.config.js && echo \"Build-Size Rollup (minified+gzip):\" && gzip-size --raw ./test_tmp/rollup.bundle.js", + "lint": "eslint src test config", + "clear": "rimraf -rf ./dist && rimraf -rf ./gen", + "build:es6": "rimraf -rf dist/es && cross-env NODE_ENV=es6 babel src --out-dir dist/es", + "build:es5": "cross-env NODE_ENV=es5 babel src --out-dir dist/lib", + "build:test": "cross-env NODE_ENV=es5 babel test --out-dir test_tmp", + "build:index": "browserify test_tmp/scripts/index.js > docs/index.js", + "build:browser": "browserify test_tmp/scripts/e2e.js > docs/e2e.js", + "build:worker": "browserify test_tmp/scripts/worker.js > docs/worker.js", + "build:iframe": "browserify test_tmp/scripts/iframe.js > docs/iframe.js", + "build:leader-iframe": "browserify test_tmp/scripts/leader-iframe.js > docs/leader-iframe.js", + "build:lib-browser": "browserify dist/lib/browserify.index.js > dist/lib/browser.js", + "build:lib-browser:min": "uglifyjs --compress --mangle --output dist/lib/browser.min.js -- dist/lib/browser.js", + "build": "npm run clear && concurrently \"npm run build:es6\" \"npm run build:es5\" \"npm run build:test\" && concurrently \"npm run build:index\" \"npm run build:browser\" \"npm run build:worker\" \"npm run build:iframe\" \"npm run build:leader-iframe\" && npm run build:lib-browser && npm run build:lib-browser:min", + "build:min": "uglifyjs --compress --mangle --output dist/lib/browserify.min.js -- dist/lib/browserify.index.js", + "docs:only": "http-server ./docs --silent", + "docs:serve": "npm run build && echo \"Open http://localhost:8080/\" && npm run docs:only" + }, + "pre-commit": [ + "lint" + ], + "dependencies": { + "@babel/runtime": "^7.7.2", + "detect-node": "^2.1.0", + "js-sha3": "0.8.0", + "microseconds": "0.2.0", + "nano-time": "1.0.0", + "oblivious-set": "1.0.0", + "rimraf": "3.0.2", + "unload": "2.2.0" + }, + "devDependencies": { + "@babel/cli": "7.14.3", + "@babel/core": "7.14.3", + "@babel/plugin-proposal-object-rest-spread": "7.14.4", + "@babel/plugin-transform-member-expression-literals": "7.12.13", + "@babel/plugin-transform-property-literals": "7.12.13", + "@babel/plugin-transform-runtime": "7.14.3", + "@babel/polyfill": "7.12.1", + "@babel/preset-env": "7.14.4", + "@babel/types": "7.14.4", + "@types/core-js": "2.5.4", + "assert": "2.0.0", + "async-test-util": "1.7.3", + "browserify": "17.0.0", + "child-process-promise": "2.2.1", + "clone": "2.1.2", + "concurrently": "6.2.0", + "convert-hrtime": "5.0.0", + "copyfiles": "2.4.1", + "cross-env": "7.0.3", + "eslint": "7.27.0", + "gzip-size-cli": "5.0.0", + "http-server": "0.12.3", + "jest": "27.0.3", + "karma": "6.3.3", + "karma-babel-preprocessor": "8.0.1", + "karma-browserify": "8.0.0", + "karma-chrome-launcher": "3.1.0", + "karma-coverage": "2.0.3", + "karma-detect-browsers": "2.3.3", + "karma-edge-launcher": "0.4.2", + "karma-firefox-launcher": "2.1.1", + "karma-ie-launcher": "1.0.0", + "karma-mocha": "2.0.1", + "karma-opera-launcher": "1.0.0", + "karma-safari-launcher": "1.0.0", + "mocha": "8.4.0", + "pre-commit": "1.2.2", + "random-int": "3.0.0", + "random-token": "0.0.8", + "rollup": "2.50.5", + "rollup-plugin-node-resolve": "5.2.0", + "rollup-plugin-uglify": "6.0.4", + "testcafe": "1.14.2", + "ts-node": "10.0.0", + "typescript": "4.3.2", + "watchify": "4.0.0", + "webpack": "5.38.1", + "webpack-cli": "4.7.0" + }, + "browser": { + "./src/methods/node.js": false, + "./dist/es/methods/node.js": false, + "./dist/lib/methods/node.js": false + } +} diff --git a/node_modules/broadcast-channel/src/broadcast-channel.js b/node_modules/broadcast-channel/src/broadcast-channel.js new file mode 100644 index 0000000..da132aa --- /dev/null +++ b/node_modules/broadcast-channel/src/broadcast-channel.js @@ -0,0 +1,272 @@ +import { + isPromise +} from './util.js'; + +import { + chooseMethod +} from './method-chooser.js'; + +import { + fillOptionsWithDefaults +} from './options.js'; + + +export const BroadcastChannel = function (name, options) { + this.name = name; + + if (ENFORCED_OPTIONS) { + options = ENFORCED_OPTIONS; + } + this.options = fillOptionsWithDefaults(options); + + this.method = chooseMethod(this.options); + + // isListening + this._iL = false; + + /** + * _onMessageListener + * setting onmessage twice, + * will overwrite the first listener + */ + this._onML = null; + + /** + * _addEventListeners + */ + this._addEL = { + message: [], + internal: [] + }; + + /** + * Unsend message promises + * where the sending is still in progress + * @type {Set} + */ + this._uMP = new Set(); + + /** + * _beforeClose + * array of promises that will be awaited + * before the channel is closed + */ + this._befC = []; + + /** + * _preparePromise + */ + this._prepP = null; + _prepareChannel(this); +}; + +// STATICS + +/** + * used to identify if someone overwrites + * window.BroadcastChannel with this + * See methods/native.js + */ +BroadcastChannel._pubkey = true; + +/** + * clears the tmp-folder if is node + * @return {Promise} true if has run, false if not node + */ +export function clearNodeFolder(options) { + options = fillOptionsWithDefaults(options); + const method = chooseMethod(options); + if (method.type === 'node') { + return method.clearNodeFolder().then(() => true); + } else { + return Promise.resolve(false); + } +} + +/** + * if set, this method is enforced, + * no mather what the options are + */ +let ENFORCED_OPTIONS; +export function enforceOptions(options) { + ENFORCED_OPTIONS = options; +} + + +// PROTOTYPE +BroadcastChannel.prototype = { + postMessage(msg) { + if (this.closed) { + throw new Error( + 'BroadcastChannel.postMessage(): ' + + 'Cannot post message after channel has closed' + ); + } + return _post(this, 'message', msg); + }, + postInternal(msg) { + return _post(this, 'internal', msg); + }, + set onmessage(fn) { + const time = this.method.microSeconds(); + const listenObj = { + time, + fn + }; + _removeListenerObject(this, 'message', this._onML); + if (fn && typeof fn === 'function') { + this._onML = listenObj; + _addListenerObject(this, 'message', listenObj); + } else { + this._onML = null; + } + }, + + addEventListener(type, fn) { + const time = this.method.microSeconds(); + const listenObj = { + time, + fn + }; + _addListenerObject(this, type, listenObj); + }, + removeEventListener(type, fn) { + const obj = this._addEL[type].find(obj => obj.fn === fn); + _removeListenerObject(this, type, obj); + }, + + close() { + if (this.closed) { + return; + } + this.closed = true; + const awaitPrepare = this._prepP ? this._prepP : Promise.resolve(); + + this._onML = null; + this._addEL.message = []; + + return awaitPrepare + // wait until all current sending are processed + .then(() => Promise.all(Array.from(this._uMP))) + // run before-close hooks + .then(() => Promise.all(this._befC.map(fn => fn()))) + // close the channel + .then(() => this.method.close(this._state)); + }, + get type() { + return this.method.type; + }, + get isClosed() { + return this.closed; + } +}; + + +/** + * Post a message over the channel + * @returns {Promise} that resolved when the message sending is done + */ +function _post(broadcastChannel, type, msg) { + const time = broadcastChannel.method.microSeconds(); + const msgObj = { + time, + type, + data: msg + }; + + const awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve(); + return awaitPrepare.then(() => { + + const sendPromise = broadcastChannel.method.postMessage( + broadcastChannel._state, + msgObj + ); + + // add/remove to unsend messages list + broadcastChannel._uMP.add(sendPromise); + sendPromise + .catch() + .then(() => broadcastChannel._uMP.delete(sendPromise)); + + return sendPromise; + }); +} + +function _prepareChannel(channel) { + const maybePromise = channel.method.create(channel.name, channel.options); + if (isPromise(maybePromise)) { + channel._prepP = maybePromise; + maybePromise.then(s => { + // used in tests to simulate slow runtime + /*if (channel.options.prepareDelay) { + await new Promise(res => setTimeout(res, this.options.prepareDelay)); + }*/ + channel._state = s; + }); + } else { + channel._state = maybePromise; + } +} + + +function _hasMessageListeners(channel) { + if (channel._addEL.message.length > 0) return true; + if (channel._addEL.internal.length > 0) return true; + return false; +} + +function _addListenerObject(channel, type, obj) { + channel._addEL[type].push(obj); + _startListening(channel); +} + +function _removeListenerObject(channel, type, obj) { + channel._addEL[type] = channel._addEL[type].filter(o => o !== obj); + _stopListening(channel); +} + +function _startListening(channel) { + if (!channel._iL && _hasMessageListeners(channel)) { + // someone is listening, start subscribing + + const listenerFn = msgObj => { + channel._addEL[msgObj.type].forEach(obj => { + if (msgObj.time >= obj.time) { + obj.fn(msgObj.data); + } + }); + }; + + const time = channel.method.microSeconds(); + if (channel._prepP) { + channel._prepP.then(() => { + channel._iL = true; + channel.method.onMessage( + channel._state, + listenerFn, + time + ); + }); + } else { + channel._iL = true; + channel.method.onMessage( + channel._state, + listenerFn, + time + ); + } + } +} + +function _stopListening(channel) { + if (channel._iL && !_hasMessageListeners(channel)) { + // noone is listening, stop subscribing + channel._iL = false; + const time = channel.method.microSeconds(); + channel.method.onMessage( + channel._state, + null, + time + ); + } +} diff --git a/node_modules/broadcast-channel/src/browserify.index.js b/node_modules/broadcast-channel/src/browserify.index.js new file mode 100644 index 0000000..ed57b85 --- /dev/null +++ b/node_modules/broadcast-channel/src/browserify.index.js @@ -0,0 +1,6 @@ +const module = require('./index.es5.js'); +const BroadcastChannel = module.BroadcastChannel; +const createLeaderElection = module.createLeaderElection; + +window['BroadcastChannel2'] = BroadcastChannel; +window['createLeaderElection'] = createLeaderElection; \ No newline at end of file diff --git a/node_modules/broadcast-channel/src/index.es5.js b/node_modules/broadcast-channel/src/index.es5.js new file mode 100644 index 0000000..b80dc4c --- /dev/null +++ b/node_modules/broadcast-channel/src/index.es5.js @@ -0,0 +1,24 @@ +/** + * because babel can only export on default-attribute, + * we use this for the non-module-build + * this ensures that users do not have to use + * var BroadcastChannel = require('broadcast-channel').default; + * but + * var BroadcastChannel = require('broadcast-channel'); + */ + +import { + BroadcastChannel, + createLeaderElection, + clearNodeFolder, + enforceOptions, + beLeader +} from './index.js'; + +module.exports = { + BroadcastChannel, + createLeaderElection, + clearNodeFolder, + enforceOptions, + beLeader +}; diff --git a/node_modules/broadcast-channel/src/index.js b/node_modules/broadcast-channel/src/index.js new file mode 100644 index 0000000..c7b964d --- /dev/null +++ b/node_modules/broadcast-channel/src/index.js @@ -0,0 +1,9 @@ +export { + BroadcastChannel, + clearNodeFolder, + enforceOptions +} from './broadcast-channel'; +export { + createLeaderElection, + beLeader +} from './leader-election'; diff --git a/node_modules/broadcast-channel/src/leader-election.js b/node_modules/broadcast-channel/src/leader-election.js new file mode 100644 index 0000000..ba321fd --- /dev/null +++ b/node_modules/broadcast-channel/src/leader-election.js @@ -0,0 +1,230 @@ +import { + sleep, + randomToken +} from './util.js'; + +import unload from 'unload'; + +const LeaderElection = function (channel, options) { + this._channel = channel; + this._options = options; + + this.isLeader = false; + this.isDead = false; + this.token = randomToken(); + + this._isApl = false; // _isApplying + this._reApply = false; + + // things to clean up + this._unl = []; // _unloads + this._lstns = []; // _listeners + this._invs = []; // _intervals + this._dpL = () => { }; // onduplicate listener + this._dpLC = false; // true when onduplicate called +}; + +LeaderElection.prototype = { + applyOnce() { + if (this.isLeader) return Promise.resolve(false); + if (this.isDead) return Promise.resolve(false); + + // do nothing if already running + if (this._isApl) { + this._reApply = true; + return Promise.resolve(false); + } + this._isApl = true; + + let stopCriteria = false; + const recieved = []; + + const handleMessage = (msg) => { + if (msg.context === 'leader' && msg.token != this.token) { + recieved.push(msg); + + if (msg.action === 'apply') { + // other is applying + if (msg.token > this.token) { + // other has higher token, stop applying + stopCriteria = true; + } + } + + if (msg.action === 'tell') { + // other is already leader + stopCriteria = true; + } + } + }; + this._channel.addEventListener('internal', handleMessage); + + + + const ret = _sendMessage(this, 'apply') // send out that this one is applying + .then(() => sleep(this._options.responseTime)) // let others time to respond + .then(() => { + if (stopCriteria) return Promise.reject(new Error()); + else return _sendMessage(this, 'apply'); + }) + .then(() => sleep(this._options.responseTime)) // let others time to respond + .then(() => { + if (stopCriteria) return Promise.reject(new Error()); + else return _sendMessage(this); + }) + .then(() => beLeader(this)) // no one disagreed -> this one is now leader + .then(() => true) + .catch(() => false) // apply not successfull + .then(success => { + this._channel.removeEventListener('internal', handleMessage); + this._isApl = false; + if (!success && this._reApply) { + this._reApply = false; + return this.applyOnce(); + } else return success; + }); + return ret; + }, + + awaitLeadership() { + if ( + /* _awaitLeadershipPromise */ + !this._aLP + ) { + this._aLP = _awaitLeadershipOnce(this); + } + return this._aLP; + }, + + set onduplicate(fn) { + this._dpL = fn; + }, + + die() { + if (this.isDead) return; + this.isDead = true; + + this._lstns.forEach(listener => this._channel.removeEventListener('internal', listener)); + this._invs.forEach(interval => clearInterval(interval)); + this._unl.forEach(uFn => { + uFn.remove(); + }); + return _sendMessage(this, 'death'); + } +}; + +function _awaitLeadershipOnce(leaderElector) { + if (leaderElector.isLeader) return Promise.resolve(); + + return new Promise((res) => { + let resolved = false; + + function finish() { + if (resolved) { + return; + } + resolved = true; + clearInterval(interval); + leaderElector._channel.removeEventListener('internal', whenDeathListener); + res(true); + } + + // try once now + leaderElector.applyOnce().then(() => { + if (leaderElector.isLeader) { + finish(); + } + }); + + // try on fallbackInterval + const interval = setInterval(() => { + leaderElector.applyOnce().then(() => { + if (leaderElector.isLeader) { + finish(); + } + }); + }, leaderElector._options.fallbackInterval); + leaderElector._invs.push(interval); + + // try when other leader dies + const whenDeathListener = msg => { + if (msg.context === 'leader' && msg.action === 'death') { + leaderElector.applyOnce().then(() => { + if (leaderElector.isLeader) finish(); + }); + } + }; + leaderElector._channel.addEventListener('internal', whenDeathListener); + leaderElector._lstns.push(whenDeathListener); + }); +} + +/** + * sends and internal message over the broadcast-channel + */ +function _sendMessage(leaderElector, action) { + const msgJson = { + context: 'leader', + action, + token: leaderElector.token + }; + return leaderElector._channel.postInternal(msgJson); +} + +export function beLeader(leaderElector) { + leaderElector.isLeader = true; + const unloadFn = unload.add(() => leaderElector.die()); + leaderElector._unl.push(unloadFn); + + const isLeaderListener = msg => { + if (msg.context === 'leader' && msg.action === 'apply') { + _sendMessage(leaderElector, 'tell'); + } + + if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) { + /** + * another instance is also leader! + * This can happen on rare events + * like when the CPU is at 100% for long time + * or the tabs are open very long and the browser throttles them. + * @link https://github.com/pubkey/broadcast-channel/issues/414 + * @link https://github.com/pubkey/broadcast-channel/issues/385 + */ + leaderElector._dpLC = true; + leaderElector._dpL(); // message the lib user so the app can handle the problem + _sendMessage(leaderElector, 'tell'); // ensure other leader also knows the problem + } + }; + leaderElector._channel.addEventListener('internal', isLeaderListener); + leaderElector._lstns.push(isLeaderListener); + return _sendMessage(leaderElector, 'tell'); +} + + +function fillOptionsWithDefaults(options, channel) { + if (!options) options = {}; + options = JSON.parse(JSON.stringify(options)); + + if (!options.fallbackInterval) { + options.fallbackInterval = 3000; + } + + if (!options.responseTime) { + options.responseTime = channel.method.averageResponseTime(channel.options); + } + + return options; +} + +export function createLeaderElection(channel, options) { + if (channel._leaderElector) { + throw new Error('BroadcastChannel already has a leader-elector'); + } + + options = fillOptionsWithDefaults(options, channel); + const elector = new LeaderElection(channel, options); + channel._befC.push(() => elector.die()); + + channel._leaderElector = elector; + return elector; +} diff --git a/node_modules/broadcast-channel/src/method-chooser.js b/node_modules/broadcast-channel/src/method-chooser.js new file mode 100644 index 0000000..20c0024 --- /dev/null +++ b/node_modules/broadcast-channel/src/method-chooser.js @@ -0,0 +1,72 @@ +import NativeMethod from './methods/native.js'; +import IndexeDbMethod from './methods/indexed-db.js'; +import LocalstorageMethod from './methods/localstorage.js'; +import SimulateMethod from './methods/simulate.js'; + +import { + isNode +} from './util'; + +// order is important +const METHODS = [ + NativeMethod, // fastest + IndexeDbMethod, + LocalstorageMethod +]; + +/** + * The NodeMethod is loaded lazy + * so it will not get bundled in browser-builds + */ +if (isNode) { + + /** + * we use the non-transpiled code for nodejs + * because it runs faster + */ + const NodeMethod = require( + '../../src/methods/' + + // use this hack so that browserify and others + // do not import the node-method by default + // when bundling. + 'node.js' + ); + + /** + * this will be false for webpackbuilds + * which will shim the node-method with an empty object {} + */ + if (typeof NodeMethod.canBeUsed === 'function') { + METHODS.push(NodeMethod); + } +} + + +export function chooseMethod(options) { + let chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); + + // directly chosen + if (options.type) { + if (options.type === 'simulate') { + // only use simulate-method if directly chosen + return SimulateMethod; + } + const ret = chooseMethods.find(m => m.type === options.type); + if (!ret) throw new Error('method-type ' + options.type + ' not found'); + else return ret; + } + + /** + * if no webworker support is needed, + * remove idb from the list so that localstorage is been chosen + */ + if (!options.webWorkerSupport && !isNode) { + chooseMethods = chooseMethods.filter(m => m.type !== 'idb'); + } + + const useMethod = chooseMethods.find(method => method.canBeUsed()); + if (!useMethod) + throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(m => m.type))); + else + return useMethod; +} diff --git a/node_modules/broadcast-channel/src/methods/cookies.js b/node_modules/broadcast-channel/src/methods/cookies.js new file mode 100644 index 0000000..01fd00b --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/cookies.js @@ -0,0 +1,4 @@ +/** + * if you really need this method, + * implement it + */ diff --git a/node_modules/broadcast-channel/src/methods/indexed-db.js b/node_modules/broadcast-channel/src/methods/indexed-db.js new file mode 100644 index 0000000..3c54dff --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/indexed-db.js @@ -0,0 +1,332 @@ +/** + * this method uses indexeddb to store the messages + * There is currently no observerAPI for idb + * @link https://github.com/w3c/IndexedDB/issues/51 + */ + +import { + sleep, + randomInt, + randomToken, + microSeconds as micro, + isNode +} from '../util.js'; + +export const microSeconds = micro; +import { ObliviousSet } from 'oblivious-set'; + +import { + fillOptionsWithDefaults +} from '../options'; + +const DB_PREFIX = 'pubkey.broadcast-channel-0-'; +const OBJECT_STORE_ID = 'messages'; + +export const type = 'idb'; + +export function getIdb() { + if (typeof indexedDB !== 'undefined') return indexedDB; + if (typeof window !== 'undefined') { + if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB; + if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB; + if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB; + } + + return false; +} + +export function createDatabase(channelName) { + const IndexedDB = getIdb(); + + // create table + const dbName = DB_PREFIX + channelName; + const openRequest = IndexedDB.open(dbName, 1); + + openRequest.onupgradeneeded = ev => { + const db = ev.target.result; + db.createObjectStore(OBJECT_STORE_ID, { + keyPath: 'id', + autoIncrement: true + }); + }; + const dbPromise = new Promise((res, rej) => { + openRequest.onerror = ev => rej(ev); + openRequest.onsuccess = () => { + res(openRequest.result); + }; + }); + + return dbPromise; +} + +/** + * writes the new message to the database + * so other readers can find it + */ +export function writeMessage(db, readerUuid, messageJson) { + const time = new Date().getTime(); + const writeObject = { + uuid: readerUuid, + time, + data: messageJson + }; + + const transaction = db.transaction([OBJECT_STORE_ID], 'readwrite'); + + return new Promise((res, rej) => { + transaction.oncomplete = () => res(); + transaction.onerror = ev => rej(ev); + + const objectStore = transaction.objectStore(OBJECT_STORE_ID); + objectStore.add(writeObject); + }); +} + +export function getAllMessages(db) { + const objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); + const ret = []; + return new Promise(res => { + objectStore.openCursor().onsuccess = ev => { + const cursor = ev.target.result; + if (cursor) { + ret.push(cursor.value); + //alert("Name for SSN " + cursor.key + " is " + cursor.value.name); + cursor.continue(); + } else { + res(ret); + } + }; + }); +} + +export function getMessagesHigherThan(db, lastCursorId) { + const objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); + const ret = []; + + function openCursor() { + // Occasionally Safari will fail on IDBKeyRange.bound, this + // catches that error, having it open the cursor to the first + // item. When it gets data it will advance to the desired key. + try { + const keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity); + return objectStore.openCursor(keyRangeValue); + } catch (e) { + return objectStore.openCursor(); + } + } + + return new Promise(res => { + openCursor().onsuccess = ev => { + const cursor = ev.target.result; + if (cursor) { + if (cursor.value.id < lastCursorId + 1) { + cursor.continue(lastCursorId + 1); + } else { + ret.push(cursor.value); + cursor.continue(); + } + } else { + res(ret); + } + }; + }); +} + +export function removeMessageById(db, id) { + const request = db.transaction([OBJECT_STORE_ID], 'readwrite') + .objectStore(OBJECT_STORE_ID) + .delete(id); + return new Promise(res => { + request.onsuccess = () => res(); + }); +} + +export function getOldMessages(db, ttl) { + const olderThen = new Date().getTime() - ttl; + const objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID); + const ret = []; + return new Promise(res => { + objectStore.openCursor().onsuccess = ev => { + const cursor = ev.target.result; + if (cursor) { + const msgObk = cursor.value; + if (msgObk.time < olderThen) { + ret.push(msgObk); + //alert("Name for SSN " + cursor.key + " is " + cursor.value.name); + cursor.continue(); + } else { + // no more old messages, + res(ret); + return; + } + } else { + res(ret); + } + }; + }); +} + +export function cleanOldMessages(db, ttl) { + return getOldMessages(db, ttl) + .then(tooOld => { + return Promise.all( + tooOld.map(msgObj => removeMessageById(db, msgObj.id)) + ); + }); +} + +export function create(channelName, options) { + options = fillOptionsWithDefaults(options); + + return createDatabase(channelName).then(db => { + const state = { + closed: false, + lastCursorId: 0, + channelName, + options, + uuid: randomToken(), + /** + * emittedMessagesIds + * contains all messages that have been emitted before + * @type {ObliviousSet} + */ + eMIs: new ObliviousSet(options.idb.ttl * 2), + // ensures we do not read messages in parrallel + writeBlockPromise: Promise.resolve(), + messagesCallback: null, + readQueuePromises: [], + db + }; + + /** + * Handle abrupt closes that do not originate from db.close(). + * This could happen, for example, if the underlying storage is + * removed or if the user clears the database in the browser's + * history preferences. + */ + db.onclose = function () { + state.closed = true; + + if (options.idb.onclose) options.idb.onclose(); + }; + + /** + * if service-workers are used, + * we have no 'storage'-event if they post a message, + * therefore we also have to set an interval + */ + _readLoop(state); + + return state; + }); +} + +function _readLoop(state) { + if (state.closed) return; + + readNewMessages(state) + .then(() => sleep(state.options.idb.fallbackInterval)) + .then(() => _readLoop(state)); +} + + +function _filterMessage(msgObj, state) { + if (msgObj.uuid === state.uuid) return false; // send by own + if (state.eMIs.has(msgObj.id)) return false; // already emitted + if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback + return true; +} + +/** + * reads all new messages from the database and emits them + */ +function readNewMessages(state) { + + // channel already closed + if (state.closed) return Promise.resolve(); + + // if no one is listening, we do not need to scan for new messages + if (!state.messagesCallback) return Promise.resolve(); + + return getMessagesHigherThan(state.db, state.lastCursorId) + .then(newerMessages => { + const useMessages = newerMessages + /** + * there is a bug in iOS where the msgObj can be undefined some times + * so we filter them out + * @link https://github.com/pubkey/broadcast-channel/issues/19 + */ + .filter(msgObj => !!msgObj) + .map(msgObj => { + if (msgObj.id > state.lastCursorId) { + state.lastCursorId = msgObj.id; + } + return msgObj; + }) + .filter(msgObj => _filterMessage(msgObj, state)) + .sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time + useMessages.forEach(msgObj => { + if (state.messagesCallback) { + state.eMIs.add(msgObj.id); + state.messagesCallback(msgObj.data); + } + }); + + return Promise.resolve(); + }); +} + +export function close(channelState) { + channelState.closed = true; + channelState.db.close(); +} + +export function postMessage(channelState, messageJson) { + + channelState.writeBlockPromise = channelState.writeBlockPromise + .then(() => writeMessage( + channelState.db, + channelState.uuid, + messageJson + )) + .then(() => { + if (randomInt(0, 10) === 0) { + /* await (do not await) */ + cleanOldMessages( + channelState.db, + channelState.options.idb.ttl + ); + } + }); + + return channelState.writeBlockPromise; +} + +export function onMessage(channelState, fn, time) { + channelState.messagesCallbackTime = time; + channelState.messagesCallback = fn; + readNewMessages(channelState); +} + +export function canBeUsed() { + if (isNode) return false; + const idb = getIdb(); + + if (!idb) return false; + return true; +} + +export function averageResponseTime(options) { + return options.idb.fallbackInterval * 2; +} + +export default { + create, + close, + onMessage, + postMessage, + canBeUsed, + type, + averageResponseTime, + microSeconds +}; diff --git a/node_modules/broadcast-channel/src/methods/localstorage.js b/node_modules/broadcast-channel/src/methods/localstorage.js new file mode 100644 index 0000000..5a8f991 --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/localstorage.js @@ -0,0 +1,185 @@ +/** + * A localStorage-only method which uses localstorage and its 'storage'-event + * This does not work inside of webworkers because they have no access to locastorage + * This is basically implemented to support IE9 or your grandmothers toaster. + * @link https://caniuse.com/#feat=namevalue-storage + * @link https://caniuse.com/#feat=indexeddb + */ + +import { ObliviousSet } from 'oblivious-set'; + +import { + fillOptionsWithDefaults +} from '../options'; + +import { + sleep, + randomToken, + microSeconds as micro, + isNode +} from '../util'; + +export const microSeconds = micro; + +const KEY_PREFIX = 'pubkey.broadcastChannel-'; +export const type = 'localstorage'; + +/** + * copied from crosstab + * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32 + */ +export function getLocalStorage() { + let localStorage; + if (typeof window === 'undefined') return null; + try { + localStorage = window.localStorage; + localStorage = window['ie8-eventlistener/storage'] || window.localStorage; + } catch (e) { + // New versions of Firefox throw a Security exception + // if cookies are disabled. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153 + } + return localStorage; +} + +export function storageKey(channelName) { + return KEY_PREFIX + channelName; +} + + +/** +* writes the new message to the storage +* and fires the storage-event so other readers can find it +*/ +export function postMessage(channelState, messageJson) { + return new Promise(res => { + sleep().then(() => { + const key = storageKey(channelState.channelName); + const writeObj = { + token: randomToken(), + time: new Date().getTime(), + data: messageJson, + uuid: channelState.uuid + }; + const value = JSON.stringify(writeObj); + getLocalStorage().setItem(key, value); + + /** + * StorageEvent does not fire the 'storage' event + * in the window that changes the state of the local storage. + * So we fire it manually + */ + const ev = document.createEvent('Event'); + ev.initEvent('storage', true, true); + ev.key = key; + ev.newValue = value; + window.dispatchEvent(ev); + + res(); + }); + }); +} + +export function addStorageEventListener(channelName, fn) { + const key = storageKey(channelName); + const listener = ev => { + if (ev.key === key) { + fn(JSON.parse(ev.newValue)); + } + }; + window.addEventListener('storage', listener); + return listener; +} +export function removeStorageEventListener(listener) { + window.removeEventListener('storage', listener); +} + +export function create(channelName, options) { + options = fillOptionsWithDefaults(options); + if (!canBeUsed()) { + throw new Error('BroadcastChannel: localstorage cannot be used'); + } + + const uuid = randomToken(); + + /** + * eMIs + * contains all messages that have been emitted before + * @type {ObliviousSet} + */ + const eMIs = new ObliviousSet(options.localstorage.removeTimeout); + + const state = { + channelName, + uuid, + eMIs // emittedMessagesIds + }; + + + state.listener = addStorageEventListener( + channelName, + (msgObj) => { + if (!state.messagesCallback) return; // no listener + if (msgObj.uuid === uuid) return; // own message + if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted + if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old + + eMIs.add(msgObj.token); + state.messagesCallback(msgObj.data); + } + ); + + + return state; +} + +export function close(channelState) { + removeStorageEventListener(channelState.listener); +} + +export function onMessage(channelState, fn, time) { + channelState.messagesCallbackTime = time; + channelState.messagesCallback = fn; +} + +export function canBeUsed() { + if (isNode) return false; + const ls = getLocalStorage(); + + if (!ls) return false; + + try { + const key = '__broadcastchannel_check'; + ls.setItem(key, 'works'); + ls.removeItem(key); + } catch (e) { + // Safari 10 in private mode will not allow write access to local + // storage and fail with a QuotaExceededError. See + // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes + return false; + } + + return true; +} + + +export function averageResponseTime() { + const defaultTime = 120; + const userAgent = navigator.userAgent.toLowerCase(); + if (userAgent.includes('safari') && !userAgent.includes('chrome')) { + // safari is much slower so this time is higher + return defaultTime * 2; + } + return defaultTime; +} + +export default { + create, + close, + onMessage, + postMessage, + canBeUsed, + type, + averageResponseTime, + microSeconds +}; diff --git a/node_modules/broadcast-channel/src/methods/native.js b/node_modules/broadcast-channel/src/methods/native.js new file mode 100644 index 0000000..180c739 --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/native.js @@ -0,0 +1,76 @@ +import { + microSeconds as micro, + isNode +} from '../util'; + +export const microSeconds = micro; + +export const type = 'native'; + +export function create(channelName) { + const state = { + messagesCallback: null, + bc: new BroadcastChannel(channelName), + subFns: [] // subscriberFunctions + }; + + state.bc.onmessage = msg => { + if (state.messagesCallback) { + state.messagesCallback(msg.data); + } + }; + + return state; +} + +export function close(channelState) { + channelState.bc.close(); + channelState.subFns = []; +} + +export function postMessage(channelState, messageJson) { + try { + channelState.bc.postMessage(messageJson, false); + return Promise.resolve(); + } catch (err) { + return Promise.reject(err); + } +} + +export function onMessage(channelState, fn) { + channelState.messagesCallback = fn; +} + +export function canBeUsed() { + + /** + * in the electron-renderer, isNode will be true even if we are in browser-context + * so we also check if window is undefined + */ + if (isNode && typeof window === 'undefined') return false; + + if (typeof BroadcastChannel === 'function') { + if (BroadcastChannel._pubkey) { + throw new Error( + 'BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill' + ); + } + return true; + } else return false; +} + + +export function averageResponseTime() { + return 150; +} + +export default { + create, + close, + onMessage, + postMessage, + canBeUsed, + type, + averageResponseTime, + microSeconds +}; diff --git a/node_modules/broadcast-channel/src/methods/node.js b/node_modules/broadcast-channel/src/methods/node.js new file mode 100644 index 0000000..bfbdf28 --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/node.js @@ -0,0 +1,694 @@ +/** + * this method is used in nodejs-environments. + * The ipc is handled via sockets and file-writes to the tmp-folder + */ + +const util = require('util'); +const fs = require('fs'); +const os = require('os'); +const events = require('events'); +const net = require('net'); +const path = require('path'); +const micro = require('nano-time'); +const rimraf = require('rimraf'); +const sha3_224 = require('js-sha3').sha3_224; +const isNode = require('detect-node'); +const unload = require('unload'); + +const fillOptionsWithDefaults = require('../../dist/lib/options.js').fillOptionsWithDefaults; +const ownUtil = require('../../dist/lib/util.js'); +const randomInt = ownUtil.randomInt; +const randomToken = ownUtil.randomToken; +const { ObliviousSet } = require('oblivious-set'); + +/** + * windows sucks, so we have handle windows-type of socket-paths + * @link https://gist.github.com/domenic/2790533#gistcomment-331356 + */ +function cleanPipeName(str) { + if ( + process.platform === 'win32' && + !str.startsWith('\\\\.\\pipe\\') + ) { + str = str.replace(/^\//, ''); + str = str.replace(/\//g, '-'); + return '\\\\.\\pipe\\' + str; + } else { + return str; + } +} + +const mkdir = util.promisify(fs.mkdir); +const writeFile = util.promisify(fs.writeFile); +const readFile = util.promisify(fs.readFile); +const unlink = util.promisify(fs.unlink); +const readdir = util.promisify(fs.readdir); +const chmod = util.promisify(fs.chmod); +const removeDir = util.promisify(rimraf); + +const OTHER_INSTANCES = {}; +const TMP_FOLDER_NAME = 'pubkey.bc'; +const TMP_FOLDER_BASE = path.join( + os.tmpdir(), + TMP_FOLDER_NAME +); +const getPathsCache = new Map(); + +function getPaths(channelName) { + if (!getPathsCache.has(channelName)) { + const channelHash = sha3_224(channelName); // use hash incase of strange characters + /** + * because the lenght of socket-paths is limited, we use only the first 20 chars + * and also start with A to ensure we do not start with a number + * @link https://serverfault.com/questions/641347/check-if-a-path-exceeds-maximum-for-unix-domain-socket + */ + const channelFolder = 'A' + channelHash.substring(0, 20); + + const channelPathBase = path.join( + TMP_FOLDER_BASE, + channelFolder + ); + const folderPathReaders = path.join( + channelPathBase, + 'rdrs' + ); + const folderPathMessages = path.join( + channelPathBase, + 'messages' + ); + + const ret = { + channelBase: channelPathBase, + readers: folderPathReaders, + messages: folderPathMessages + }; + getPathsCache.set(channelName, ret); + return ret; + } + return getPathsCache.get(channelName); +} + +let ENSURE_BASE_FOLDER_EXISTS_PROMISE = null; +async function ensureBaseFolderExists() { + if (!ENSURE_BASE_FOLDER_EXISTS_PROMISE) { + ENSURE_BASE_FOLDER_EXISTS_PROMISE = mkdir(TMP_FOLDER_BASE).catch(() => null); + } + return ENSURE_BASE_FOLDER_EXISTS_PROMISE; +} + +async function ensureFoldersExist(channelName, paths) { + paths = paths || getPaths(channelName); + + await ensureBaseFolderExists(); + + await mkdir(paths.channelBase).catch(() => null); + await Promise.all([ + mkdir(paths.readers).catch(() => null), + mkdir(paths.messages).catch(() => null) + ]); + + // set permissions so other users can use the same channel + const chmodValue = '777'; + await Promise.all([ + chmod(paths.channelBase, chmodValue), + chmod(paths.readers, chmodValue), + chmod(paths.messages, chmodValue) + ]).catch(() => null); +} + +/** + * removes the tmp-folder + * @return {Promise} + */ +async function clearNodeFolder() { + if (!TMP_FOLDER_BASE || TMP_FOLDER_BASE === '' || TMP_FOLDER_BASE === '/') { + throw new Error('BroadcastChannel.clearNodeFolder(): path is wrong'); + } + ENSURE_BASE_FOLDER_EXISTS_PROMISE = null; + await removeDir(TMP_FOLDER_BASE); + ENSURE_BASE_FOLDER_EXISTS_PROMISE = null; + return true; +} + + +function socketPath(channelName, readerUuid, paths) { + paths = paths || getPaths(channelName); + const socketPath = path.join( + paths.readers, + readerUuid + '.s' + ); + return cleanPipeName(socketPath); +} + +function socketInfoPath(channelName, readerUuid, paths) { + paths = paths || getPaths(channelName); + const socketPath = path.join( + paths.readers, + readerUuid + '.json' + ); + return socketPath; +} + + +/** + * Because it is not possible to get all socket-files in a folder, + * when used under fucking windows, + * we have to set a normal file so other readers know our socket exists + */ +function createSocketInfoFile(channelName, readerUuid, paths) { + const pathToFile = socketInfoPath(channelName, readerUuid, paths); + return writeFile( + pathToFile, + JSON.stringify({ + time: microSeconds() + }) + ).then(() => pathToFile); +} + +/** + * returns the amount of channel-folders in the tmp-directory + * @return {Promise} + */ +async function countChannelFolders() { + await ensureBaseFolderExists(); + const folders = await readdir(TMP_FOLDER_BASE); + return folders.length; +} + + +async function connectionError(originalError) { + const count = await countChannelFolders(); + + // we only show the augmented message if there are more then 30 channels + // because we then assume that BroadcastChannel is used in unit-tests + if (count < 30) return originalError; + + const addObj = {}; + Object.entries(originalError).forEach(([k, v]) => addObj[k] = v); + const text = 'BroadcastChannel.create(): error: ' + + 'This might happen if you have created to many channels, ' + + 'like when you use BroadcastChannel in unit-tests.' + + 'Try using BroadcastChannel.clearNodeFolder() to clear the tmp-folder before each test.' + + 'See https://github.com/pubkey/broadcast-channel#clear-tmp-folder'; + const newError = new Error(text + ': ' + JSON.stringify(addObj, null, 2)); + return newError; +} + +/** + * creates the socket-file and subscribes to it + * @return {{emitter: EventEmitter, server: any}} + */ +async function createSocketEventEmitter(channelName, readerUuid, paths) { + const pathToSocket = socketPath(channelName, readerUuid, paths); + + const emitter = new events.EventEmitter(); + const server = net + .createServer(stream => { + stream.on('end', function () { }); + stream.on('data', function (msg) { + emitter.emit('data', msg.toString()); + }); + }); + + await new Promise((resolve, reject) => { + server.on('error', async (err) => { + const useErr = await connectionError(err); + reject(useErr); + }); + + server.listen(pathToSocket, async (err, res) => { + if (err) { + const useErr = await connectionError(err); + reject(useErr); + } else resolve(res); + }); + }); + + return { + path: pathToSocket, + emitter, + server + }; +} + +async function openClientConnection(channelName, readerUuid) { + const pathToSocket = socketPath(channelName, readerUuid); + const client = new net.Socket(); + return new Promise((res, rej) => { + client.connect( + pathToSocket, + () => res(client) + ); + client.on('error', err => rej(err)); + }); +} + + +/** + * writes the new message to the file-system + * so other readers can find it + * @return {Promise} + */ +function writeMessage(channelName, readerUuid, messageJson, paths) { + paths = paths || getPaths(channelName); + const time = microSeconds(); + const writeObject = { + uuid: readerUuid, + time, + data: messageJson + }; + + const token = randomToken(); + const fileName = time + '_' + readerUuid + '_' + token + '.json'; + + const msgPath = path.join( + paths.messages, + fileName + ); + + return writeFile( + msgPath, + JSON.stringify(writeObject) + ).then(() => { + return { + time, + uuid: readerUuid, + token, + path: msgPath + }; + }); +} + +/** + * returns the uuids of all readers + * @return {string[]} + */ +async function getReadersUuids(channelName, paths) { + paths = paths || getPaths(channelName); + const readersPath = paths.readers; + const files = await readdir(readersPath); + + return files + .map(file => file.split('.')) + .filter(split => split[1] === 'json') // do not scan .socket-files + .map(split => split[0]); +} + +async function messagePath(channelName, time, token, writerUuid) { + const fileName = time + '_' + writerUuid + '_' + token + '.json'; + + const msgPath = path.join( + getPaths(channelName).messages, + fileName + ); + return msgPath; +} + +async function getAllMessages(channelName, paths) { + paths = paths || getPaths(channelName); + const messagesPath = paths.messages; + const files = await readdir(messagesPath); + return files.map(file => { + const fileName = file.split('.')[0]; + const split = fileName.split('_'); + + return { + path: path.join( + messagesPath, + file + ), + time: parseInt(split[0]), + senderUuid: split[1], + token: split[2] + }; + }); +} + +function getSingleMessage(channelName, msgObj, paths) { + paths = paths || getPaths(channelName); + + return { + path: path.join( + paths.messages, + msgObj.t + '_' + msgObj.u + '_' + msgObj.to + '.json' + ), + time: msgObj.t, + senderUuid: msgObj.u, + token: msgObj.to + }; +} + + +function readMessage(messageObj) { + return readFile(messageObj.path, 'utf8') + .then(content => JSON.parse(content)); +} + +async function cleanOldMessages(messageObjects, ttl) { + const olderThen = Date.now() - ttl; + await Promise.all( + messageObjects + .filter(obj => (obj.time / 1000) < olderThen) + .map(obj => unlink(obj.path).catch(() => null)) + ); +} + + + +const type = 'node'; + +/** + * creates a new channelState + * @return {Promise} + */ +async function create(channelName, options = {}) { + options = fillOptionsWithDefaults(options); + const time = microSeconds(); + const paths = getPaths(channelName); + const ensureFolderExistsPromise = ensureFoldersExist(channelName, paths); + const uuid = randomToken(); + + const state = { + time, + channelName, + options, + uuid, + paths, + // contains all messages that have been emitted before + emittedMessagesIds: new ObliviousSet(options.node.ttl * 2), + messagesCallbackTime: null, + messagesCallback: null, + // ensures we do not read messages in parrallel + writeBlockPromise: Promise.resolve(), + otherReaderClients: {}, + // ensure if process crashes, everything is cleaned up + removeUnload: unload.add(() => close(state)), + closed: false + }; + + if (!OTHER_INSTANCES[channelName]) OTHER_INSTANCES[channelName] = []; + OTHER_INSTANCES[channelName].push(state); + + await ensureFolderExistsPromise; + const [ + socketEE, + infoFilePath + ] = await Promise.all([ + createSocketEventEmitter(channelName, uuid, paths), + createSocketInfoFile(channelName, uuid, paths), + refreshReaderClients(state) + ]); + state.socketEE = socketEE; + state.infoFilePath = infoFilePath; + + // when new message comes in, we read it and emit it + socketEE.emitter.on('data', data => { + + // if the socket is used fast, it may appear that multiple messages are flushed at once + // so we have to split them before + const singleOnes = data.split('|'); + singleOnes + .filter(single => single !== '') + .forEach(single => { + try { + const obj = JSON.parse(single); + handleMessagePing(state, obj); + } catch (err) { + throw new Error('could not parse data: ' + single); + } + }); + }); + + return state; +} + +function _filterMessage(msgObj, state) { + if (msgObj.senderUuid === state.uuid) return false; // not send by own + if (state.emittedMessagesIds.has(msgObj.token)) return false; // not already emitted + if (!state.messagesCallback) return false; // no listener + if (msgObj.time < state.messagesCallbackTime) return false; // not older then onMessageCallback + if (msgObj.time < state.time) return false; // msgObj is older then channel + + state.emittedMessagesIds.add(msgObj.token); + return true; +} + +/** + * when the socket pings, so that we now new messages came, + * run this + */ +async function handleMessagePing(state, msgObj) { + + /** + * when there are no listener, we do nothing + */ + if (!state.messagesCallback) return; + + let messages; + if (!msgObj) { + // get all + messages = await getAllMessages(state.channelName, state.paths); + } else { + // get single message + messages = [ + getSingleMessage(state.channelName, msgObj, state.paths) + ]; + } + + const useMessages = messages + .filter(msgObj => _filterMessage(msgObj, state)) + .sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time + + + // if no listener or message, so not do anything + if (!useMessages.length || !state.messagesCallback) return; + + // read contents + await Promise.all( + useMessages + .map( + msgObj => readMessage(msgObj).then(content => msgObj.content = content) + ) + ); + + useMessages.forEach(msgObj => { + state.emittedMessagesIds.add(msgObj.token); + + if (state.messagesCallback) { + // emit to subscribers + state.messagesCallback(msgObj.content.data); + } + }); +} + +/** + * ensures that the channelState is connected with all other readers + * @return {Promise} + */ +function refreshReaderClients(channelState) { + return getReadersUuids(channelState.channelName, channelState.paths) + .then(otherReaders => { + // remove subscriptions to closed readers + Object.keys(channelState.otherReaderClients) + .filter(readerUuid => !otherReaders.includes(readerUuid)) + .forEach(async (readerUuid) => { + try { + await channelState.otherReaderClients[readerUuid].destroy(); + } catch (err) { } + delete channelState.otherReaderClients[readerUuid]; + }); + + // add new readers + return Promise.all( + otherReaders + .filter(readerUuid => readerUuid !== channelState.uuid) // not own + .filter(readerUuid => !channelState.otherReaderClients[readerUuid]) // not already has client + .map(async (readerUuid) => { + try { + if (channelState.closed) return; + try { + const client = await openClientConnection(channelState.channelName, readerUuid); + channelState.otherReaderClients[readerUuid] = client; + } catch (err) { + // this can throw when the cleanup of another channel was interrupted + // or the socket-file does not exits yet + } + } catch (err) { + // this might throw if the other channel is closed at the same time when this one is running refresh + // so we do not throw an error + } + }) + ); + }); +} + +/** + * post a message to the other readers + * @return {Promise} + */ +function postMessage(channelState, messageJson) { + const writePromise = writeMessage( + channelState.channelName, + channelState.uuid, + messageJson, + channelState.paths + ); + channelState.writeBlockPromise = channelState.writeBlockPromise.then(async () => { + + // w8 one tick to let the buffer flush + await new Promise(res => setTimeout(res, 0)); + + const [msgObj] = await Promise.all([ + writePromise, + refreshReaderClients(channelState) + ]); + emitOverFastPath(channelState, msgObj, messageJson); + const pingStr = '{"t":' + msgObj.time + ',"u":"' + msgObj.uuid + '","to":"' + msgObj.token + '"}|'; + + const writeToReadersPromise = Promise.all( + Object.values(channelState.otherReaderClients) + .filter(client => client.writable) // client might have closed in between + .map(client => { + return new Promise(res => { + client.write(pingStr, res); + }); + }) + ); + + /** + * clean up old messages + * to not waste resources on cleaning up, + * only if random-int matches, we clean up old messages + */ + if (randomInt(0, 20) === 0) { + /* await */ + getAllMessages(channelState.channelName, channelState.paths) + .then(allMessages => cleanOldMessages(allMessages, channelState.options.node.ttl)); + } + + return writeToReadersPromise; + }); + + return channelState.writeBlockPromise; +} + +/** + * When multiple BroadcastChannels with the same name + * are created in a single node-process, we can access them directly and emit messages. + * This might not happen often in production + * but will speed up things when this module is used in unit-tests. + */ +function emitOverFastPath(state, msgObj, messageJson) { + if (!state.options.node.useFastPath) return; // disabled + const others = OTHER_INSTANCES[state.channelName].filter(s => s !== state); + + const checkObj = { + time: msgObj.time, + senderUuid: msgObj.uuid, + token: msgObj.token + }; + + others + .filter(otherState => _filterMessage(checkObj, otherState)) + .forEach(otherState => { + otherState.messagesCallback(messageJson); + }); +} + + +function onMessage(channelState, fn, time = microSeconds()) { + channelState.messagesCallbackTime = time; + channelState.messagesCallback = fn; + handleMessagePing(channelState); +} + +/** + * closes the channel + * @return {Promise} + */ +function close(channelState) { + if (channelState.closed) return; + channelState.closed = true; + channelState.emittedMessagesIds.clear(); + OTHER_INSTANCES[channelState.channelName] = OTHER_INSTANCES[channelState.channelName].filter(o => o !== channelState); + + if (channelState.removeUnload) { + channelState.removeUnload.remove(); + } + + return new Promise((res) => { + + if (channelState.socketEE) + channelState.socketEE.emitter.removeAllListeners(); + + Object.values(channelState.otherReaderClients) + .forEach(client => client.destroy()); + + if (channelState.infoFilePath) { + try { + fs.unlinkSync(channelState.infoFilePath); + } catch (err) { } + } + + /** + * the server get closed lazy because others might still write on it + * and have not found out that the infoFile was deleted + */ + setTimeout(() => { + channelState.socketEE.server.close(); + res(); + }, 200); + }); +} + + +function canBeUsed() { + return isNode; +} + +/** + * on node we use a relatively height averageResponseTime, + * because the file-io might be in use. + * Also it is more important that the leader-election is reliable, + * then to have a fast election. + */ +function averageResponseTime() { + return 200; +} + +function microSeconds() { + return parseInt(micro.microseconds()); +} + +module.exports = { + TMP_FOLDER_BASE, + cleanPipeName, + getPaths, + ensureFoldersExist, + clearNodeFolder, + socketPath, + socketInfoPath, + createSocketInfoFile, + countChannelFolders, + createSocketEventEmitter, + openClientConnection, + writeMessage, + getReadersUuids, + messagePath, + getAllMessages, + getSingleMessage, + readMessage, + cleanOldMessages, + type, + create, + _filterMessage, + handleMessagePing, + refreshReaderClients, + postMessage, + emitOverFastPath, + onMessage, + close, + canBeUsed, + averageResponseTime, + microSeconds +}; diff --git a/node_modules/broadcast-channel/src/methods/simulate.js b/node_modules/broadcast-channel/src/methods/simulate.js new file mode 100644 index 0000000..2a8c760 --- /dev/null +++ b/node_modules/broadcast-channel/src/methods/simulate.js @@ -0,0 +1,59 @@ +import { + microSeconds as micro, +} from '../util'; + +export const microSeconds = micro; + +export const type = 'simulate'; + +const SIMULATE_CHANNELS = new Set(); + +export function create(channelName) { + const state = { + name: channelName, + messagesCallback: null + }; + SIMULATE_CHANNELS.add(state); + + return state; +} + +export function close(channelState) { + SIMULATE_CHANNELS.delete(channelState); +} + +export function postMessage(channelState, messageJson) { + return new Promise(res => setTimeout(() => { + const channelArray = Array.from(SIMULATE_CHANNELS); + channelArray + .filter(channel => channel.name === channelState.name) + .filter(channel => channel !== channelState) + .filter(channel => !!channel.messagesCallback) + .forEach(channel => channel.messagesCallback(messageJson)); + res(); + }, 5)); +} + +export function onMessage(channelState, fn) { + channelState.messagesCallback = fn; +} + +export function canBeUsed() { + return true; +} + + +export function averageResponseTime() { + return 5; +} + +export default { + create, + close, + onMessage, + postMessage, + canBeUsed, + type, + averageResponseTime, + microSeconds +}; diff --git a/node_modules/broadcast-channel/src/options.js b/node_modules/broadcast-channel/src/options.js new file mode 100644 index 0000000..cd86be1 --- /dev/null +++ b/node_modules/broadcast-channel/src/options.js @@ -0,0 +1,30 @@ +export function fillOptionsWithDefaults(originalOptions = {}) { + const options = JSON.parse(JSON.stringify(originalOptions)); + + // main + if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; + + + // indexed-db + if (!options.idb) options.idb = {}; + // after this time the messages get deleted + if (!options.idb.ttl) options.idb.ttl = 1000 * 45; + if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; + // handles abrupt db onclose events. + if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') + options.idb.onclose = originalOptions.idb.onclose; + + // localstorage + if (!options.localstorage) options.localstorage = {}; + if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; + + // custom methods + if (originalOptions.methods) options.methods = originalOptions.methods; + + // node + if (!options.node) options.node = {}; + if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes; + if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true; + + return options; +} diff --git a/node_modules/broadcast-channel/src/util.js b/node_modules/broadcast-channel/src/util.js new file mode 100644 index 0000000..f207bcd --- /dev/null +++ b/node_modules/broadcast-channel/src/util.js @@ -0,0 +1,57 @@ +/** + * returns true if the given object is a promise + */ +export function isPromise(obj) { + if (obj && + typeof obj.then === 'function') { + return true; + } else { + return false; + } +} + +export function sleep(time) { + if (!time) time = 0; + return new Promise(res => setTimeout(res, time)); +} + +export function randomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} + +/** + * https://stackoverflow.com/a/8084248 + */ +export function randomToken() { + return Math.random().toString(36).substring(2); +} + + +let lastMs = 0; +let additional = 0; + +/** + * returns the current time in micro-seconds, + * WARNING: This is a pseudo-function + * Performance.now is not reliable in webworkers, so we just make sure to never return the same time. + * This is enough in browsers, and this function will not be used in nodejs. + * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests. + */ +export function microSeconds() { + const ms = new Date().getTime(); + if (ms === lastMs) { + additional++; + return ms * 1000 + additional; + } else { + lastMs = ms; + additional = 0; + return ms * 1000; + } +} + +/** + * copied from the 'detect-node' npm module + * We cannot use the module directly because it causes problems with rollup + * @link https://github.com/iliakan/detect-node/blob/master/index.js + */ +export const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; diff --git a/node_modules/broadcast-channel/types/broadcast-channel.d.ts b/node_modules/broadcast-channel/types/broadcast-channel.d.ts new file mode 100644 index 0000000..afb0fb5 --- /dev/null +++ b/node_modules/broadcast-channel/types/broadcast-channel.d.ts @@ -0,0 +1,65 @@ +declare type MethodType = 'node' | 'idb' | 'native' | 'localstorage' | 'simulate'; + + + +interface BroadcastChannelEventMap { + "message": MessageEvent; + "messageerror": MessageEvent; +} + +export interface BroadcastMethod { + type: string; + microSeconds(): number; + create(channelName: string, options: BroadcastChannelOptions): Promise | State; + close(channelState: State): void; + onMessage(channelState: State, callback: (args: any) => void): void; + postMessage(channelState: State, message: any): Promise; + canBeUsed(): boolean; + averageResponseTime(): number; +} + +export type BroadcastChannelOptions = { + type?: MethodType, + methods?: BroadcastMethod[] | BroadcastMethod, + webWorkerSupport?: boolean; + prepareDelay?: number; + node?: { + ttl?: number; + useFastPath?: boolean; + }; + idb?: { + ttl?: number; + fallbackInterval?: number; + onclose?: () => void; + }; +}; + +declare type EventContext = 'message' | 'internal' | 'leader'; + +declare type OnMessageHandler = ((this: BroadcastChannel, ev: T) => any) | null; + +/** + * api as defined in + * @link https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts + * @link https://github.com/Microsoft/TypeScript/blob/master/src/lib/webworker.generated.d.ts#L325 + */ +export class BroadcastChannel { + constructor(name: string, opts?: BroadcastChannelOptions); + readonly name: string; + readonly options: BroadcastChannelOptions; + readonly type: MethodType; + readonly isClosed: boolean; + + postMessage(msg: T): Promise; + close(): Promise; + + onmessage: OnMessageHandler; + + // not defined in the offical standard + addEventListener(type: EventContext, handler: OnMessageHandler): void; + removeEventListener(type: EventContext, handler: OnMessageHandler): void; + +} +// statics +export function clearNodeFolder(opts?: BroadcastChannelOptions): Promise; +export function enforceOptions(opts?: BroadcastChannelOptions | false | null): void; diff --git a/node_modules/broadcast-channel/types/index.d.ts b/node_modules/broadcast-channel/types/index.d.ts new file mode 100644 index 0000000..d4d6b26 --- /dev/null +++ b/node_modules/broadcast-channel/types/index.d.ts @@ -0,0 +1,2 @@ +export * from './broadcast-channel'; +export * from './leader-election'; \ No newline at end of file diff --git a/node_modules/broadcast-channel/types/leader-election.d.ts b/node_modules/broadcast-channel/types/leader-election.d.ts new file mode 100644 index 0000000..808de90 --- /dev/null +++ b/node_modules/broadcast-channel/types/leader-election.d.ts @@ -0,0 +1,44 @@ +import { + BroadcastChannel, + OnMessageHandler +} from './broadcast-channel'; + +export type LeaderElectionOptions = { + /** + * This value decides how often instances will renegotiate who is leader. + * Probably should be at least 2x bigger than responseTime. + */ + fallbackInterval?: number; + /** + * This timer value is used when resolving which instance should be leader. + * In case when your application elects more than one leader increase this value. + */ + responseTime?: number; +}; + +export declare class LeaderElector { + + /** + * IMPORTANT: The leader election is lazy, + * it will not start before you call awaitLeadership() + * so isLeader will never become true then + */ + readonly isLeader: boolean; + + readonly isDead: boolean; + readonly token: string; + + applyOnce(): Promise; + awaitLeadership(): Promise; + die(): Promise; + + /** + * Add an event handler that is run + * when it is detected that there are duplicate leaders + */ + onduplicate: OnMessageHandler; +} + +type CreateFunction = (channel: BroadcastChannel, options?: LeaderElectionOptions) => LeaderElector; + +export const createLeaderElection: CreateFunction; diff --git a/node_modules/buffer/AUTHORS.md b/node_modules/buffer/AUTHORS.md new file mode 100644 index 0000000..468aa19 --- /dev/null +++ b/node_modules/buffer/AUTHORS.md @@ -0,0 +1,73 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- shuse2 (shus.toda@gmail.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) +- Deklan Webster (deklanw@gmail.com) +- Martin Heidegger (martin.heidegger@gmail.com) + +#### Generated by bin/update-authors.sh. diff --git a/node_modules/buffer/LICENSE b/node_modules/buffer/LICENSE new file mode 100644 index 0000000..d6bf75d --- /dev/null +++ b/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other 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. diff --git a/node_modules/buffer/README.md b/node_modules/buffer/README.md new file mode 100644 index 0000000..451e235 --- /dev/null +++ b/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 11+, iOS 11+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/buffer/index.d.ts b/node_modules/buffer/index.d.ts new file mode 100644 index 0000000..07096a2 --- /dev/null +++ b/node_modules/buffer/index.d.ts @@ -0,0 +1,194 @@ +export class Buffer extends Uint8Array { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readBigUInt64LE(offset: number): BigInt; + readBigUInt64BE(offset: number): BigInt; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readBigInt64LE(offset: number): BigInt; + readBigInt64BE(offset: number): BigInt; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeBigUInt64LE(value: number, offset: number): BigInt; + writeBigUInt64BE(value: number, offset: number): BigInt; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeBigInt64LE(value: number, offset: number): BigInt; + writeBigInt64BE(value: number, offset: number): BigInt; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer | Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initializing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; +} diff --git a/node_modules/buffer/index.js b/node_modules/buffer/index.js new file mode 100644 index 0000000..7a0e9c2 --- /dev/null +++ b/node_modules/buffer/index.js @@ -0,0 +1,2106 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +const base64 = require('base64-js') +const ieee754 = require('ieee754') +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} diff --git a/node_modules/buffer/package.json b/node_modules/buffer/package.json new file mode 100644 index 0000000..ca1ad9a --- /dev/null +++ b/node_modules/buffer/package.json @@ -0,0 +1,93 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "6.0.3", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.5", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.5" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-old": "airtap -- test/*.js", + "test-browser-old-local": "airtap --local -- test/*.js", + "test-browser-new": "airtap -- test/*.js test/node/*.js", + "test-browser-new-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.js" + ] + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/cardinal/.npmignore b/node_modules/cardinal/.npmignore new file mode 100644 index 0000000..7e2f179 --- /dev/null +++ b/node_modules/cardinal/.npmignore @@ -0,0 +1 @@ +assets diff --git a/node_modules/cardinal/.travis.yml b/node_modules/cardinal/.travis.yml new file mode 100644 index 0000000..c60f507 --- /dev/null +++ b/node_modules/cardinal/.travis.yml @@ -0,0 +1,6 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" diff --git a/node_modules/cardinal/LICENSE b/node_modules/cardinal/LICENSE new file mode 100644 index 0000000..19c037f --- /dev/null +++ b/node_modules/cardinal/LICENSE @@ -0,0 +1,23 @@ +Copyright 2012 Thorsten Lorenz. +All rights reserved. + +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. diff --git a/node_modules/cardinal/README.md b/node_modules/cardinal/README.md new file mode 100644 index 0000000..90ca4b5 --- /dev/null +++ b/node_modules/cardinal/README.md @@ -0,0 +1,131 @@ +# cardinal [![Build Status](https://secure.travis-ci.org/thlorenz/cardinal.svg)](http://travis-ci.org/thlorenz/cardinal) + +become a patron + +[![NPM](https://nodei.co/npm/cardinal.png?downloads=true&stars=true)](https://nodei.co/npm/cardinal/) + +**car·di·nal** *(kärdn-l, kärdnl)* - crested thick-billed North American finch having bright red plumage in the male. + +![screenshot](https://github.com/thlorenz/cardinal/raw/master/assets/screen-shot.png) + +## Features + +- highlights JavaScript code with ANSI colors to improve terminal output +- theming support, see [custom color themes](https://github.com/thlorenz/cardinal/tree/master/themes) +- optionally print line numbers +- API and command line interface (`cdl`) +- `.cardinalrc` config to customize settings +- supports UNIX pipes + +*** + +**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)* + +- [Installation](#installation) + - [As library](#as-library) + - [As Commandline Tool](#as-commandline-tool) +- [Commandline](#commandline) + - [Highlight a file](#highlight-a-file) + - [As part of a UNIX pipe](#as-part-of-a-unix-pipe) + - [Theme](#theme) +- [API](#api) + - [*highlight(code[, opts])*](#highlightcode-opts) + - [*highlightFileSync(fullPath[, opts])*](#highlightfilesyncfullpath-opts) + - [*highlightFile(fullPath[, opts], callback)*](#highlightfilefullpath-opts-callback) + - [opts](#opts) +- [Examples ([*browse*](https://github.com/thlorenz/cardinal/tree/master/examples))](#examples-[browse]https://githubcom/thlorenz/cardinal/tree/master/examples) + + +## Installation + +### As library + + npm install cardinal + +### As Commandline Tool + + [sudo] npm install -g cardinal + +**Note:** + +When installed globally, cardinal exposes itself as the `cdl` command. + +## Commandline + +### Highlight a file + + cdl [options] + +**options**: + - `--nonum`: turns off line number printing (relevant if it is turned on inside `~/.cardinalrc` + +### As part of a UNIX pipe + + cat file.js | grep console | cdl + +**Note:** + +Not all code lines may be parsable JavaScript. In these cases the line is printed to the terminal without +highlighting it. + +### Theme + +The default theme will be used for highlighting. + +To use a different theme, include a `.cardinalrc` file in your `HOME` directory. + +This is a JSON file of the following form: + +```json +{ + "theme": "hide-semicolons", + "linenos": true|false +} +``` + +- `theme` can be the name of any of the [built-in themes](https://github.com/thlorenz/cardinal/tree/master/themes) or the +full path to a custom theme anywhere on your computer. +- linenos toggles line number printing + +## API + +### *highlight(code[, opts])* + +- returns the highlighted version of the passed code ({String}) or throws an error if it was not able to parse it +- opts (see below) + +### *highlightFileSync(fullPath[, opts])* + +- returns the highlighted version of the file whose fullPath ({String}) was passed or throws an error if it was not able + to parse it +- opts (see below) + +### *highlightFile(fullPath[, opts], callback)* + +- calls back with the highlighted version of the file whose fullPath ({String}) was passed or with an error if it was not able + to parse it +- opts (see below) +- `callback` ({Function}) has the following signature: `function (err, highlighted) { .. }` + +### opts + +opts is an {Object} with the following properties: + +- `theme` {Object} is used to optionally override the theme used to highlight +- `linenos` {Boolean} if `true` line numbers are included in the highlighted code +- `firstline` {Integer} sets line number of the first line when line numbers are printed +- `jsx` {Boolean} if `true` _JSX_ syntax is supported, otherwise cardinal will raise an error + when encountering _JSX_ (default: `false`) + +**Note** The `json` option is obsoleted and not necessary anymore as cardinal properly understands both JSON and JavaScript. + +## Examples ([*browse*](https://github.com/thlorenz/cardinal/tree/master/examples)) + +- [sample .cardinalrc](https://github.com/thlorenz/cardinal/blob/master/examples/.cardinalrc) +- [highlighting a code snippet](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-string.js) via + ***highlight()*** +- [file that highlights itself](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-self.js) via + ***highlightFile()*** including line numbers +- [file that highlights itself hiding all + semicolons](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-self-hide-semicolons.js) via + ***highlightFileSync()*** diff --git a/node_modules/cardinal/bin/cdl.js b/node_modules/cardinal/bin/cdl.js new file mode 100755 index 0000000..80daf9f --- /dev/null +++ b/node_modules/cardinal/bin/cdl.js @@ -0,0 +1,78 @@ +#!/usr/bin/env node +var cardinal = require('..') +var path = require('path') +var settings = require('../settings') +var args = process.argv +var theme = settings.resolveTheme() +var opts = settings.getSettings() +var highlighted + +opts = opts || {} +opts.theme = theme +// jsx is only turned on when highlighting non-json files +opts.jsx = false + +function usage() { + var msg = [ + 'Usage: cdl [options]' + , '' + , 'Options (~/.cardinalrc overrides):' + , ' --nonum: turn off line printing' + , '' + , 'Unix Pipe Example: cat filename.js | grep console | cdl' + , '' + ].join('\n') + console.log(msg) +} + +function highlightFile() { + try { + // Enabling jsx for JSON breaks most likelely due to esprima AST generation + // not working for JSON + opts.jsx = path.extname(args[2]) !== '.json' + highlighted = cardinal.highlightFileSync(args[2], opts) + console.log(highlighted) + } catch (e) { + console.trace() + console.error(e) + } +} + +(function runner() { +// E.g., "cardinal myfile.js" +if (args.length === 3) return highlightFile() + +var opt = args[3] + +// E.g., "cardinal myfile.js --nonum" +if (opt && opt.indexOf('--') === 0) { + if ((/^--(nonum|noline)/i).test(opt)) opts.linenos = false + else { + usage() + return console.error('Unknown option: ', opt) + } + + return highlightFile() +} + +// UNIX pipes e.g., "cat myfile.js | grep console | cardinal +var stdin = process.stdin +var stdout = process.stdout + +// line numbers don't make sense when we are printing line by line +opts.linenos = false + +stdin.setEncoding('utf-8') +stdin.resume() +stdin + .on('data', function(chunk) { + chunk.split('\n').forEach(function(line) { + try { + stdout.write(cardinal.highlight(line, opts) + '\n') + } catch (e) { + // line doesn't represent a valid js snippet and therefore cannot be parsed -> just print as is + stdout.write(line + '\n') + } + }) + }) +})() diff --git a/node_modules/cardinal/cardinal.js b/node_modules/cardinal/cardinal.js new file mode 100644 index 0000000..2ef6f87 --- /dev/null +++ b/node_modules/cardinal/cardinal.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports = { + highlight: require('./lib/highlight') + , highlightFile: require('./lib/highlightFile') + , highlightFileSync: require('./lib/highlightFileSync') +} diff --git a/node_modules/cardinal/examples/.cardinalrc b/node_modules/cardinal/examples/.cardinalrc new file mode 100644 index 0000000..34be5cc --- /dev/null +++ b/node_modules/cardinal/examples/.cardinalrc @@ -0,0 +1,3 @@ +{ + "theme": "hide-semicolons" +} diff --git a/node_modules/cardinal/examples/README.md b/node_modules/cardinal/examples/README.md new file mode 100644 index 0000000..a6c2cd9 --- /dev/null +++ b/node_modules/cardinal/examples/README.md @@ -0,0 +1,7 @@ +# Cardinal Examples + +You can run the examples individually or as a demo: + +- install cardinal: `npm install cardinal` +- explore cardinal: `npm explore cardinal` +- run the demo: `npm run demo` diff --git a/node_modules/cardinal/examples/git-diff.txt b/node_modules/cardinal/examples/git-diff.txt new file mode 100644 index 0000000..e324b67 --- /dev/null +++ b/node_modules/cardinal/examples/git-diff.txt @@ -0,0 +1,78 @@ +diff --git a/test/settings.js b/test/settings.js +index 7b28d66..642688f 100644 +--- a/test/settings.js ++++ b/test/settings.js +@@ -1,14 +1,20 @@ + 'use strict'; + /*jshint asi: true*/ + +-var test = require('tap').test +- , path = require('path') +- , fs = require('fs') +- , settings = require('../settings') +- , existsSync = fs.existsSync || path.existsSync ++var test = require('tap').test ++ , path = require('path') ++ , fs = require('fs') + , hideSemicolonsTheme = require('../themes/hide-semicolons') + , home = path.join(__dirname, 'fixtures', 'home') + , rcpath = path.join(home, '.cardinalrc') ++ , existsSync = fs.existsSync || path.existsSync ++ , settingsResolve = require.resolve('../settings') ++ , settings ++ ++function setup () { ++ delete require.cache[settingsResolve] ++ settings = require(settingsResolve) ++} + + function writerc(config) { + fs.writeFileSync(rcpath, JSON.stringify(config), 'utf-8') +@@ -25,22 +31,47 @@ function resolveTheme (config) { + return result; + } + ++function getSettings (config) { ++ writerc(config) ++ var result = settings.getSettings(home) ++ removerc() ++ return result; ++} ++ + if (!existsSync(home)) fs.mkdirSync(home); + + test('no .cardinalrc in home', function (t) { ++ setup() + var theme = settings.resolveTheme(home) + t.equals(theme, undefined, 'resolves no theme') + t.end() + }) + + test('.cardinalrc with theme "hide-semicolons" in home', function (t) { ++ setup() + var theme = resolveTheme({ theme: "hide-semicolons" }) + t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme') + t.end() + }) + + test('.cardinalrc with full path to "hide-semicolons.js" in home', function (t) { ++ setup() + var theme = resolveTheme({ theme: path.join(__dirname, '..', 'themes', 'hide-semicolons.js') }) + t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme') + t.end() + }) ++ ++test('.cardinalrc with linenos: true', function (t) { ++ setup() ++ var opts = { linenos: true } ++ t.deepEquals(getSettings(opts), opts) ++ t.end() ++}) ++ ++test('.cardinalrc with linenos: true and theme', function (t) { ++ setup() ++ var opts = { linenos: true, theme: 'some theme' } ++ t.deepEquals(getSettings(opts), opts) ++ t.end() ++}) ++ diff --git a/node_modules/cardinal/examples/highlight-diff.js b/node_modules/cardinal/examples/highlight-diff.js new file mode 100644 index 0000000..958b61d --- /dev/null +++ b/node_modules/cardinal/examples/highlight-diff.js @@ -0,0 +1,90 @@ +'use strict' + +var fs = require('fs') +var path = require('path') +var highlighter = require('..') +var colors = require('ansicolors') +var diffFile = path.join(__dirname, 'git-diff.txt') +var diff = fs.readFileSync(diffFile, 'utf-8') + +// @@ is not a valid js token, so when we see it, we can be sure that we are dealing with a git or svn diff +var diffRegex = /^@@[^@]+@@$/m +var diffIndRegex = /^(@@[^@]+@@)(.*)$/ +var addRemRegex = /^[+-]/ +var lines = diff.split('\n') + +function isDiff(lines) { + return !!lines + .filter(function(line) { + return diffRegex.test(line) + }) + .length +} + +diff = isDiff(lines) + +function tryHighlight(code) { + // TODO: need to remove symbols added to get valid code + // this should be done by getting the splits instead of the actual code from the highlighter + // now we can remove first / last one after highlighting completed + function tryAppending(appended, tryNext) { + try { + return highlighter.highlight(code + appended) + } catch (e) { + return tryNext(code) + } + } + + function tryRemoveLeadingComma(tryNext) { + var success + try { + success = highlighter.highlight(code.replace(/^( +),(.+)$/, '$1 $2')) + return success + } catch (e) { + return tryNext(code) + } + } + + function tryPlain() { + try { + return highlighter.highlight(code) + } catch (e) { + return tryCloseMustache() + } + } + + function tryCloseMustache() { return tryAppending('}', tryCloseParen) } + + function tryCloseParen() { return tryAppending('\\)', tryCloseMustacheParen) } + + function tryCloseMustacheParen() { return tryAppending('})', tryRemovingCommas) } + + function tryRemovingCommas() { return tryRemoveLeadingComma(giveUp) } + + function giveUp() { return code } + + return tryPlain() +} + +function highlightDiffInd(line, matches) { + var highlighted = colors.brightBlue(matches[1]) + var code = matches[2] + return code ? highlighted + tryHighlight(code) : highlighted +} + +function colorsAddRemove(c) { + return addRemRegex.test(c) ? colors.yellow(c) : c +} + +function highlightDiff(line) { + var diffIndMatches = diffIndRegex.exec(line) + + return diffIndMatches + ? highlightDiffInd(line, diffIndMatches) + : colorsAddRemove(line[0]) + tryHighlight(line.slice(1)) +} + +var highlightFn = diff ? highlightDiff : tryHighlight +var highlightedLines = lines.map(highlightFn) + +console.log(highlightedLines.join('\n')) diff --git a/node_modules/cardinal/examples/highlight-json.js b/node_modules/cardinal/examples/highlight-json.js new file mode 100644 index 0000000..b0d5387 --- /dev/null +++ b/node_modules/cardinal/examples/highlight-json.js @@ -0,0 +1,11 @@ +// This file will highlight the passed code using the custom theme when run via: "node highlight-json" +'use strict' + +var cardinal = require('..') + +var json = JSON.stringify({ + foo: 'bar', + baz: 'quux' +}) + +console.log(cardinal.highlight(json)) diff --git a/node_modules/cardinal/examples/highlight-self-hide-semicolons.js b/node_modules/cardinal/examples/highlight-self-hide-semicolons.js new file mode 100644 index 0000000..9d48c88 --- /dev/null +++ b/node_modules/cardinal/examples/highlight-self-hide-semicolons.js @@ -0,0 +1,22 @@ + /* + * This file will highlight itself using a custom theme when run via: "node highlight-self-hide-semicolons" + * The custom theme highlights semicolons as 'black', thus hiding them. + */ +'use strict' + +var cardinal = require('..') +var hideSemicolonsTheme = require('../themes/hide-semicolons') + +function highlight() { + // Using the synchronous highlightFileSync() + // For asynchronous highlighting use: highlightFile() - see highlight-self.js + + try { + var highlighted = cardinal.highlightFileSync(__filename, {theme: hideSemicolonsTheme}) + console.log(highlighted) + } catch (err) { + console.error(err) + } +} + +highlight() diff --git a/node_modules/cardinal/examples/highlight-self.js b/node_modules/cardinal/examples/highlight-self.js new file mode 100644 index 0000000..814d89a --- /dev/null +++ b/node_modules/cardinal/examples/highlight-self.js @@ -0,0 +1,16 @@ +// This file will highlight itself using the default theme when run via: "node highlight-self" +'use strict' + +var cardinal = require('..') + +function highlight() { + // Using the asynchronous highlightFile() + // For synchronous highlighting use: highlightFileSync() - see highlight-self-hide-semicolons.js + + cardinal.highlightFile(__filename, { linenos: true }, function(err, res) { + if (err) return console.error(err) + console.log(res) + }) +} + +highlight() diff --git a/node_modules/cardinal/examples/highlight-string.js b/node_modules/cardinal/examples/highlight-string.js new file mode 100644 index 0000000..7f444a5 --- /dev/null +++ b/node_modules/cardinal/examples/highlight-string.js @@ -0,0 +1,15 @@ +// This file will highlight the passed code using the custom theme when run via: "node highlight-string" +'use strict' + +var cardinal = require('..') + +var code = '' + + +function add(a, b) { + var sum = a + b + return sum +} + + +'' + +console.log(cardinal.highlight(code)) diff --git a/node_modules/cardinal/package.json b/node_modules/cardinal/package.json new file mode 100644 index 0000000..1cf81fd --- /dev/null +++ b/node_modules/cardinal/package.json @@ -0,0 +1,47 @@ +{ + "name": "cardinal", + "version": "2.1.1", + "description": "Syntax highlights JavaScript code with ANSI colors to be printed to the terminal.", + "main": "cardinal.js", + "scripts": { + "test": "npm run run-test && npm run lint", + "run-test": "tape test/*.js", + "lint": "standart", + "lint-fix": "standart --fix", + "demo": "node examples/highlight-string.js; node examples/highlight-self; node examples/highlight-self-hide-semicolons;" + }, + "bin": { + "cdl": "./bin/cdl.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/thlorenz/cardinal.git" + }, + "keywords": [ + "syntax", + "highlight", + "theme", + "javascript", + "json", + "terminal", + "console", + "print", + "output" + ], + "author": "Thorsten Lorenz (thlorenz.com)", + "license": "MIT", + "dependencies": { + "ansicolors": "~0.3.2", + "redeyed": "~2.1.0" + }, + "devDependencies": { + "readdirp": "~2.1.0", + "standart": "~6.1.0", + "tape": "~4.9.0" + }, + "standart": { + "ignore": [ + "test/fixtures" + ] + } +} diff --git a/node_modules/cardinal/settings.js b/node_modules/cardinal/settings.js new file mode 100644 index 0000000..e17f382 --- /dev/null +++ b/node_modules/cardinal/settings.js @@ -0,0 +1,53 @@ +'use strict' + +var path = require('path') +var fs = require('fs') +var utl = require('./utl') +var home = process.env.HOME +var settings + +function getSettings(home_) { + if (settings) return settings + var settingsJson + try { + settingsJson = fs.readFileSync(path.join(home_ || home, '.cardinalrc'), 'utf-8') + } catch (_) { + // no .cardinalrc found - not a problem + return undefined + } + try { + return JSON.parse(settingsJson) + } catch (e) { + // Have a .cardinalrc, but something about it is wrong - warn the user + // Coudn't parse the contained JSON + console.error(e) + return undefined + } +} + +// home_ mainly to be used during tests +// Resolves the preferred theme from the .cardinalrc found in the HOME directory +// If it couldn't be resolved, undefined is returned +function resolveTheme(home_) { + var themePath + var settings = getSettings(home_) + + if (!settings || !settings.theme) return undefined + + try { + // allow specifying just the name of a built-in theme or a full path to a custom theme + themePath = utl.isPath(settings.theme) ? settings.theme : path.join(__dirname, 'themes', settings.theme) + + return require(themePath) + } catch (e) { + // Specified theme path is invalid + console.error(e) + return undefined + } +} + +module.exports = { + resolveTheme: resolveTheme + , getSettings: getSettings +} + diff --git a/node_modules/cardinal/test/cardinal-highlight-block-comment.js b/node_modules/cardinal/test/cardinal-highlight-block-comment.js new file mode 100644 index 0000000..394e22f --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-block-comment.js @@ -0,0 +1,22 @@ +'use strict' + +/* eslint-disable no-path-concat */ + +var test = require('tape') +var fs = require('fs') +var customTheme = require('./fixtures/custom') +var cardinal = require('..') + +test('\nhighlighting a block comment without line numbers', function(t) { + var code = fs.readFileSync(__dirname + '/fixtures/block-comment.js', 'utf8') + var highlighted = cardinal.highlight(code, { theme: customTheme }) + t.equal(highlighted, '\n\u001b[90m/**\n * This is a meaningless block jsdoc for a meaningless function.\n * Joins two strings, separating them to appear on two lines.\n * \n * @name foo\n * @function\n * @param uno {String} first string\n * @param dos {String} second string\n * @return {String} result of the join\n */\u001b[39m\n\u001b[96mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[96mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m \u001b[90m(\u001b[39m\u001b[96muno\u001b[39m\u001b[32m,\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n \u001b[31mreturn\u001b[39m \u001b[96muno\u001b[39m \u001b[93m+\u001b[39m \u001b[92m\'\\n\'\u001b[39m \u001b[93m+\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m;\u001b[39m\n\u001b[33m}\u001b[39m\n') + t.end() +}) + +test('\nhighlighting a block comment with line numbers', function(t) { + var code = fs.readFileSync(__dirname + '/fixtures/block-comment.js', 'utf8') + var highlighted = cardinal.highlight(code, { theme: customTheme, linenos: true }) + t.equal(highlighted, '\u001b[90m 1: \n\u001b[90m 2: \u001b[90m/**\n\u001b[90m 3: * This is a meaningless block jsdoc for a meaningless function.\n\u001b[90m 4: * Joins two strings, separating them to appear on two lines.\n\u001b[90m 5: * \n\u001b[90m 6: * @name foo\n\u001b[90m 7: * @function\n\u001b[90m 8: * @param uno {String} first string\n\u001b[90m 9: * @param dos {String} second string\n\u001b[90m10: * @return {String} result of the join\n\u001b[90m11: */\u001b[39m\n\u001b[90m12: \u001b[96mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[96mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m \u001b[90m(\u001b[39m\u001b[96muno\u001b[39m\u001b[32m,\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m13: \u001b[31mreturn\u001b[39m \u001b[96muno\u001b[39m \u001b[93m+\u001b[39m \u001b[92m\'\\n\'\u001b[39m \u001b[93m+\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m14: \u001b[33m}\u001b[39m') + t.end() +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-file-async.js b/node_modules/cardinal/test/cardinal-highlight-file-async.js new file mode 100644 index 0000000..0b37fe3 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-file-async.js @@ -0,0 +1,42 @@ +'use strict' + +/* eslint-disable no-path-concat */ + +var test = require('tape') +var path = require('path') +var customTheme = require('./fixtures/custom') +var cardinal = require('..') + +var file = path.join(__dirname, 'fixtures/foo.js') +var fileWithErrors = path.join(__dirname, 'fixtures/foo-with-errors.js') + +test('supplying custom theme', function(t) { + cardinal.highlightFile(file, { theme: customTheme }, function(err, highlighted) { + t.equals(null, err, 'no error') + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n') + t.end() + }) +}) + +test('not supplying custom theme', function(t) { + cardinal.highlightFile(file, function(err, highlighted) { + t.equals(null, err, 'no error') + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n') + t.end() + }) +}) + +test('syntactically invalid code', function(t) { + cardinal.highlightFile(fileWithErrors, function(err, highlighted) { + t.equals(null, err, 'no error') + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m\n') + t.end() + }) +}) + +test('non existing file', function(t) { + cardinal.highlightFile('./not/existing', function(err, highlighted) { + t.ok((/ENOENT. .*not.existing/).test(err.message)) + t.end() + }) +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-file-sync.js b/node_modules/cardinal/test/cardinal-highlight-file-sync.js new file mode 100644 index 0000000..7aba881 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-file-sync.js @@ -0,0 +1,40 @@ +'use strict' + +/* eslint-disable no-path-concat */ + +var test = require('tape') +var path = require('path') +var customTheme = require('./fixtures/custom') +var cardinal = require('..') + +var file = path.join(__dirname, 'fixtures/foo.js') +var fileWithErrors = path.join(__dirname, 'fixtures/foo-with-errors.js') + +test('supplying custom theme', function(t) { + var highlighted = cardinal.highlightFileSync(file, { theme: customTheme }) + + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n') + t.end() +}) + +test('not supplying custom theme', function(t) { + var highlighted = cardinal.highlightFileSync(file) + + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n') + t.end() +}) + +test('syntactically invalid code', function(t) { + var highlighted = cardinal.highlightFileSync(fileWithErrors) + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m\n') + t.end() +}) + +test('non existing file', function(t) { + try { + cardinal.highlightFileSync('./not/existing') + } catch (e) { + t.ok((/ENOENT. .*not.existing/).test(e.message)) + t.end() + } +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-json-file-async.js b/node_modules/cardinal/test/cardinal-highlight-json-file-async.js new file mode 100644 index 0000000..d7c539f --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-json-file-async.js @@ -0,0 +1,15 @@ +'use strict' + +var test = require('tape') +var path = require('path') +var cardinal = require('..') + +var file = path.join(__dirname, 'fixtures/json.json') + +test('without custom theme', function(t) { + cardinal.highlightFile(file, function(err, highlighted) { + t.equals(null, err, 'no error') + t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m') + t.end() + }) +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-json-file-sync.js b/node_modules/cardinal/test/cardinal-highlight-json-file-sync.js new file mode 100644 index 0000000..0e94eb4 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-json-file-sync.js @@ -0,0 +1,14 @@ +'use strict' + +var test = require('tape') +var path = require('path') +var cardinal = require('..') + +var file = path.join(__dirname, 'fixtures/json.json') + +test('without custom theme', function(t) { + var highlighted = cardinal.highlightFileSync(file) + + t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m') + t.end() +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-json.js b/node_modules/cardinal/test/cardinal-highlight-json.js new file mode 100644 index 0000000..8abdd80 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-json.js @@ -0,0 +1,32 @@ +'use strict' + +var test = require('tape') +var customTheme = require('./fixtures/custom') +var cardinal = require('..') + +var json = JSON.stringify({ + foo: 'bar', + baz: 'quux', + bam: null +}) + +test('supplying custom theme', function(t) { + var highlighted = cardinal.highlight(json, { theme: customTheme }) + + t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[92m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[92m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[92m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m') + t.end() +}) + +test('not supplying custom theme', function(t) { + var highlighted = cardinal.highlight(json) + + t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m') + t.end() +}) + +test('with the obsoleted json option (ignored)', function(t) { + var highlighted = cardinal.highlight(json, { json: true }) + + t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m') + t.end() +}) diff --git a/node_modules/cardinal/test/cardinal-highlight-string.js b/node_modules/cardinal/test/cardinal-highlight-string.js new file mode 100644 index 0000000..3483257 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-highlight-string.js @@ -0,0 +1,61 @@ +'use strict' + +var test = require('tape') +var customTheme = require('./fixtures/custom') +var cardinal = require('..') + +var code = 'function foo() { var a = 3; return a > 2 ? true : false; }' +var codeWithErrors = 'function () { var a = 3; return a > 2 ? true : false; }' + +test('supplying custom theme', function(t) { + var highlighted = cardinal.highlight(code, { theme: customTheme }) + + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m') + t.end() +}) + +test('not supplying custom theme', function(t) { + var highlighted = cardinal.highlight(code) + + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m') + t.end() +}) + +test('syntactically invalid code', function(t) { + var highlighted = cardinal.highlight(codeWithErrors) + + t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m') + t.end() +}) + +test('line numbers no firstline given', function(t) { + var highlighted = cardinal.highlight(code, { linenos: true }) + t.equals(highlighted, '\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m') + t.end() +}) + +test('line numbers firstline 99', function(t) { + var highlighted = cardinal.highlight(code, { linenos: true, firstline: 99 }) + t.equals(highlighted, '\u001b[90m99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m') + t.end() +}) + +test('line numbers multi line no first line given', function(t) { + var multilineCode = '' + +function foo() { + return 1 +} + var highlighted = cardinal.highlight(multilineCode, { linenos: true }) + t.equals(highlighted, '\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m2: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\n\u001b[90m3: \u001b[33m}\u001b[39m') + t.end() +}) + +test('line numbers multi line first line 99', function(t) { + var multilineCode = '' + +function foo() { + return 1 +} + var highlighted = cardinal.highlight(multilineCode, { linenos: true, firstline: 99 }) + t.equals(highlighted, '\u001b[90m 99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m100: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\n\u001b[90m101: \u001b[33m}\u001b[39m') + t.end() +}) diff --git a/node_modules/cardinal/test/cardinal-smoke.js b/node_modules/cardinal/test/cardinal-smoke.js new file mode 100644 index 0000000..efd7a88 --- /dev/null +++ b/node_modules/cardinal/test/cardinal-smoke.js @@ -0,0 +1,37 @@ +'use strict' + +// applying esprima to a bunch of files of contained libraries as a smoke test +var test = require('tape') +var path = require('path') +var fs = require('fs') +var readdirp = require('readdirp') +var cardinal = require('..') +var nodeModules = path.join(__dirname, '..', 'node_modules') +var tapedir = path.join(nodeModules, 'tape') +var redeyeddir = path.join(nodeModules, 'redeyed') + +test('tape', function(t) { + readdirp({ root: tapedir, fileFilter: '*.js' }) + .on('data', function(entry) { + var code = fs.readFileSync(entry.fullPath, 'utf-8') + var result = cardinal.highlight(code) + + if (!(/^[^/*]*var /.test(code))) { + t.pass('skipping ' + entry.path + ' due to missing var statement') + } else { + t.assert(~result.indexOf('[32mvar\u001b[39m'), 'highlighted ' + entry.path) + } + }) + .on('end', t.end.bind(t)) +}) + +test('redeyed', function(t) { + readdirp({ root: redeyeddir, fileFilter: 'redeyed.js' }) + .on('data', function(entry) { + var code = fs.readFileSync(entry.fullPath, 'utf-8') + var result = cardinal.highlight(code) + + t.assert(~result.indexOf('[32mvar\u001b[39m') || !(~result.indexOf('var ')), 'highlighted ' + entry.path) + }) + .on('end', t.end.bind(t)) +}) diff --git a/node_modules/cardinal/test/fixtures/block-comment.js b/node_modules/cardinal/test/fixtures/block-comment.js new file mode 100644 index 0000000..597bc69 --- /dev/null +++ b/node_modules/cardinal/test/fixtures/block-comment.js @@ -0,0 +1,14 @@ + +/** + * This is a meaningless block jsdoc for a meaningless function. + * Joins two strings, separating them to appear on two lines. + * + * @name foo + * @function + * @param uno {String} first string + * @param dos {String} second string + * @return {String} result of the join + */ +module.exports = function foo (uno, dos) { + return uno + '\n' + dos; +} diff --git a/node_modules/cardinal/test/fixtures/custom.js b/node_modules/cardinal/test/fixtures/custom.js new file mode 100644 index 0000000..fc369fc --- /dev/null +++ b/node_modules/cardinal/test/fixtures/custom.js @@ -0,0 +1,144 @@ +var colors = require('ansicolors'); + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + // changed from default + 'true' : colors.red + + , 'false' : undefined + , _default : colors.brightRed + } + + , 'Identifier': { + 'undefined' : colors.brightBlack + , 'self' : colors.brightRed + , 'console' : colors.blue + , 'log' : colors.blue + , 'warn' : colors.red + , 'error' : colors.brightRed + // + // changed from default + , _default : colors.brightCyan + } + + , 'Null': { + _default: colors.brightBlack + } + + , 'Numeric': { + _default: colors.blue + } + + , 'String': { + _default: colors.brightGreen + } + + , 'Keyword': { + 'break' : undefined + + , 'case' : undefined + , 'catch' : colors.cyan + , 'continue' : undefined + + , 'debugger' : undefined + , 'default' : undefined + , 'delete' : colors.red + , 'do' : undefined + + , 'else' : undefined + + , 'finally' : colors.cyan + , 'for' : undefined + , 'function' : undefined + + , 'if' : undefined + , 'in' : undefined + , 'instanceof' : undefined + + , 'new' : colors.red + , 'return' : colors.red + , 'switch' : undefined + + , 'this' : colors.brightRed + , 'throw' : undefined + , 'try' : colors.cyan + , 'typeof' : undefined + + , 'var' : colors.green + , 'void' : undefined + + , 'while' : undefined + , 'with' : undefined + , _default : colors.brightBlue + } + , 'Punctuator': { + ';': colors.brightBlack + , '.': colors.green + , ',': colors.green + + , '{': colors.yellow + , '}': colors.yellow + , '(': colors.brightBlack + , ')': colors.brightBlack + , '[': colors.yellow + , ']': colors.yellow + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': undefined + , '^': undefined + , '!': undefined + , '~': undefined + , '?': undefined + , ':': undefined + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + + , '>>>=': undefined + + , _default: colors.brightYellow + } + + // line comment + , Line: { + _default: colors.brightBlack + } + + /* block comment */ + , Block: { + _default: colors.brightBlack + } + + , _default: undefined +}; diff --git a/node_modules/cardinal/test/fixtures/foo-with-errors.js b/node_modules/cardinal/test/fixtures/foo-with-errors.js new file mode 100644 index 0000000..fefebe2 --- /dev/null +++ b/node_modules/cardinal/test/fixtures/foo-with-errors.js @@ -0,0 +1,3 @@ +function () { + var a = 3; return a > 2 ? true : false; +}; diff --git a/node_modules/cardinal/test/fixtures/foo.js b/node_modules/cardinal/test/fixtures/foo.js new file mode 100644 index 0000000..bd9a3e0 --- /dev/null +++ b/node_modules/cardinal/test/fixtures/foo.js @@ -0,0 +1,3 @@ +function foo() { + var a = 3; return a > 2 ? true : false; +} diff --git a/node_modules/cardinal/test/fixtures/json.json b/node_modules/cardinal/test/fixtures/json.json new file mode 100644 index 0000000..0c39df4 --- /dev/null +++ b/node_modules/cardinal/test/fixtures/json.json @@ -0,0 +1 @@ +{"foo":"bar","baz":"quux","bam":null} \ No newline at end of file diff --git a/node_modules/cardinal/test/fixtures/svn-diff.txt b/node_modules/cardinal/test/fixtures/svn-diff.txt new file mode 100644 index 0000000..635b056 --- /dev/null +++ b/node_modules/cardinal/test/fixtures/svn-diff.txt @@ -0,0 +1,23 @@ +Index: grunt.js +=================================================================== +--- grunt.js (revision 31200) ++++ grunt.js (working copy) +@@ -12,6 +12,7 @@ + + module.exports = function (grunt) { + ++ console.log('hello world'); + // Project configuration. + grunt.initConfig({ + lint: { +@@ -19,10 +20,6 @@ + 'packages/services.web/{!(test)/**/,}*.js', + 'packages/error/**/*.js' + ], +- scripts: [ +- 'grunt.js', +- 'db/**/*.js' +- ], + browser: [ + 'packages/web/server.js', + 'packages/web/server/**/*.js', diff --git a/node_modules/cardinal/test/settings.js b/node_modules/cardinal/test/settings.js new file mode 100644 index 0000000..9e7d004 --- /dev/null +++ b/node_modules/cardinal/test/settings.js @@ -0,0 +1,77 @@ +'use strict' +/* jshint asi: true */ + +var test = require('tape') +var path = require('path') +var fs = require('fs') +var hideSemicolonsTheme = require('../themes/hide-semicolons') +var home = path.join(__dirname, 'fixtures', 'home') +var rcpath = path.join(home, '.cardinalrc') +var existsSync = fs.existsSync || path.existsSync +var settingsResolve = require.resolve('../settings') +var settings + +function setup() { + delete require.cache[settingsResolve] + settings = require(settingsResolve) +} + +function writerc(config) { + fs.writeFileSync(rcpath, JSON.stringify(config), 'utf-8') +} + +function removerc() { + fs.unlinkSync(rcpath) +} + +function resolveTheme(config) { + writerc(config) + var result = settings.resolveTheme(home) + removerc() + return result +} + +function getSettings(config) { + writerc(config) + var result = settings.getSettings(home) + removerc() + return result +} + +if (!existsSync(home)) fs.mkdirSync(home) + +test('no .cardinalrc in home', function(t) { + setup() + var theme = settings.resolveTheme(home) + t.equals(theme, undefined, 'resolves no theme') + t.end() +}) + +test('.cardinalrc with theme "hide-semicolons" in home', function(t) { + setup() + var theme = resolveTheme({ theme: 'hide-semicolons' }) + t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme') + t.end() +}) + +test('.cardinalrc with full path to "hide-semicolons.js" in home', function(t) { + setup() + var theme = resolveTheme({ theme: path.join(__dirname, '..', 'themes', 'hide-semicolons.js') }) + t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme') + t.end() +}) + +test('.cardinalrc with linenos: true', function(t) { + setup() + var opts = { linenos: true } + t.deepEquals(getSettings(opts), opts) + t.end() +}) + +test('.cardinalrc with linenos: true and theme', function(t) { + setup() + var opts = { linenos: true, theme: 'some theme' } + t.deepEquals(getSettings(opts), opts) + t.end() +}) + diff --git a/node_modules/cardinal/test/themes.js b/node_modules/cardinal/test/themes.js new file mode 100644 index 0000000..0f3f5ad --- /dev/null +++ b/node_modules/cardinal/test/themes.js @@ -0,0 +1,22 @@ +'use strict' +/* jshint asi: true */ + +var test = require('tape') +var path = require('path') +var fs = require('fs') +var themesdir = path.join(__dirname, '..', 'themes') +var allFiles = fs.readdirSync(themesdir) + +test('validate themes by requiring all of them', function(t) { + allFiles + .filter(function(file) { return path.extname(file) === '.js' }) + .forEach(function(theme) { + try { + t.ok(require(path.join(themesdir, theme)), theme + ' is valid') + } catch (e) { + t.fail('theme: ' + theme + ' is invalid! ' + e.message) + } + }) + t.end() +}) + diff --git a/node_modules/cardinal/themes/README.md b/node_modules/cardinal/themes/README.md new file mode 100644 index 0000000..fe2a443 --- /dev/null +++ b/node_modules/cardinal/themes/README.md @@ -0,0 +1,31 @@ +# cardinal themes + +These are the built in themes that come with cardinal. + +You can create more themes by copying and then editing the [empty +theme](https://github.com/thlorenz/cardinal/blob/master/themes/empty.js) which is provided for that purpose. + +The [hide semicolons theme](https://github.com/thlorenz/cardinal/blob/master/themes/hide-semicolons.js) has the added +benefit of making all semicolons invisible. This makes code more readable at times. + +Find out how to change the theme used by cardinal [here](https://github.com/thlorenz/cardinal#theme). + +# sharing themes + +To add your theme to the cardinal built-in themes, follow the below steps: + +1. fork the cardinal repository +2. add your theme to the themes folder and commit your changes +3. create a pull request + +If you believe that your theme is better than the current default theme, let me know by creating an issue. + +This will allow others to cast their vote. If enough people agree, your theme will be promoted to be the default. + +## Contributed Themes + +### tomorrow night + +[![tomorrow-night](https://github.com/thlorenz/cardinal/raw/master/assets/theme-tomorrow-night.png)](https://github.com/thlorenz/cardinal/blob/master/themes/tomorrow-night.js) + +*by [firede](https://github.com/firede)* diff --git a/node_modules/cardinal/themes/default.js b/node_modules/cardinal/themes/default.js new file mode 100644 index 0000000..3d096e7 --- /dev/null +++ b/node_modules/cardinal/themes/default.js @@ -0,0 +1,201 @@ +var colors = require('ansicolors') + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + 'true' : undefined + , 'false' : undefined + , _default : colors.brightRed + } + + , 'Identifier': { + 'undefined' : colors.brightBlack + , 'self' : colors.brightRed + , 'console' : colors.blue + , 'log' : colors.blue + , 'warn' : colors.red + , 'error' : colors.brightRed + , _default : colors.white + } + + , 'Null': { + _default: colors.brightBlack + } + + , 'Numeric': { + _default: colors.blue + } + + , 'String': { + _default: function(s, info) { + var nextToken = info.tokens[info.tokenIndex + 1] + + // show keys of object literals and json in different color + return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':') + ? colors.green(s) + : colors.brightGreen(s) + } + } + + , 'Keyword': { + 'break' : undefined + + , 'case' : undefined + , 'catch' : colors.cyan + , 'class' : undefined + , 'const' : undefined + , 'continue' : undefined + + , 'debugger' : undefined + , 'default' : undefined + , 'delete' : colors.red + , 'do' : undefined + + , 'else' : undefined + , 'enum' : undefined + , 'export' : undefined + , 'extends' : undefined + + , 'finally' : colors.cyan + , 'for' : undefined + , 'function' : undefined + + , 'if' : undefined + , 'implements' : undefined + , 'import' : undefined + , 'in' : undefined + , 'instanceof' : undefined + , 'let' : undefined + , 'new' : colors.red + , 'package' : undefined + , 'private' : undefined + , 'protected' : undefined + , 'public' : undefined + , 'return' : colors.red + , 'static' : undefined + , 'super' : undefined + , 'switch' : undefined + + , 'this' : colors.brightRed + , 'throw' : undefined + , 'try' : colors.cyan + , 'typeof' : undefined + + , 'var' : colors.green + , 'void' : undefined + + , 'while' : undefined + , 'with' : undefined + , 'yield' : undefined + , _default : colors.brightBlue + } + , 'Punctuator': { + ';': colors.brightBlack + , '.': colors.green + , ',': colors.green + + , '{': colors.yellow + , '}': colors.yellow + , '(': colors.brightBlack + , ')': colors.brightBlack + , '[': colors.yellow + , ']': colors.yellow + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': undefined + , '^': undefined + , '!': undefined + , '~': undefined + , '?': undefined + , ':': undefined + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + , '=>': undefined + , '**': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + , '...': undefined + , '**=': undefined + + , '>>>=': undefined + + , _default: colors.brightYellow + } + + // line comment + , Line: { + _default: colors.brightBlack + } + + /* block comment */ + , Block: { + _default: colors.brightBlack + } + + // JSX + , JSXAttribute: { + _default: colors.magenta + } + , JSXClosingElement: { + _default: colors.magenta + } + , JSXElement: { + _default: colors.magenta + } + , JSXEmptyExpression: { + _default: colors.magenta + } + , JSXExpressionContainer: { + _default: colors.magenta + } + , JSXIdentifier: { + className: colors.blue + , _default: colors.magenta + } + , JSXMemberExpression: { + _default: colors.magenta + } + , JSXNamespacedName: { + _default: colors.magenta + } + , JSXOpeningElement: { + _default: colors.magenta + } + , JSXSpreadAttribute: { + _default: colors.magenta + } + , JSXText: { + _default: colors.brightGreen + } + + , _default: undefined +} diff --git a/node_modules/cardinal/themes/empty.js b/node_modules/cardinal/themes/empty.js new file mode 100644 index 0000000..d3f0ea7 --- /dev/null +++ b/node_modules/cardinal/themes/empty.js @@ -0,0 +1,199 @@ +/* + * Copy this file and use it as a starting point for your custom cardinal color theme. + * Just fill in or change the entries for the tokens you want to color + * Keep in mind that more specific configurations override less specific ones. + */ + +// eslint-disable-next-line no-unused-vars +var colors = require('ansicolors') + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + 'true' : undefined + , 'false' : undefined + , _default : undefined + } + + , 'Identifier': { + _default: undefined + } + + , 'Null': { + _default: undefined + } + + , 'Numeric': { + _default: undefined + } + + , 'String': { + _default: undefined + } + + , 'Keyword': { + 'break' : undefined + + , 'case' : undefined + , 'catch' : undefined + , 'class' : undefined + , 'const' : undefined + , 'continue' : undefined + + , 'debugger' : undefined + , 'default' : undefined + , 'delete' : undefined + , 'do' : undefined + + , 'else' : undefined + , 'enum' : undefined + , 'export' : undefined + , 'extends' : undefined + + , 'finally' : undefined + , 'for' : undefined + , 'function' : undefined + + , 'if' : undefined + , 'implements' : undefined + , 'import' : undefined + , 'in' : undefined + , 'instanceof' : undefined + , 'interface' : undefined + , 'let' : undefined + , 'new' : undefined + + , 'package' : undefined + , 'private' : undefined + , 'protected' : undefined + , 'public' : undefined + + , 'return' : undefined + , 'static' : undefined + , 'super' : undefined + , 'switch' : undefined + + , 'this' : undefined + , 'throw' : undefined + , 'try' : undefined + , 'typeof' : undefined + + , 'var' : undefined + , 'void' : undefined + + , 'while' : undefined + , 'with' : undefined + , 'yield' : undefined + , _default : undefined + } + , 'Punctuator': { + ';': undefined + , '.': undefined + , ',': undefined + + , '{': undefined + , '}': undefined + , '(': undefined + , ')': undefined + , '[': undefined + , ']': undefined + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': undefined + , '^': undefined + , '!': undefined + , '~': undefined + , '?': undefined + , ':': undefined + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + , '=>': undefined + , '**': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + , '...': undefined + , '**=': undefined + + , '>>>=': undefined + + , _default: undefined + } + + // line comment + , Line: { + _default: undefined + } + + /* block comment */ + , Block: { + _default: undefined + } + + // JSX + , JSXAttribute: { + _default: undefined + } + , JSXClosingElement: { + _default: undefined + } + , JSXElement: { + _default: undefined + } + , JSXEmptyExpression: { + _default: undefined + } + , JSXExpressionContainer: { + _default: undefined + } + , JSXIdentifier: { + // many more identifies are possible, div, table, etc. + className: undefined + , _default: undefined + } + , JSXMemberExpression: { + _default: undefined + } + , JSXNamespacedName: { + _default: undefined + } + , JSXOpeningElement: { + _default: undefined + } + , JSXSpreadAttribute: { + _default: undefined + } + , JSXText: { + _default: undefined + } + + , _default: undefined +} diff --git a/node_modules/cardinal/themes/hide-semicolons.js b/node_modules/cardinal/themes/hide-semicolons.js new file mode 100644 index 0000000..0add3f1 --- /dev/null +++ b/node_modules/cardinal/themes/hide-semicolons.js @@ -0,0 +1,202 @@ +var colors = require('ansicolors') + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + 'true' : undefined + , 'false' : undefined + , _default : colors.brightRed + } + + , 'Identifier': { + 'undefined' : colors.brightBlack + , 'self' : colors.brightRed + , 'console' : colors.blue + , 'log' : colors.blue + , 'warn' : colors.red + , 'error' : colors.brightRed + , _default : colors.white + } + + , 'Null': { + _default: colors.brightBlack + } + + , 'Numeric': { + _default: colors.blue + } + + , 'String': { + _default: function(s, info) { + var nextToken = info.tokens[info.tokenIndex + 1] + + // show keys of object literals and json in different color + return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':') + ? colors.green(s) + : colors.brightGreen(s) + } + } + + , 'Keyword': { + 'break' : undefined + + , 'case' : undefined + , 'catch' : colors.cyan + , 'class' : undefined + , 'const' : undefined + , 'continue' : undefined + + , 'debugger' : undefined + , 'default' : undefined + , 'delete' : colors.red + , 'do' : undefined + + , 'else' : undefined + , 'enum' : undefined + , 'export' : undefined + , 'extends' : undefined + + , 'finally' : colors.cyan + , 'for' : undefined + , 'function' : undefined + + , 'if' : undefined + , 'implements' : undefined + , 'import' : undefined + , 'in' : undefined + , 'instanceof' : undefined + , 'let' : undefined + , 'new' : colors.red + , 'package' : undefined + , 'private' : undefined + , 'protected' : undefined + , 'public' : undefined + , 'return' : colors.red + , 'static' : undefined + , 'super' : undefined + , 'switch' : undefined + + , 'this' : colors.brightRed + , 'throw' : undefined + , 'try' : colors.cyan + , 'typeof' : undefined + + , 'var' : colors.green + , 'void' : undefined + + , 'while' : undefined + , 'with' : undefined + , 'yield' : undefined + , _default : colors.brightBlue + } + , 'Punctuator': { + // setting semicolon's color to the same as the terminal background makes it invisible + ';': colors.black + + , '.': colors.green + , ',': colors.green + + , '{': colors.yellow + , '}': colors.yellow + , '(': colors.brightBlack + , ')': colors.brightBlack + , '[': colors.yellow + , ']': colors.yellow + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': undefined + , '^': undefined + , '!': undefined + , '~': undefined + , '?': undefined + , ':': undefined + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + , '=>': undefined + , '**': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + , '...': undefined + , '**=': undefined + + , '>>>=': undefined + + , _default: colors.brightYellow + } + + // line comment + , Line: { + _default: colors.brightBlack + } + + /* block comment */ + , Block: { + _default: colors.brightBlack + } + + // JSX + , JSXAttribute: { + _default: colors.magenta + } + , JSXClosingElement: { + _default: colors.magenta + } + , JSXElement: { + _default: colors.magenta + } + , JSXEmptyExpression: { + _default: colors.magenta + } + , JSXExpressionContainer: { + _default: colors.magenta + } + , JSXIdentifier: { + className: colors.blue + , _default: colors.magenta + } + , JSXMemberExpression: { + _default: colors.magenta + } + , JSXNamespacedName: { + _default: colors.magenta + } + , JSXOpeningElement: { + _default: colors.magenta + } + , JSXSpreadAttribute: { + _default: colors.magenta + } + , JSXText: { + _default: colors.brightGreen + } + , _default: undefined +} diff --git a/node_modules/cardinal/themes/jq.js b/node_modules/cardinal/themes/jq.js new file mode 100644 index 0000000..877f8c2 --- /dev/null +++ b/node_modules/cardinal/themes/jq.js @@ -0,0 +1,169 @@ +var colors = require('ansicolors') + +// mimics [jq](https://stedolan.github.io/jq/) highlighting for json files +// mainly in the fact that the keys are a clearly different color than the strings +// However improvements to this theme are highly welcome! :) + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + 'true' : undefined + , 'false' : undefined + , _default : colors.brightRed + } + + , 'Identifier': { + 'undefined' : colors.brightBlack + , 'self' : colors.brightRed + , 'console' : colors.blue + , 'log' : colors.blue + , 'warn' : colors.red + , 'error' : colors.brightRed + , _default : colors.white + } + + , 'Null': { + _default: colors.brightBlack + } + + , 'Numeric': { + _default: colors.blue + } + + , 'String': { + _default: function(s, info) { + var nextToken = info.tokens[info.tokenIndex + 1] + + // show keys of object literals and json in different color + return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':') + ? colors.brightBlue(s) + : colors.brightGreen(s) + } + } + + , 'Keyword': { + 'break' : undefined + + , 'case' : undefined + , 'catch' : colors.cyan + , 'class' : undefined + , 'const' : undefined + , 'continue' : undefined + + , 'debugger' : undefined + , 'default' : undefined + , 'delete' : colors.red + , 'do' : undefined + + , 'else' : undefined + , 'enum' : undefined + , 'export' : undefined + , 'extends' : undefined + + , 'finally' : colors.cyan + , 'for' : undefined + , 'function' : undefined + + , 'if' : undefined + , 'implements' : undefined + , 'import' : undefined + , 'in' : undefined + , 'instanceof' : undefined + , 'let' : undefined + , 'new' : colors.red + , 'package' : undefined + , 'private' : undefined + , 'protected' : undefined + , 'public' : undefined + , 'return' : colors.red + , 'static' : undefined + , 'super' : undefined + , 'switch' : undefined + + , 'this' : colors.brightRed + , 'throw' : undefined + , 'try' : colors.cyan + , 'typeof' : undefined + + , 'var' : colors.green + , 'void' : undefined + + , 'while' : undefined + , 'with' : undefined + , 'yield' : undefined + , _default : colors.brightBlue + } + , 'Punctuator': { + ';': colors.brightBlack + , '.': colors.green + , ',': colors.green + + , '{': colors.brightWhite + , '}': colors.brightWhite + , '(': colors.brightBlack + , ')': colors.brightBlack + , '[': colors.brightWhite + , ']': colors.brightWhite + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': undefined + , '^': undefined + , '!': undefined + , '~': undefined + , '?': undefined + , ':': undefined + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + , '=>': undefined + , '**': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + , '...': undefined + , '**=': undefined + + , '>>>=': undefined + + , _default: colors.brightYellow + } + + // line comment + , Line: { + _default: colors.brightBlack + } + + /* block comment */ + , Block: { + _default: colors.brightBlack + } + + , _default: undefined +} diff --git a/node_modules/cardinal/themes/tomorrow-night.js b/node_modules/cardinal/themes/tomorrow-night.js new file mode 100644 index 0000000..6b1c2d4 --- /dev/null +++ b/node_modules/cardinal/themes/tomorrow-night.js @@ -0,0 +1,215 @@ +var colors = require('ansicolors') + +// Change the below definitions in order to tweak the color theme. +module.exports = { + + 'Boolean': { + 'true' : undefined + , 'false' : undefined + , _default : colors.yellow + } + + , 'Identifier': { + 'undefined' : colors.yellow + , 'self' : colors.yellow + , 'type' : colors.yellow + , 'value' : colors.yellow + , 'console' : undefined + , 'log' : colors.blue + , 'warn' : colors.blue + , 'error' : colors.blue + , 'join' : colors.blue + , _default : function(s, info) { + var prevToken = info.tokens[info.tokenIndex - 1] + var nextToken = info.tokens[info.tokenIndex + 1] + + return (nextToken + && nextToken.type === 'Punctuator' + && nextToken.value === '(' + && prevToken + && prevToken.type === 'Keyword' + && prevToken.value === 'function' + ) ? colors.blue(s) : colors.white(s) + } + } + + , 'Null': { + _default: colors.yellow + } + + , 'Numeric': { + _default: colors.yellow + } + + , 'String': { + _default: function(s, info) { + var nextToken = info.tokens[info.tokenIndex + 1] + + // show keys of object literals and json in different color + return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':') + ? colors.green(s) + : colors.brightGreen(s) + } + } + + , 'Keyword': { + 'break' : colors.magenta + + , 'case' : colors.magenta + , 'catch' : colors.magenta + , 'class' : undefined + , 'const' : undefined + , 'continue' : colors.magenta + + , 'debugger' : colors.magenta + , 'default' : colors.magenta + , 'delete' : colors.red + , 'do' : colors.magenta + + , 'else' : colors.magenta + , 'enum' : undefined + , 'export' : undefined + , 'extends' : undefined + + , 'finally' : colors.magenta + , 'for' : colors.magenta + , 'function' : colors.magenta + + , 'if' : colors.magenta + , 'implements' : undefined + , 'import' : undefined + , 'in' : colors.cyan + , 'instanceof' : colors.cyan + , 'let' : undefined + , 'new' : colors.cyan + , 'package' : undefined + , 'private' : undefined + , 'protected' : undefined + , 'public' : undefined + , 'return' : colors.magenta + , 'static' : undefined + , 'super' : undefined + , 'switch' : colors.magenta + + , 'this' : colors.red + , 'throw' : colors.magenta + , 'try' : colors.magenta + , 'typeof' : colors.cyan + + , 'var' : colors.magenta + , 'void' : colors.magenta + + , 'while' : colors.magenta + , 'with' : colors.cyan + , 'yield' : undefined + , _default : colors.white + } + , 'Punctuator': { + ';': colors.white + , '.': colors.white + , ',': colors.white + + , '{': colors.white + , '}': colors.white + , '(': colors.white + , ')': colors.white + , '[': colors.white + , ']': colors.white + + , '<': undefined + , '>': undefined + , '+': undefined + , '-': undefined + , '*': undefined + , '%': undefined + , '&': undefined + , '|': colors.white + , '^': undefined + , '!': undefined + , '~': undefined + , '?': colors.white + , ':': colors.white + , '=': undefined + + , '<=': undefined + , '>=': undefined + , '==': undefined + , '!=': undefined + , '++': undefined + , '--': undefined + , '<<': undefined + , '>>': undefined + , '&&': undefined + , '||': undefined + , '+=': undefined + , '-=': undefined + , '*=': undefined + , '%=': undefined + , '&=': undefined + , '|=': undefined + , '^=': undefined + , '/=': undefined + , '=>': undefined + , '**': undefined + + , '===': undefined + , '!==': undefined + , '>>>': undefined + , '<<=': undefined + , '>>=': undefined + , '...': undefined + , '**=': undefined + + , '>>>=': undefined + + , _default: colors.cyan + } + + // line comment + , Line: { + _default: colors.brightBlack + } + + /* block comment */ + , Block: { + _default: colors.brightBlack + } + + // JSX + , JSXAttribute: { + _default: colors.magenta + } + , JSXClosingElement: { + _default: colors.magenta + } + , JSXElement: { + _default: colors.magenta + } + , JSXEmptyExpression: { + _default: colors.magenta + } + , JSXExpressionContainer: { + _default: colors.magenta + } + , JSXIdentifier: { + className: colors.blue + , _default: colors.magenta + } + , JSXMemberExpression: { + _default: colors.magenta + } + , JSXNamespacedName: { + _default: colors.magenta + } + , JSXOpeningElement: { + _default: colors.magenta + } + , JSXSpreadAttribute: { + _default: colors.magenta + } + , JSXText: { + _default: colors.brightGreen + } + + , _default: undefined +} diff --git a/node_modules/cardinal/utl.js b/node_modules/cardinal/utl.js new file mode 100644 index 0000000..737d521 --- /dev/null +++ b/node_modules/cardinal/utl.js @@ -0,0 +1,12 @@ +'use strict' + +var util = require('util') + +module.exports.isPath = function(s) { + return (/[/\\]/).test(s) +} + +module.exports.inspect = function(obj, depth) { + console.log(util.inspect(obj, false, depth || 5, true)) +} + diff --git a/node_modules/chalk/license b/node_modules/chalk/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/chalk/package.json b/node_modules/chalk/package.json new file mode 100644 index 0000000..ddcf758 --- /dev/null +++ b/node_modules/chalk/package.json @@ -0,0 +1,81 @@ +{ + "name": "chalk", + "version": "5.2.0", + "description": "Terminal string styling done right", + "license": "MIT", + "repository": "chalk/chalk", + "funding": "https://github.com/chalk/chalk?sponsor=1", + "type": "module", + "main": "./source/index.js", + "exports": "./source/index.js", + "imports": { + "#ansi-styles": "./source/vendor/ansi-styles/index.js", + "#supports-color": { + "node": "./source/vendor/supports-color/index.js", + "default": "./source/vendor/supports-color/browser.js" + } + }, + "types": "./source/index.d.ts", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "scripts": { + "test": "xo && c8 ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "source", + "!source/index.test-d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "@types/node": "^16.11.10", + "ava": "^3.15.0", + "c8": "^7.10.0", + "color-convert": "^2.0.1", + "execa": "^6.0.0", + "log-update": "^5.0.0", + "matcha": "^0.7.0", + "tsd": "^0.19.0", + "xo": "^0.53.0", + "yoctodelay": "^2.0.0" + }, + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "@typescript-eslint/consistent-type-imports": "off", + "@typescript-eslint/consistent-type-exports": "off", + "@typescript-eslint/consistent-type-definitions": "off" + } + }, + "c8": { + "reporter": [ + "text", + "lcov" + ], + "exclude": [ + "source/vendor" + ] + } +} diff --git a/node_modules/chalk/readme.md b/node_modules/chalk/readme.md new file mode 100644 index 0000000..93511c0 --- /dev/null +++ b/node_modules/chalk/readme.md @@ -0,0 +1,325 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk) +[![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) +[![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) +[![run on repl.it](https://img.shields.io/badge/Run_on_Replit-f26207?logo=replit&logoColor=white)](https://repl.it/github/chalk/chalk) + +![](media/screenshot.png) + +
+ +--- + + + +--- + +
+ +## Highlights + +- Expressive API +- Highly performant +- No dependencies +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~86,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 4, 2022 + +## Install + +```sh +npm install chalk +``` + +**IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0) + +## Usage + +```js +import chalk from 'chalk'; + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +import chalk from 'chalk'; + +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +import chalk from 'chalk'; + +const error = chalk.bold.red; +const warning = chalk.hex('#FFA500'); // Orange color + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +import chalk from 'chalk'; + +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + +## API + +### chalk.`